I'm now trying to import an array of related objects and Sanity want's a unique _key for each entry. How can I get Sanity to just pick its own key during the import?
Great news! You don't have to manually generate _key values for every array item during import. There are a couple of approaches depending on how you're importing:
If you're using sanity dataset import with NDJSON files:
You can use the --replace flag along with missing _key values, and Sanity will automatically generate them during import. However, the most reliable approach is to add the keys to your NDJSON before importing.
For programmatic imports (recommended):
The easiest solution is to use a UUID library to generate _key values as you create your array items. Here's a quick example:
import { v4 as uuidv4 } from 'uuid';
import {createClient} from '@sanity/client'
const client = createClient({...})
const document = {
_type: 'myDocument',
items: [
{
_key: uuidv4(), // Generates a unique key automatically
title: 'First item',
// ... other fields
},
{
_key: uuidv4(),
title: 'Second item',
// ... other fields
}
]
}
client.create(document)You can also use other methods to generate unique keys - they just need to be unique within the array. Some people use simple counters or slugified values, but UUIDs are the safest bet to avoid collisions.
Why _key is required:
As explained in the _key documentation, this property ensures each array item can be uniquely identified and tracked, which is crucial for Sanity's real-time collaborative editing features and proper rendering in Studio.
The key thing to remember: _key only needs to be unique within its containing array, not across your entire dataset (unlike _id for documents). So generating them on-the-fly during your import script with something like uuid is a clean, simple solution that works reliably.
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.