How to auto-publish documents created via Sanity client in Node.js?

10 replies
Last updated: Jul 6, 2021
Hi! I already asked this question without answer, and it seem to have been buried so I ask it again.
https://sanity-io-land.slack.com/archives/C01T1B5GVEG/p1624550975405600
I have created a Node (Javascript) script to input data into my dataset with the sanity client.

I create my client like this (with real values):

const sanityClient = require('@sanity/client')
const client = sanityClient({
  projectId: 'your-project-id',
  dataset: 'bikeshop',
  apiVersion: '2019-01-29', // use current UTC date - see "specifying API version"!
  token: 'sanity-auth-token', // or leave blank for unauthenticated usage
  useCdn: true, // `false` if you want to ensure fresh data
})
Then I create a matching javascript object and call


client.create(obj);
All works fine and the document is created but it is not published. (this is an issue because I need to create a few hundred documents so I dont want to manually publish them).
AI Update

I understand your frustration! The behavior you're experiencing is actually expected - when you use client.create() without specifying an _id, Sanity auto-generates one as a UUID, and this creates what Sanity considers a published document (no drafts. prefix in the ID).

Understanding Draft vs Published

The key thing to understand is that in Sanity, whether a document is "draft" or "published" is determined entirely by its _id:

  • Published document: ID does NOT start with drafts. (e.g., abc-123)
  • Draft document: ID DOES start with drafts. (e.g., drafts.abc-123)

According to the Perspectives documentation and Published Documents documentation, when you create a document without the drafts. prefix, it's already published.

Why You Might Think They're Not Published

The confusion likely comes from how you're viewing the documents. Here's what might be happening:

  1. Studio Display: If you're checking in Sanity Studio, it might show indicators that make it look like documents need publishing, but if the _id doesn't have drafts. prefix, they're already live
  2. Query Perspective: Depending on how you're querying, you might be looking at the wrong perspective
  3. CDN Caching: With useCdn: true, you might not see fresh data immediately

Verify Your Documents Are Actually Published

Run this check to see what's really in your dataset:

const sanityClient = require('@sanity/client')
const client = sanityClient({
  projectId: 'your-project-id',
  dataset: 'bikeshop',
  apiVersion: '2021-06-24', // Use a current date
  token: 'sanity-auth-token',
  useCdn: false // Important for accurate results
})

// Check for published documents (no drafts. prefix)
const published = await client.fetch('*[_type == "yourType" && !(_id in path("drafts.**"))]')
console.log('Published documents:', published.map(d => d._id))

// Check for draft documents (with drafts. prefix)
const drafts = await client.fetch('*[_type == "yourType" && _id in path("drafts.**")]')
console.log('Draft documents:', drafts.map(d => d._id))

Your Code Should Already Work

Your current approach should create published documents automatically:

const sanityClient = require('@sanity/client')
const client = sanityClient({
  projectId: 'your-project-id',
  dataset: 'bikeshop',
  apiVersion: '2021-06-24', // Update to a current date
  token: 'sanity-auth-token',
  useCdn: false // Use false for write operations
})

// This creates a PUBLISHED document (auto-generated ID without drafts. prefix)
await client.create({
  _type: 'yourDocumentType',
  title: 'My Document',
  // your other fields
})

According to the Document ID documentation, when you don't specify an _id, Sanity auto-generates a UUID, and these are created as published documents by default.

Important Configuration Changes

Make these adjustments to your client setup:

  1. Set useCdn: false - The CDN is only for reads, and using it for writes can cause confusion
  2. Update your apiVersion - Use a more recent date like '2021-06-24' or later
  3. Verify token permissions - Ensure your token has write access to the dataset

If Documents Really Aren't Showing

If you run the verification query above and find your documents ARE published (no drafts. prefix) but still aren't appearing where you expect:

  • Check your frontend queries are using the published perspective
  • Make sure you're querying the correct dataset
  • Verify your API version settings match between write and read operations

The documents created by client.create() without an explicit _id are already published and ready to use - no manual publishing step needed!

Show original thread
10 replies
The left pic is my document created with the javascript code, then right one is one I manually added.
When I fetch these with a query I only get the ones I manually publish, the other ones does not show up, neither in my local fe, nor my public one.
There is no pencil icon or anything next to the post either.
I tried running a patch but it still doesnt publish.
I actually tried without it, and I just tried setting up a new sanity project, and there it works fine.
In my current (faulty) project i tried fetching through the routes the way it is done in the template:


import { client } from '../../sanityClient';

/**
 * This route is called 'all' instead of index to prevent route conflicts.
 * @see <https://sapper.svelte.dev/docs#Route_conflicts>
 */
export async function get (req, res) {
  try {
    const posts = await client.fetch('*[_type == "productContent" && defined(slug.current)]')
    res.end(JSON.stringify({ posts }));
  } catch (err) {
    res.writeHead(500, {
      'Content-Type': 'application/json'
    });

    res.end(JSON.stringify({
      message: err.message
    }));  
  }
};
And this still doesnt show the new document
So it's for sure an issue with our Sanity project. Since I input and fetch the same in both the projects.
Such a bittersweet feeling in those cases where you’re happy your code works but frustrated trying to figure out why it won’t work on this project.
exactly haha. We have a theory that it could be the "intl-input" plugin.
user A
you were actually right my man.I added the i18n_lang field and now it works
so thank you!
Great! Glad to hear it. 🙌

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?