👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Handling caching issues with Sanity data in NextJS app router

4 replies
Last updated: May 24, 2024
Using NextJS app router
next@14.2.3

When I load data from sanity it seems that it gets cached. the only way to avoid caching is to provide to the client.fetch an extra parameter. but then typescript doesn’t recognise this… Though it works and there is no cache..


import groq from 'groq';

import { Footer } from '@/components/footer';
import { Header } from '@/components/header';
import { type ContentItem, renderComponent } from '@/lib/render';
import { client } from '@/sanity/lib/client';

type DataProps = {
  content: ContentItem[];
};

const pageQuery = groq`*[_type == "page" && slug.current == $slug]`;

async function getData(slug: string) {
  const res = await client.fetch(pageQuery, { slug, next: { revalidate: 1 } });
  if (!res) {
    throw new Error('Failed to fetch data');
  }

  return res[0];
}

export default async function Page() {
  const slug = '/';
  const data: DataProps = await getData(slug);
  console.log('page.tsx data', data);

  return (
    <main className="flex flex-col items-center">
      <Header />
      {data?.content.map(renderComponent)}
      <Footer />
    </main>
  );
}
May 24, 2024, 2:20 PM
how do I get typescript to recognise this prop (which I think is just a
fetch
and nextjs is decorating the
fetch
with extra props
May 24, 2024, 2:21 PM
actually I’m not sure this actually solves the cache…
May 24, 2024, 2:25 PM
😞
May 24, 2024, 2:25 PM
okay, this is the solution:

async function getData(slug: string) {
  const res = await client.fetch(pageQuery, { slug }, { cache: 'no-store' });
  if (!res) {
    throw new Error('Failed to fetch data');
  }

  return res[0];
}
source:
https://www.sanity.io/answers/how-to-disable-cache-in-sanity-io-for-immediate-reflection-of-changes-made-in-the-studio-on-the-blog-
May 24, 2024, 2:27 PM

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?