Query returns null for drafts in Next.js but works in Vision with token
This is a classic issue with perspectives in Sanity's API! The Vision pane and your Next.js client are using different default perspectives, which is why you're seeing different results.
The Problem
By default, the Vision tool in Sanity Studio uses the previewDrafts perspective, which returns draft documents. However, when you query via the API from your Next.js app, it uses a different default perspective depending on your API version.
As of API version 2025-02-19, the default perspective changed to published, which means your queries will only return published documents unless you explicitly specify otherwise.
The Solution
You need to add the perspective option to your client configuration. Since you want to see drafts (and you already have a token with appropriate permissions), set it to previewDrafts:
import { createClient } from "next-sanity";
export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID;
export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET;
export const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION;
export const token = process.env.SANITY_SECRET_TOKEN;
export const client = createClient({
projectId,
dataset,
apiVersion,
useCdn: false,
token,
perspective: 'previewDrafts' // Add this line
})The previewDrafts perspective will return draft versions when they exist, falling back to published versions when no draft exists. This matches the behavior you're seeing in Vision.
Alternative Approaches
If you want more control over when to show drafts vs published content, you could:
- Create two separate clients - one for published content and one for previews:
export const previewClient = createClient({
projectId,
dataset,
apiVersion,
useCdn: false,
token,
perspective: 'previewDrafts'
})
export const publicClient = createClient({
projectId,
dataset,
apiVersion,
useCdn: true,
perspective: 'published'
})- Use Next.js Draft Mode - Integrate with Next.js Draft Mode to conditionally switch between perspectives based on whether a user is previewing content.
Why This Happens
Draft documents in Sanity have an _id prefixed with drafts. (e.g., drafts.asdf-1234). The perspective setting controls whether queries include these draft documents in results. Without the proper perspective, your authenticated token alone isn't enough - the API still filters out drafts by default.
Show original thread9 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.