Joint session with Vercel: How to build intelligent storefronts (May 15th)

How to publish documents via Sanity API/JavaScript client?

2 repliesLast updated: Nov 29, 2025

Is there a way to perform a “publish” through the API/JavaScript client? (We’d like to add a “publish all drafts” button)
AI Update

Yes, you can absolutely perform a "publish" through the API/JavaScript client! In Sanity, publishing is essentially copying a draft document to its published version by manipulating the document IDs.

How Publishing Works in Sanity

Sanity uses a draft/publish system where:

Publishing via the API

To publish a document programmatically using the JavaScript client, you can use the createOrReplace mutation. Here's how:

import {createClient} from '@sanity/client'

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset',
  token: 'your-token-with-write-access',
  apiVersion: '2025-01-01',
  useCdn: false
})

// Publish a single document
async function publishDocument(documentId) {
  // Fetch the draft
  const draft = await client.getDocument(`drafts.${documentId}`)
  
  if (!draft) {
    throw new Error('Draft not found')
  }
  
  // Remove the drafts. prefix from _id
  const {_id, ...documentWithoutId} = draft
  
  // Create or replace the published version
  return client.createOrReplace({
    ...documentWithoutId,
    _id: documentId,
    _type: draft._type
  })
}

Publishing All Drafts

For your "publish all drafts" button, you could do something like this:

async function publishAllDrafts() {
  // Query all draft documents
  const drafts = await client.fetch(
    `*[_id in path("drafts.**")]`
  )
  
  // Create a transaction to publish them all
  const transaction = client.transaction()
  
  drafts.forEach(draft => {
    const publishedId = draft._id.replace('drafts.', '')
    const {_id, ...doc} = draft
    
    transaction.createOrReplace({
      ...doc,
      _id: publishedId
    })
  })
  
  return transaction.commit()
}

Important Considerations

This approach gives you full programmatic control over publishing, which is perfect for building custom workflows, scheduled publishing, or bulk operations like your "publish all drafts" button!

Show original thread
2 replies

Was this answer helpful?

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.

Related contributions