Sanity previewDrafts perspective not returning draft posts in Next.js
export default async function BlogOverviewPage() {
const posts = await getAllPosts();
return <>work with the posts object</>export async function getAllPosts() {
const DEFAULT_TAGS = ["post"] as string[];
if (client) {
const result = await client.fetch(postquery, {}, {
//cache: "force-cache",
next: {
revalidate: 60 // for simple, time-based revalidation
//tags: DEFAULT_TAGS, // for tag-based revalidation
}
});
console.log("# Items: "+result.length);
return result || [];
}
return [];
}I can see what's happening here! When using the previewDrafts perspective, you must provide an authentication token and set useCdn: false in your client configuration. Without these, the client silently falls back to only returning published content, which is exactly what you're experiencing.
Here's what you need to fix:
import { createClient } from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
apiVersion: '2024-01-01',
useCdn: false, // CRITICAL: Must be false for draft content
token: process.env.SANITY_API_TOKEN, // CRITICAL: Must have read token
perspective: 'previewDrafts',
})The key requirements for previewDrafts perspective are:
useCdn: false- The CDN only serves published content, so you must query the origin API directlytoken- You need a read token with permissions to view drafts (create one in your Sanity project settings)- Token permissions - The token must have "Viewer" or higher permissions
Without both of these, the Sanity client will only return published documents, even though you've set the perspective to previewDrafts. This is a security feature - draft content requires authentication.
In Vision tool, you're already authenticated through Studio, which is why you see all drafts there. But your Next.js client needs explicit authentication.
Important security note: Since you're using this in a Server Component, the token stays server-side and won't be exposed to the browser. Never use a token in client-side code.
Also, your Next.js caching configuration looks fine. The revalidate: 60 will work correctly once you fix the client configuration. The issue isn't with Next.js caching - it's that your client is silently failing to fetch drafts due to missing authentication.
For a complete setup with Draft Mode in Next.js App Router, check out the Visual Editing with Next.js documentation which covers the full authentication flow.
Show original thread9 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.