Sanity useCdn true vs false for a read-after-publish content page
0 reputation · 05 Sept 2024, 05:58 UTC
0 reputation · 05 Sept 2024, 05:58 UTC
We run a Next.js front end backed by Sanity (assume a recent @sanity/client major; exact version semantics to be confirmed against its changelog). One concrete constraint: after an editor publishes an update, the public article page is revalidated and re-fetched within seconds, and readers should not see the pre-publish version.
The client exposes the documented useCdn flag. With useCdn: true, reads come from the apicdn.sanity.io edge cache, which is faster and cheaper under traffic but can serve a stale document for a short propagation window after a mutation. With useCdn: false, queries hit the live origin and return the freshest committed content at higher latency and load. There does not appear to be a documented maximum staleness bound for the CDN, which makes the choice hard to reason about for this read-after-publish path.
A split setup (CDN for anonymous traffic, live origin for preview/drafts) is a documented pattern, but our case sits in between: it is a public page, yet freshness matters immediately after publish.
Specifically:
client.listen or webhooks replace the freshness guesswork here, and how would that interact with CDN-cached reads?For a public article that is revalidated immediately after a publish, the only guarantee that the reader will never see the pre‑publish version is to read from the live origin. useCdn: false guarantees freshness, while useCdn: true can return a stale copy for an unpredictable propagation window.
useCdn: true uses apicdn.sanity.io, an eventually consistent edge cache.useCdn: false hits the Sanity API origin and always returns the most recent committed document.useCdn: true for lists, navigation, and other staleness‑tolerant reads.useCdn: false and use it inside the article page’s data fetch (e.g. getStaticProps with ISR or a dedicated API route). Because Next.js revalidates on publish, the origin query happens once per revalidation, not once per reader.import {createClient} from "@sanity/client";
const base = {
projectId: process.env.SANITY_PROJECT_ID!,
dataset: "production",
apiVersion: "2024-01-01"
};
export const cdnClient = createClient({...base, useCdn: true});
export const originClient = createClient({...base, useCdn: false});
useCdn setting you give it. It is useful for preview UIs, not for guaranteeing freshness to anonymous readers._updatedAt timestamps.revalidate: 1 to getStaticProps and confirm that a page refresh after publish shows the updated content without manual purging.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.