Discrepancy between post counts in Sanity Vision and local environment using the same query and perspective.
This is a classic issue! The previewDrafts perspective requires authentication with a token to access draft documents. When you use Sanity Vision in the Studio, you're already authenticated (logged in), so it works seamlessly. But when you're querying from your local environment, you need to explicitly provide a token.
Here's what's happening: Without a token, your client can only see published documents, even though you've set perspective: 'previewDrafts'. The perspective setting tells Sanity what you want to see, but the token provides the permission to actually see it.
The Solution
You need to add a read token to your client configuration. Here's how:
1. Create an API token in your project
Go to manage.sanity.io, select your project, navigate to the API tab, and create a token with Viewer permissions. You can also run:
pnpm dlx sanity manage2. Add the token to your environment variables
In your .env.local file:
SANITY_API_READ_TOKEN="your-token-here"3. Update your client configuration
sanityClient({
// ...
useCdn: false,
perspective: isDev ? 'previewDrafts' : 'published',
token: isDev ? process.env.SANITY_API_READ_TOKEN : undefined
})The key point from the Sanity documentation on token handling is clear:
Authentication will also be required to use the
previewDraftsperspective, a method of performing a GROQ query that returns the latest draft version of a document instead of an already-published document.
Important Security Note: Never expose this token in client-side code! Only use it in server-side contexts (API routes, server components, etc.). The token gives read access to all documents in your dataset, including drafts.
Once you add the token, your local environment should return all 5 results (2 published + 3 drafts) just like Vision does. The previewDrafts perspective will return draft versions when they exist, falling back to published versions for documents that don't have drafts.
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.