VENNStart
Guide

Updating CMS content in Next.js without rebuilding the site

How I connect CMS webhooks to revalidateTag and revalidatePath, and why a CDN or browser can still show old content after Next.js has refreshed.

Lê Anh Tuấn4 min read

A typo fix in the CMS shouldn't trigger a rebuild of the whole site. I use on-demand revalidation: the CMS sends a webhook saying what changed, and the app calls revalidateTag or revalidatePath. A successful webhook can still leave old content in a CDN or a browser. For static versus per-request versus ISR routes, see SSR, SSG and ISR in the App Router.

Tag first, then path, rebuild last

revalidatePath('/blog/my-post') marks one route. revalidateTag('post:my-post', ...) targets tagged data on however many pages use it. From a Route Handler, both only mark entries, and pages render again on request. A tag shared by 5,000 pages doesn't set off 5,000 renders at once.

Which event should clear which tag depends on the site. On one headless CMS site I worked on, editing the "About" page only needed that page's path, an article also affected the listings, and contact details showed up on every page.

Tag by entity and by list

// lib/posts.ts (Next.js 15, or 16 without cacheComponents)
import { unstable_cache } from 'next/cache'
import { db } from '@/lib/db'
const CMS_URL = process.env.CMS_URL

export const tags = {
  posts: 'posts', // every list of posts, including the sitemap
  post: (slug: string) => `post:${slug}`, // one post, in every locale
  settings: 'settings', // header, footer, contact details
}

export async function getPost(locale: string, slug: string) {
  const res = await fetch(`${CMS_URL}/posts/${slug}?locale=${locale}`, {
    next: { revalidate: 86400, tags: [tags.post(slug)] },
  })
  if (res.status === 404) return null
  if (!res.ok) throw new Error(`post ${slug}: ${res.status}`)
  return res.json()
}

export async function getPostSlugs(): Promise<string[]> {
  const res = await fetch(`${CMS_URL}/posts/slugs`, { next: { revalidate: 86400, tags: [tags.posts] } })
  return res.json()
}

export const getSettings = unstable_cache(
  async (locale: string) => db.settings.findFirst({ where: { locale } }),
  ['settings'],
  { revalidate: 86400, tags: [tags.settings] },
)

Each tag starts with the entity type. My first version on a marketplace site used the bare slug (tags: [slug]), which worked because slugs there were unique site-wide, but with post: in front tags won't collide the day they aren't. The locale stays out of the tag, so one call refreshes every language. Anything you might refresh early needs a tag: that site's homepage data was cached for 12 hours with none, and refreshing it meant revalidating by path.

fetch tags have to be known before the request, so these use the slug. With cacheComponents in Next.js 16, cacheTag() runs after the data arrives and tagging by database ID gets easier.

When a post changes, the listings, the homepage widget and the sitemap go stale too (app/sitemap.ts is cached by default). I keep the mapping in one function:

// lib/revalidation.ts
import { tags } from '@/lib/posts'

export type ContentEvent =
  | { type: 'post.created' | 'post.deleted'; slug: string }
  | { type: 'post.updated'; slug: string; previousSlug?: string }
  | { type: 'settings.updated' }

export function targetsFor(event: ContentEvent) {
  switch (event.type) {
    case 'post.created':
    case 'post.deleted':
      return { tags: [tags.posts, tags.post(event.slug)], wholeSite: false }
    case 'post.updated': {
      const t = [tags.posts, tags.post(event.slug)]
      if (event.previousSlug) t.push(tags.post(event.previousSlug))
      return { tags: t, wholeSite: false }
    }
    case 'settings.updated':
      return { tags: [tags.settings], wholeSite: true }
  }
}

A slug change invalidates the old slug as well, and the old URL regenerates as a 404 or a redirect. Creating a post invalidates its own tag, because a request for that slug before the post existed may have cached an empty result.

Verify the webhook signature and map known events

// app/api/revalidate/route.ts
import { createHmac, timingSafeEqual } from 'node:crypto'
import { revalidatePath, revalidateTag } from 'next/cache'
import { targetsFor, type ContentEvent } from '@/lib/revalidation'

function validSignature(body: string, signature: string | null) {
  const secret = process.env.REVALIDATE_SECRET
  if (!secret || !signature) return false
  const expected = Buffer.from(createHmac('sha256', secret).update(body).digest('hex'))
  const given = Buffer.from(signature)
  return given.length === expected.length && timingSafeEqual(given, expected)
}

export async function POST(req: Request) {
  const body = await req.text() // verify the raw body, not re-serialized JSON
  if (!validSignature(body, req.headers.get('x-signature'))) {
    return Response.json({ ok: false }, { status: 401 })
  }
  const targets = targetsFor(JSON.parse(body) as ContentEvent)
  if (!targets) return Response.json({ ok: false }, { status: 400 })

  for (const tag of targets.tags) revalidateTag(tag, { expire: 0 }) // Next 15: revalidateTag(tag)
  if (targets.wholeSite) revalidatePath('/', 'layout')

  return Response.json({ ok: true, ...targets, at: new Date().toISOString() })
}

On Next.js 15, revalidateTag(tag) expires the entry immediately. Next.js 16 deprecates the one-argument form: 'max' serves stale data while refreshing in the background, and { expire: 0 } expires it right away, which is what the docs suggest for webhooks. updateTag in 16 only works in Server Actions, so it suits an admin form inside the app better.

Left open, this endpoint lets anyone make your origin and CMS re-render every page. I export only POST so the secret stays out of URLs and access logs, check an HMAC of the raw body with timingSafeEqual, and map known event types to tags.

The snippet above uses as ContentEvent, which is a type assertion, not JSON validation. Catch malformed JSON and validate each event's fields before calling targetsFor in production. Never pass a tag or path from the body straight into revalidateTag. Rate-limit it at the proxy too, since a bulk import can fire hundreds of webhooks in a minute.

The response lists the tags with a timestamp, the first thing I check when an edit doesn't show up.

revalidatePath('/', 'layout') invalidates every page under the root layout, and the backend takes a burst of requests as they regenerate. I keep it for site-wide data like the footer.

With type set, Next.js matches the route's file path, not the URL. My old shortcut called revalidatePath('/news', 'layout') while the route was defined under app/[locale]/(group)/news/, so it didn't match anything and Next.js didn't complain. It needed revalidatePath('/[locale]/(group)/news', 'layout').

Locales and new posts

A literal path has to include the locale the way the route sees it. If the proxy hides the default locale and rewrites /about to /vi/about, the path to revalidate is still /vi/about.

// lib/localized-paths.ts
import { revalidatePath } from 'next/cache'

const LOCALES = ['en', 'vi'] as const

// Route paths as Next.js sees them: the [locale] segment is always there,
// even when the proxy hides the default locale from public URLs.
export function revalidateEveryLocale(path: string) {
  for (const locale of LOCALES) {
    revalidatePath(`/${locale}${path === '/' ? '' : path}`)
  }
}

// One page in every language
revalidateEveryLocale('/about')

// Every post page in every language: a file path pattern plus a type
revalidatePath('/[locale]/blog/[slug]', 'page')

generateStaticParams only runs at build time. New posts appear through dynamicParams (default true), which renders a slug missing at build on its first request and caches it. My shop site caps generateStaticParams at 1,000 slugs and leaves the rest to dynamicParams. With cacheComponents, dynamicParams is gone and generateStaticParams must return at least one param.

A revalidate of a few hours stays as a safety net, because webhooks get lost when the CMS goes down or a deploy restarts the app, and a direct database edit sends none.

Fresh on the server, old for the reader

An open tab keeps its loaded RSC payloads, and prefetched static pages are reused for 5 minutes (staleTimes.static). For stock levels and prices I skip ISR HTML entirely and let the client fetch them from an uncached Route Handler with a short Cache-Control.

Next.js sends ISR pages with s-maxage equal to the revalidate time, and static pages with one year. A CDN that honours it keeps serving old HTML, so purge it from the same webhook or don't let it hold HTML for long. With several instances, each has its own cache and a webhook only hits one of them, so you need a shared cacheHandler.

Images annoy me the most. The next/image cache has no invalidation API, so an image replaced under the same URL can live until minimumCacheTTL (4 hours in Next.js 16, 60 seconds in 15). Upload replacements under a new file name.

Read the headers to find the stale layer

Test with next build && next start, because next dev renders on every request:

curl -sI https://example.com/blog/my-post | grep -i -E 'x-nextjs-cache|cache-control'
# x-nextjs-cache: HIT    served from cache
# x-nextjs-cache: STALE  served the old copy, regenerating in the background
# x-nextjs-cache: MISS   rendered now, not in the cache yet

After a revalidation you should see STALE or MISS, then HIT with new content. HIT with old content means the revalidation didn't match anything, like my /news shortcut. No header means the route is dynamic and the stale part is the data cache. NEXT_PRIVATE_DEBUG_CACHE=1 logs cache hits and misses on the server.

The projects here all run Next.js 15. The Next.js 16 behaviour comes from the docs, not from production.

  • Next.js
  • Caching
  • ISR
  • Revalidation
  • App Router
  • CMS

I'm Tuấn (Venn), a web developer in Ho Chi Minh City. I mostly build Next.js sites and web apps, and I take freelance work.

Work with me

More posts

  1. 01Guide4 min read

    Deploying Next.js and NestJS to AWS EC2 with Docker Compose

    How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.

  2. 02Guide4 min read

    How I store OAuth tokens for social media APIs in NestJS

    OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.

  3. 03vennee.dev3 min read

    llms.txt on my Next.js site, and now Lighthouse grades it

    vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.