Does Next.js's `createClient().fetch()` in the `next-sanity` package leverage the Data Cache?
No, the basic createClient().fetch() from next-sanity does not automatically leverage the Next.js Data Cache. To integrate with Next.js caching features, you need to use the sanityFetch() helper function provided by next-sanity.
The Key Difference
The standard Sanity client's fetch() method bypasses Next.js's built-in caching mechanisms. While it will query your Sanity content successfully, those queries won't be cached by Next.js's Data Cache, meaning you lose out on the performance benefits and revalidation strategies that Next.js provides.
Using sanityFetch() for Cache Integration
The sanityFetch() helper function is specifically designed to work seamlessly with Next.js caching and revalidation. It wraps the standard client and integrates with the Next.js Data Cache, giving you full control over cache behavior.
Here's how to set it up and use it:
// Create a sanityFetch helper
import { createClient } from 'next-sanity'
const client = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
apiVersion: '2024-07-11',
useCdn: true,
})
export async function sanityFetch<QueryResponse>({
query,
params = {},
revalidate = 60, // default revalidation time in seconds
tags = [],
}: {
query: string
params?: any
revalidate?: number | false
tags?: string[]
}) {
return client.fetch<QueryResponse>(query, params, {
next: {
revalidate: tags.length ? false : revalidate, // Use tags OR time-based revalidation
tags,
},
})
}Cache Revalidation Options
The sanityFetch() helper supports Next.js cache revalidation through the third parameter - the next options object that you pass to client.fetch():
Tag-based revalidation (recommended):
const posts = await sanityFetch({
query: POSTS_QUERY,
tags: ['post', 'author'],
})You can then use Next.js's revalidateTag() to surgically invalidate specific cached content when your Sanity documents change.
Time-based revalidation:
const data = await sanityFetch({
query: MY_QUERY,
revalidate: 3600, // revalidate every hour
})The Bottom Line
If you want your Sanity queries to work with Next.js's Data Cache, use the sanityFetch() helper pattern shown in the next-sanity README. The basic createClient().fetch() won't give you cache integration on its own - you need to explicitly pass the next options object with tags or revalidate settings to enable caching behavior.
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.