Issue with caching in Next.js server component using Sanity.io

9 replies
Last updated: Feb 13, 2024
Sanity/next caching drives me crazy... I have a server component in next a page which just does this:

export default async function BlogOverviewPage() {
  const posts = await getAllPosts();

  return <>work with the posts object</>
Here is the getAllPosts();


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 [];
}
client is using previewDrafts perspective. When running this query, i see in NextJS console the sanity query. When i copy this query to the Vision tool in the studio, i get all my draft posts and my one published post. When i run this via NextJS, the logging output from the logging line you see here is always (and forver 1). The publsihed item only. I really dont know what this is. Anybody an idea?
AI Update

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:

  1. useCdn: false - The CDN only serves published content, so you must query the origin API directly
  2. token - You need a read token with permissions to view drafts (create one in your Sanity project settings)
  3. 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.

Have you tried hard refreshing the page?
yeah... all the time.... NextJS even says in the log "Cache SKIP"
Is your client authenticated? You need this to view drafts. Make sure your api token is configured
ohhh. Thats a good hint. I will check this tomorrow... thanks for your infos so far
need to check how to even do that 😉 this doenst look like there is any auth going on
createClient({
    projectId,
    dataset,
    apiVersion,
    useCdn,
    perspective: process.env.NODE_ENV === "development" ? "previewDrafts" : "published"
  }

man... that was the reason... you were correct. A hint to the documentation guys at Sanity, i would love (and perhaps others) to see a hint in the previewDrafts section over there: https://www.sanity.io/docs/js-client#previewdrafts

user A
thanks a lot again. I think i would have never found it. Especially since it worked in the Vision tool but there different rules apply most likely because i am already authed in that area.
Let’s use greetings like “Hey Everyone,” “Hi, Y’all," or “Hello, Folks” to make sure everyone in the community is included. Please read the Sanity Community Code of Conduct to stay updated on expected communication &amp; behavior in our spaces: https://www.sanity.io/docs/community-code-of-conduct
No promblem :)

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?