👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

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?
Feb 12, 2024, 6:50 PM
Have you tried hard refreshing the page?
Feb 12, 2024, 7:02 PM
yeah... all the time.... NextJS even says in the log "Cache SKIP"
Feb 12, 2024, 7:06 PM
Is your client authenticated? You need this to view drafts. Make sure your api token is configured
Feb 12, 2024, 8:16 PM
ohhh. Thats a good hint. I will check this tomorrow... thanks for your infos so far
Feb 12, 2024, 10:06 PM
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"
  }

Feb 12, 2024, 10:08 PM
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.
Feb 12, 2024, 10:28 PM
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
Feb 12, 2024, 10:28 PM
No promblem :)
Feb 13, 2024, 6:48 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?