How to create unpublished document with Sanity JS client?
Yes! When you create a document through the Sanity JS client, it's published by default, but you can create it as a draft instead by prepending drafts. to the document ID.
Here's how to create a draft document:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
token: 'your-token', // needs write permissions
apiVersion: '2024-01-01'
})
// Create a draft by adding 'drafts.' prefix to the _id
await client.create({
_id: 'drafts.my-document-id', // This makes it a draft!
_type: 'myDocumentType',
title: 'My Draft Document',
// ... other fields
})The key is the drafts. prefix on the _id. When you create a document with this prefix, Sanity treats it as an unpublished draft that only appears in the Studio and won't be returned by default queries (unless you use the drafts perspective).
A few things to keep in mind:
- Generate unique IDs: If you don't specify an
_id, Sanity will auto-generate one, but it won't have thedrafts.prefix. So you need to explicitly set the ID with the prefix. - Publishing later: When you're ready to publish, you can use
client.createOrReplace()with the same ID but without thedrafts.prefix, or use the Studio's publish button. - Permissions: Make sure your API token has write permissions to create documents.
If you want to let Sanity generate the ID but still keep it as a draft, you can do this:
const doc = await client.create({
_type: 'myDocumentType',
title: 'My Draft Document',
})
// Then immediately create the draft version
await client.createOrReplace({
...doc,
_id: `drafts.${doc._id}`
})
// Optionally delete the published version if you don't want it
await client.delete(doc._id)This approach is useful when you want Sanity to handle ID generation but still maintain draft status.
Show original thread3 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.