Auto-generate reference field from _id's last 6 characters in Sanity
You're on the right track! The best approach here is to generate the _id yourself before creating the document. This allows you to derive the reference field from the ID and include it in a single create() call—no need for a second API call or transaction.
Here's how to do it:
import {v4 as uuidv4} from 'uuid'
const customId = uuidv4() // Generate a UUID like Sanity does
const reference = customId.slice(-6).toUpperCase() // Last 6 chars, uppercased
const order = {
_id: customId,
_type: 'order',
reference: reference,
// ... other fields
}
await client.create(order)This is actually a recommended pattern for content migrations and works perfectly for your use case. Sanity allows you to specify custom _id values when creating documents—they don't have to be auto-generated.
Why this is the best approach:
- Single API call: Everything happens in one
create()operation - Atomic: The document is created with the reference field already set
- Clean: No need for transactions or patches
- Supported: Custom IDs are a documented feature—Sanity accepts any valid ID format (alphanumeric plus
.,_,-up to 128 characters)
Important notes:
- Don't use
drafts.prefix for the custom ID—that's reserved for draft documents - The
_idyou set is permanent and never changes - Make sure your IDs are unique within your dataset
- If you're creating documents in Sanity Studio, it will auto-generate UUIDs, but for programmatic creation via the client, you have full control
Your initial instinct about using transactions was creative, but the issue you identified is real: you can't reference the _id of a document being created within the same transaction before it's actually created. By generating the ID upfront, you sidestep this entirely.
Show original thread1 reply
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.