Preview and publishing with Contentful and Next.js
Amol Agre (opens in a new tab), Technical Lead
Published · Reviewed · 7 min read
Direct answer#
Give each page-level content type a preview URL in Contentful that calls a Next.js route handler. The handler checks a shared secret, turns on Draft Mode and redirects to the page, which then reads from the Content Preview API with a preview token that never leaves the server. For published changes, tag your cached Contentful data and point a Contentful webhook at a second, secured route handler that calls revalidateTag or revalidatePath, with time-based revalidation as a safety net.
Key takeaways
- Preview runs on the server: a secret-checked route turns on Draft Mode, and pages read the Preview API with a token the browser never sees.
- Publishing uses a secured webhook that revalidates tagged data. Visitors see the change on their next request.
- Pair webhooks with a long time-based interval, so a missed webhook can't leave a page stale for ever.
Steps or trade-offs#
The two paths look like this. The rest of this article builds each step.
Open preview
The editor clicks Open preview in the entry editor. Contentful fills in the preview URL.
Draft route
A Next.js route handler checks the secret, turns on Draft Mode and redirects.
Preview API
The page sees Draft Mode and reads the Preview API with the server-only preview token.
Draft page
Only this editor's browser sees the unpublished content, with a draft banner.
Publish
The editor publishes the entry in Contentful.
Webhook
Contentful sends Entry.publish to your revalidation route, with a secret.
Revalidate
The route checks the secret and calls revalidateTag for the cached data.
Next visit
The next request refetches from the Delivery API and caches the new version.
Two APIs, two tokens#
Contentful serves the same content model through two read-only APIs, with the same behaviour and parameters:
| Content Delivery API | Content Preview API | |
|---|---|---|
| Host | cdn. | preview. |
| Returns | Published content only | The latest drafts of entries and assets, including unpublished changes |
| Token | The API key's delivery token | The same key's separate preview token. The delivery token won't work here |
| Caching | Served through a global CDN. Requests answered from its cache don't count towards your rate limit | Meant for previews, not for serving the live site |
| Used by | Every visitor to the live site | Editors previewing drafts, through your server |
Contentful notes that the separate token helps prevent unpublished content leaking by accident. Send either token in an Authorization: Bearer header. Contentful also recommends separate tokens per environment, so you can revoke one without affecting the others.
Keep the preview token on the server
Use the preview token only in server code (route handlers and Server Components), and never let it reach a browser bundle. Anyone who has it can read the unpublished drafts in every environment it covers.
Configure preview URLs in Contentful#
A space administrator sets up previews under Settings > Preview:
- Create a preview platform, for example "Website".
- Tick the content types that represent pages. Leave reusable fragments, such as an opening-hours block, without a preview URL.
- Enter a URL for each content type, using placeholders such as
{entry.fields.slug},{entry.sys.id}or{locale}.
https://www.example.com/api/draft?secret=YOUR_PREVIEW_SECRET&slug={entry.fields.slug}Fields used in URLs must be strings or integers, so add validation to slug fields that blocks spaces, #, % and quotation marks.
No access tokens in preview URLs
Contentful is clear that an access token must never go in a preview URL: anyone who sees the URL would get the token.
The secret above is not a Contentful token: it is a random value known only to your Next.js app and the preview configuration, and all it can do is switch on Draft Mode.
Turn on Draft Mode in a route handler#
In the App Router, draftMode() comes from next/headers and is asynchronous in current versions. Calling enable() in a route handler sets a __prerender_bypass cookie.
// app/api/draft/route.ts
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const secret = searchParams.get('secret')
const slug = searchParams.get('slug')
if (secret !== process.env.PREVIEW_SECRET || !slug) {
return new Response('Invalid token', { status: 401 })
}
// Your own data function, reading from the Preview API
const page = await getPageBySlug(slug, { preview: true })
if (!page) {
return new Response('Invalid slug', { status: 401 })
}
const draft = await draftMode()
draft.enable()
redirect(`/${page.slug}`)
}Redirect to the slug from the looked-up entry rather than the query string, which avoids an open redirect. The bypass cookie value changes on every build, and the Draft Mode session ends when the browser closes. To let editors leave preview early, call disable() from a Server Action or a POST route handler behind an "Exit preview" button.
Render drafts only in Draft Mode#
In each page or data function, read isEnabled from draftMode() and use it to choose the API host and token: Preview API and preview token when it is true, Delivery API and delivery token otherwise. Everything else in the data layer can stay the same.
// lib/contentful.ts: server code only, so the tokens never reach the browser
export async function getPageBySlug(
slug: string,
{ preview }: { preview: boolean },
) {
const host = preview ? 'preview.contentful.com' : 'cdn.contentful.com'
const token = preview
? process.env.CONTENTFUL_PREVIEW_TOKEN
: process.env.CONTENTFUL_DELIVERY_TOKEN
const space = process.env.CONTENTFUL_SPACE_ID
const query = new URLSearchParams({
content_type: 'page',
'fields.slug': slug,
limit: '1',
})
const url = `https://${host}/spaces/${space}/environments/master/entries?${query}`
const res = await fetch(url, {
headers: { Authorization: `Bearer ${token}` },
next: { tags: ['contentful'] }, // the tag the webhook route revalidates
})
if (!res.ok) throw new Error(`Contentful responded ${res.status}`)
const data = await res.json()
return data.items[0]
}
// In the page:
// const { isEnabled } = await draftMode()
// const page = await getPageBySlug(slug, { preview: isEnabled })While Draft Mode is on, Next.js skips its fetch cache, re-runs anything inside 'use cache' without saving the result, and serves the page with a private, no-store Cache-Control header. Other visitors keep getting the cached published version. A small banner driven by isEnabled helps editors see at a glance that they are looking at a draft.
Optional: Contentful Live Preview#
Contentful can show your preview in a pane beside the entry editor. Side-by-side preview needs only the preview configuration above. Live updates as the editor types, and an inspector mode that links page elements back to their fields, need Contentful's live preview SDK, which has a React-focused integration that works with Next.js. Your site must allow framing by https://app.contentful.com through the frame-ancestors directive of its Content Security Policy, and cookies used inside the frame must be set with SameSite=None and Secure. Test that the Draft Mode cookie survives inside the pane before you rely on it.
Publishing: from webhook to revalidation#
Published pages are usually prerendered or cached, so a publish in Contentful has to tell Next.js which cached data is now out of date.
- Tag your data. Add
next: { tags: [...] }to thefetchcalls that read from the Delivery API, or callcacheTaginside a'use cache'function if your project uses Cache Components. - Create a webhook under Settings > Webhooks. Choose specific topics such as
Entry.publish,Entry.unpublishandEntry.delete(plus theAssetequivalents if images matter); Contentful advises against broad wildcards like*.*in production. You can filter by content type. The URL cannot belocalhost, so use a tunnel for local testing. - Secure it. Add a custom header marked as secret and check it in the handler, or enable Contentful's request verification, which signs each request (
x-contentful-signature,x-contentful-timestamp) and can be checked withverifyRequestfrom@contentful/node-apps-toolkit. - Revalidate in a route handler:
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache'
export async function POST(request: Request) {
const secret = request.headers.get('x-webhook-secret')
if (secret !== process.env.CONTENTFUL_WEBHOOK_SECRET) {
return new Response('Invalid secret', { status: 401 })
}
const topic = request.headers.get('x-contentful-topic') ?? ''
const removed = topic.endsWith('.unpublish') || topic.endsWith('.delete')
// Serve stale while refreshing edits; expire removals immediately
revalidateTag('contentful', removed ? { expire: 0 } : 'max')
return Response.json({ revalidated: true })
}In current Next.js, revalidateTag takes a second argument and the single-argument form is deprecated. With 'max', the next request for tagged data is served the old version while a fresh one is fetched in the background. With { expire: 0 }, the next request waits for fresh data. Either way, revalidation happens when a page is next requested, not when the function is called. revalidatePath does the same for a route; for a dynamic route such as /products/[slug], pass 'page' or 'layout' as the second argument.
Keep the handler fast. Contentful allows 30 seconds for a response, does not retry timeouts, and retries 429 and 5xx responses up to three attempts in total.
Trade-offs to decide up front#
-
Freshness versus cost. Compared side by side:
Time-based revalidation Webhook revalidation Set up with next: { revalidate: 3600 }on a fetchA Contentful webhook and a secured route handler How fresh Up to one interval stale (an hour here) Updated on the next visit after a publish Extra work Refetches whether or not anything changed Only after a publish, unpublish or delete If something fails Nothing to fail A missed webhook leaves the page stale, because Contentful doesn't retry timeouts You can combine the two: webhooks as the main path and a long time-based interval as a fallback.
-
Cache granularity. One broad tag, as in the example, is simple and always correct, but every tagged page re-renders on its next visit after any publish. Narrower tags, per content type or per entry, mean less work but require you to know every page an entry appears on, including pages that reach it through references.
revalidatePathrefreshes only that path; other pages using the same data stay cached until their tags are revalidated. -
Unpublish and delete. For these events Contentful sends a tombstone payload containing only
sys, so you cannot read the slug from it. Revalidate by entry ID or broadly, and make sure pages render a 404 when the entry is gone. -
Security. Both endpoints are public URLs. Keep both secrets in environment variables, reject requests that fail the check, and never echo tokens back in responses.
These choices shape your content model and hosting as much as your code, so they belong in the planning of a Contentful and Next.js build rather than being left until launch.
Examples#
Previewing and publishing a product page. Suppose an editor changes the description on a hypothetical product page. They open preview from the entry editor; Contentful fills in {entry.fields.slug} and opens the preview URL. The draft route checks the secret, confirms the product exists through the Preview API, enables Draft Mode and redirects to the product page, which renders the unpublished description with a "Draft preview" banner. When the editor publishes, Contentful sends an Entry.publish webhook. The revalidation route checks its secret and calls revalidateTag with 'max'. The next visitor may still see the old description while Next.js fetches the new one; visitors after that see the update.
Unpublishing a campaign page. Suppose instead a marketing team unpublishes a hypothetical campaign page that has ended. Contentful sends Entry.unpublish with a tombstone payload. The handler spots the topic and calls revalidateTag with { expire: 0 }, so the next request waits for fresh data rather than receiving the old page. The entry is no longer in the Delivery API, the campaign route returns a 404, and any listing page tagged the same way drops the link on its next request.
Primary sources#
- Contentful: Content Preview API: preview host, latest drafts, separate preview token.
- Contentful: Content Delivery API: delivery host, CDN and rate limits on cached requests.
- Contentful: API concepts: how the Preview API relates to the Delivery API.
- Contentful: Authentication:
Authorization: Bearerheader and per-environment tokens. - Contentful: Content preview: preview platforms, URL placeholders, slug validation, no tokens in preview URLs.
- Contentful: Live preview: side-by-side preview, SDK features, framing and cookie requirements.
- Contentful: Webhooks overview: tombstone payloads, retries and response time limit.
- Contentful: Configuring a webhook: topics, wildcards, filters, secret headers, URL restrictions.
- Contentful: Webhook request verification: signing secret, signed headers,
verifyRequest. - Next.js: Draft Mode guide: secured draft route, cache bypass, preview banner.
- Next.js: draftMode: async API,
enable(),disable(), bypass cookie. - Next.js: revalidateTag: two-argument signature,
'max'andexpirebehaviour. - Next.js: revalidatePath: path and
typeparameters, behaviour in route handlers. - Next.js: fetch:
next.revalidateandnext.tagsoptions. - Next.js: route.js: route handlers, request headers and webhooks.