Can I import some utility for generate keys in same format used by sanity studio?
Great question! When importing data programmatically with sanity exec, you definitely want to generate _key values for array items. While Sanity Studio automatically generates these keys, there isn't an officially documented utility function that you can import to generate keys in the exact same format.
However, the solution is straightforward: use any standard unique ID generator like uuid or nanoid. The _key property can be any unique string within the array, and Sanity doesn't enforce a specific format.
Here's the recommended approach for your migration script:
import { v4 as uuidv4 } from 'uuid';
// When creating array items in your migration
const arrayItem = {
_key: uuidv4(),
_type: 'yourType',
// ... other properties
};Or if you prefer shorter keys, you can use nanoid:
import { nanoid } from 'nanoid';
const arrayItem = {
_key: nanoid(),
_type: 'yourType',
// ... other properties
};Why this works: As explained in the Sanity documentation on _key, the _key property only needs to be unique within the scope of its containing array - it doesn't need to follow any specific format. Studio generates random strings, but any unique string generation method will work just fine and maintain consistency across your dataset.
The important thing is that each _key is:
- Unique within its array
- Consistent (don't change it once set)
- Generated reliably during your import
Both uuid and nanoid are battle-tested libraries that will ensure uniqueness and work seamlessly with Sanity's array handling, real-time collaboration features, and Studio editing.
Show original thread2 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.