Using CDN in development with Sanity and Next.js

7 replies
Last updated: May 31, 2023
Would like to ask for advice. Fetching the Sanity data while developing fetches the data every time i make a change.
Is there something like caching from Sanity, or maybe using cdn from Sanity when developing?

I am on a Next js project how about caching?

Any links, tips, advices would be great.
AI Update

Constantly refetching data during development can definitely slow things down. Here's how to optimize your Sanity + Next.js setup for better caching:

Use Sanity's CDN for Development

The most important setting is enabling Sanity's CDN when creating your client. The Sanity CDN provides unlimited rate for cached content and is much faster than querying the API directly:

import { createClient } from '@sanity/client'

export const client = createClient({
  projectId: 'your-project-id',
  dataset: 'production',
  apiVersion: '2024-01-01',
  useCdn: true, // Enable CDN for faster responses
})

Setting useCdn: true is a sensible default for most situations. The CDN cache is flushed every time you publish content, so there's only a brief delay between publishing and seeing updates.

Use the sanityFetch Helper Function

If you're using next-sanity, you can create a helper function that wraps your Sanity client with Next.js caching configuration:

import { createClient, type QueryParams } from 'next-sanity'

export const client = createClient({
  projectId: 'your-project-id',
  dataset: 'production',
  apiVersion: '2024-01-01',
  useCdn: true,
})

export async function sanityFetch<const QueryString extends string>({
  query,
  params = {},
  revalidate = 60, // default revalidation time in seconds
  tags = [],
}: {
  query: QueryString
  params?: QueryParams
  revalidate?: number | false
  tags?: string[]
}) {
  return client.fetch(query, params, {
    next: {
      revalidate: tags.length ? false : revalidate,
      tags,
    },
  })
}

Then use it in your components:

const posts = await sanityFetch({
  query: POSTS_QUERY,
  revalidate: 60, // Cache for 60 seconds
})

Debug Your Cache Behavior

To see what's actually being cached during development, enable fetch logging in your next.config.ts:

const nextConfig = {
  logging: {
    fetches: {
      fullUrl: true,
    },
  },
}

This will show you cache hits/misses in your terminal, helping you understand what's working.

When to Use the API vs CDN

You should only query the API directly (useCdn: false) when responses need to be guaranteed fresh, such as during static site generation. For example, you can override the CDN setting per-request:

export async function generateStaticParams() {
  const slugs = await client
    .withConfig({ useCdn: false })
    .fetch(POSTS_SLUGS_QUERY)
  
  return slugs
}

Cache Revalidation Strategies

For production, you have several options:

  1. Time-based revalidation: Cache for a specific duration (shown above with revalidate: 60)
  2. Tag-based revalidation: Surgically invalidate specific content when it changes using tags
  3. Path-based revalidation: Revalidate entire routes using Next.js's revalidatePath

The key takeaway: use useCdn: true for development and most production scenarios. This gives you fast responses with the Sanity CDN's global caching, plus you can layer Next.js caching strategies on top for even better performance.

You can configure the client to use the API CDN any time—including in development. Adding
useCdn: true
should be enough for that instance of the client to always source from the API CDN.
Any down sides using cdn in dev or production? Thanks in advance
Your changes won’t show up immediately, will need time to propagate?
(changes to your data)
I will use it in production thanks! Does revalidate in next js work with useCdn set to true?
Yes it would—but as mentioned, against potentially stale data.
Great thank you!

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?