How to use the CDN in a query string for the frontend.
To make your query use the CDN, you need to change the domain from api.sanity.io to apicdn.sanity.io. Here's the updated version:
// Compose the URL for your project's endpoint and add the query
let URL = `https://${PROJECT_ID}.apicdn.sanity.io/v2021-10-21/data/query/${DATASET}?query=${QUERY}`The key difference is using apicdn.sanity.io instead of api.sanity.io.
What you get with the CDN
When you use Live CDN (also called API CDN), you get:
- Global edge caching with ~10 minute cache times for better performance
- Automatic cache invalidation - when content updates in Sanity, the CDN automatically handles cache updates
- Lower latency through worldwide edge distribution
- Reduced load on the origin API servers
The trade-off
The CDN uses a stale-while-revalidate strategy with 600 seconds (10 minutes) cache time. This means content may be up to 10 minutes old in exchange for significantly better performance and robustness. If your application absolutely needs the freshest data on every request, stick with api.sanity.io.
Using with Sanity Client
If you're using the Sanity JavaScript client, you can simply set useCdn: true in your configuration instead of manually changing URLs:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
useCdn: true, // Enable the CDN
apiVersion: '2021-10-21'
})This is the recommended approach as it handles the URL construction for 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.