How to create unpublished document with Sanity JS client?

3 replies
Last updated: Apr 23, 2020
I'm adding a doc through the js sanity api client and it's published automatically is there some way to add it without publishing it?
AI Update

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 the drafts. 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 the drafts. 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 thread
3 replies
Is there a way to even unpublish using the js sanity api client?
Hi Zane, there is a way to add a document without publishing it, which is by prefixing the id with
drafts.
. More info in this thread for example: https://sanity-io-land.slack.com/archives/C9Z7RC3V1/p1587097360221800
user M
Nice thanks!

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?