Hey guys, does sanity have some kind of caching mechanism on request? im using the `@sanity/client` in a rn app; the issue is, when I edit a document in sanity and then attempt...
This is actually a common issue related to how Sanity's CDN caching works! The behavior you're seeing is by design, and here's what's happening:
When you use @sanity/client with useCdn: true (which is often the default), your requests go through apicdn.sanity.io. The Live CDN uses a stale-while-revalidate caching strategy with a 600-second (10-minute) cache window.
Here's why you need to fetch twice:
- First fetch after editing: Returns the stale (cached) content from the CDN, but triggers a background revalidation
- Second fetch: Returns the fresh content that was fetched during the revalidation
This is the expected behavior of stale-while-revalidate caching - it prioritizes performance and availability by serving cached content immediately while updating in the background.
Solutions
Option 1: Disable CDN for fresh data (Recommended for your use case)
Set useCdn: false in your client configuration:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
useCdn: false, // Bypass CDN for always-fresh data
apiVersion: '2024-01-01'
})This sends requests directly to api.sanity.io instead of the CDN, giving you fresh data on every request.
Option 2: Use perspective parameter
You can also use the perspective parameter set to 'previewDrafts' or 'published' depending on your needs, but this works best when combined with useCdn: false for immediate updates.
When to use each approach
useCdn: true: Best for production apps where slightly stale data (up to 10 minutes) is acceptable and you want better performance/lower latencyuseCdn: false: Best for admin interfaces, preview modes, or when you need guaranteed fresh data on every request
Since you're building a React Native app where users expect to see their edits immediately, setting useCdn: false is probably your best bet!
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.