I have documents being created via the HTTP API, but when I go to query these documents on the front-end of my app, it's not returning any results.
Ah, I think I know what's happening here! This is almost certainly a draft vs. published document issue.
When you create documents via the HTTP API, they're typically created as draft documents by default (with an _id prefixed by drafts.). The key thing to understand is that draft documents are not visible to unauthenticated queries on public datasets.
Here's what's happening:
- Your HTTP API creates documents with IDs like
drafts.some-document-id - Your frontend queries without a token can only see published documents (IDs without the
drafts.prefix) - When you add a token to your frontend client, it authenticates and can now see draft documents
- Documents created manually in Studio work fine because Studio automatically publishes them (creating both the draft AND the published version)
The Solution
You have two options:
Option 1: Publish the documents when creating them via API
Create the published document directly (without the drafts. prefix):
// Create the published document (no drafts. prefix)
await client.create({
_id: 'some-document-id', // No drafts. prefix
_type: 'yourType',
// ... your fields
})Or if you're creating drafts first, publish them by creating the non-draft version:
// First create draft
await client.create({
_id: 'drafts.some-document-id',
// ... your data
})
// Then "publish" by creating without drafts. prefix
await client.create({
_id: 'some-document-id', // Remove drafts. prefix
// ... same data
})Option 2: Use the previewDrafts perspective on your frontend
If you need to see drafts on the frontend (for preview purposes), you can configure your client with the previewDrafts perspective, but this requires authentication:
const client = createClient({
// ... config
perspective: 'previewDrafts',
token: process.env.SANITY_API_TOKEN, // Required for drafts
useCdn: false // Can't use CDN with drafts
})Since you mentioned security concerns about tokens on the frontend, Option 1 is probably what you want - just create published documents directly via the API by omitting the drafts. prefix from your document IDs.
The draft documents documentation explains this behavior in detail - drafts are essentially "private" until published, which is why they require authentication to query.
Show original thread15 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.