Sanity "Unsupported path segment {}" error with array of references
The "Unsupported path segment {}" error you're encountering is a common issue that occurs when array items in Sanity documents are missing the required _key property. Based on the Sanity community discussions, this is exactly what's happening with your script.
The Problem
When you programmatically add items to an array field (like your codes array), each item must have a unique _key property. Sanity uses these keys internally to track array items and maintain proper document structure. Without them, the Studio can't properly render or edit the documents, resulting in the "Unsupported path segment {}" error.
The Solution
You need to ensure your script generates _key values when adding references to the codes array. You have two options:
Option 1: Use autoGenerateArrayKeys (Recommended)
When using the Sanity client to perform mutations, set the autoGenerateArrayKeys option to true:
client
.patch(documentId)
.setIfMissing({codes: []})
.append('codes', [{_type: 'reference', _ref: codeDocumentId}])
.commit({autoGenerateArrayKeys: true})Option 2: Manually Generate Keys
Alternatively, manually add unique _key values to each array item:
import {uuid} from '@sanity/uuid'
const newCodeReference = {
_type: 'reference',
_ref: codeDocumentId,
_key: uuid() // or any unique string generator
}Fixing Existing Documents
The autoGenerateArrayKeys option will only fix documents going forward. For existing documents with missing keys, you have a few approaches:
- If you have few documents: Manually add
_keyvalues to each array item through the Studio or a migration script - For many documents: Write a migration script that patches all affected documents, adding unique keys to array items
- Nuclear option: If the data isn't critical, delete and recreate the affected documents
Make sure the keys are unique within each document's array. The keys don't need to be globally unique, just unique within their parent array.
This should resolve your issue completely!
Show original thread9 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.