Can I import some utility for generate keys in same format used by sanity studio?

2 replies
Last updated: Nov 16, 2020
Hello, I'm migrating some data through sanity client using sanity exec. For collections I got this warning after importing new data:
This usually happens when items are created through the API client from outside the Content Studio and someone forgets to set the _key-property of list items.
The value of the _key can be any string as long as it is unique for each element within the array.
The message is clear, I would just like to know if I can import some utility for generate keys in same format used by sanity studio, to maintain uniformity. Thanks
AI Update

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 thread
2 replies
In the Sanity JavaScript client library documentation they use an npm package called
nanoid
to generate the keys
Now I see! Perfect, thank you

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.

Was this answer helpful?