Why Next.js 16 revalidateTag('max') Serves Stale Sitemaps (Use { expire: 0 })
The Next.js 16 caching trap that hides newly published CMS posts from crawlers on first request — and the zero-rebuild Postgres + webhook fix.
If you upgraded a Next.js 16 blog or CMS-backed storefront and replaced the deprecated single-argument revalidateTag(tag) call with revalidateTag(tag, "max"), your webhook can return HTTP 200 and still serve the old /sitemap.xml and /blog page on the very next request. That stale response is not a Vercel CDN bug — it is how Next.js 16's recommended "max" cache-life profile is designed to behave.
When Googlebot, an external automation, or your own publish verification hits /sitemap.xml right after a CMS publish, stale-while-revalidate means Hit #1 gets yesterday's URLs. Passing revalidateTag(tag, { expire: 0 }) in your webhook Route Handler paired with export const dynamic = "force-dynamic" in app/sitemap.ts forces immediate cache expiration so the very first GET sees the new post with zero Vercel rebuilds.
Use 'max' (or updateTag inside Server Actions) when serving stale UI for one extra request is harmless. Use { expire: 0 } in webhook Route Handlers whenever crawlers or users hit /sitemap.xml immediately after publishing.
The Next.js 16 Route Handler invalidation rule
01 · THE CACHE PROFILE TRAP
Why revalidateTag(tag, 'max') Returns Old Data on Hit #1
In Next.js 16, calling revalidateTag(tag) with one argument is deprecated and requires a second profile argument. While Next.js recommends "max" for most user-triggered mutations, "max" applies a one-year stale-while-revalidate window: Next.js marks the cache entry stale, hands the stale payload immediately to the very next caller, and runs fresh database work asynchronously in the background for caller #2.
Inside Server Actions you can call updateTag(tag) for immediate read-your-own-writes expiration — but updateTag() throws outside Server Actions. Webhook endpoints triggered by an external CMS (or a separate admin service) run inside Route Handlers, which leaves revalidateTag(tag, { expire: 0 }) as the exact mechanism for an immediate blocking purge.
| API Call | Where It Works | Hit #1 Response | Best For |
|---|---|---|---|
| revalidateTag(tag, "max") | Server Actions & Route Handlers | Serves stale data; refreshes in background | Tolerant UI lists under high read load |
| revalidateTag(tag, { expire: 0 }) | Server Actions & Route Handlers | Expires immediately; Hit #1 fetches fresh data | CMS webhooks, /sitemap.xml, & /blog invalidation |
| updateTag(tag) | Server Actions only | Expires immediately + refreshes client router cache | In-app Server Action form mutations |
| revalidateTag(tag) [1 arg] | Deprecated in Next.js 16 | Legacy immediate expiry with deprecation warning | Migrate to updateTag or { expire: 0 } / 'max' |
02 · ZERO-REBUILD PIPELINE
Making app/sitemap.ts Live Without Rebuilding Vercel
Even with { expire: 0 }, there is a second silent failure mode: by default, if your app/sitemap.ts calls unstable_cache without reading dynamic request data or forcing dynamic rendering, Next.js builds /sitemap.xml as a static route (○) during deployment. When I split this portfolio's custom Postgres CMS from the public Next.js site, making sitemap.ts truly zero-rebuild took two explicit guarantees.
Force Dynamic Evaluation
app/sitemap.ts
Export dynamic = 'force-dynamic' so /sitemap.xml runs on demand with max-age=0 while still reading from a tagged cache between publishes.
- Queries status = 'published' AND deleted_at IS NULL
- Enforces published_at <= NOW() for scheduled posts
- Emits per-post lastModified from updatedAt
HMAC Verification + { expire: 0 }
app/api/revalidate/route.ts
Verify x-revalidate-signature with crypto.timingSafeEqual, purge all shared tags with { expire: 0 }, and call revalidatePath per route.
- Purges blog:posts, blog:sitemap, blog:index, blog:home
- Calls revalidatePath('/sitemap.xml') & '/blog'
- Brand-new slugs render dynamically via ISR
import type { MetadataRoute } from "next";
import { getAllBlogPosts } from "@/lib/blog";
import { siteConfig } from "@/lib/data";
// Prevents freezing /sitemap.xml at build time
export const dynamic = "force-dynamic";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const lastModified = new Date();
const posts = (await getAllBlogPosts()).filter((post) => !post.noindex);
return [
{ url: siteConfig.url, lastModified, changeFrequency: "weekly", priority: 1 },
{ url: `${siteConfig.url}/blog`, lastModified, changeFrequency: "weekly", priority: 0.8 },
...posts.map((post) => ({
url: `${siteConfig.url}/blog/${post.slug}`,
lastModified: new Date(post.updatedAt || post.publishedAt || lastModified),
changeFrequency: "monthly" as const,
priority: 0.7,
})),
];
}import { createHmac, timingSafeEqual } from "node:crypto";
import { revalidatePath, revalidateTag } from "next/cache";
import { NextResponse } from "next/server";
export async function POST(request: Request) {
const secret = process.env.PORTFOLIO_REVALIDATE_SECRET?.trim();
if (!secret) {
return NextResponse.json({ error: "Missing secret" }, { status: 503 });
}
const rawBody = await request.text();
const sig = request.headers.get("x-revalidate-signature") ?? "";
const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
const valid =
sig.length === expected.length &&
timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
if (!valid) {
return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
}
const { tags = [], slugs = [] } = JSON.parse(rawBody) as {
tags?: string[];
slugs?: string[];
};
for (const tag of new Set(["blog:posts", "blog:index", "blog:home", "blog:sitemap", ...tags])) {
// Immediate purge so Hit #1 on /sitemap.xml and /blog never gets stale data
revalidateTag(tag, { expire: 0 });
}
revalidatePath("/");
revalidatePath("/blog");
revalidatePath("/sitemap.xml");
for (const slug of slugs) {
if (slug) revalidatePath(`/blog/${slug}`);
}
return NextResponse.json({ revalidated: true });
}03 · NEW SLUGS WITHOUT REBUILDS
How Brand-New Post URLs Work on Request #1
A common follow-up question is whether generateStaticParams() on app/blog/[slug]/page.tsx blocks brand-new articles created after deployment. Because dynamicParams defaults to true in Next.js App Router, any published slug absent at build time renders cleanly on demand using the exact same Postgres query and ISR lifecycle (export const revalidate = 60) — plus a permanentRedirect lookup if you ever rename a live slug later.
04 · VERIFICATION IN PRODUCTION
How to Verify First-Hit Consistency Yourself
Confirm /sitemap.xml builds as dynamic (ƒ)
Run next build cleanlyInspect the route table from next build. /sitemap.xml should display the ƒ (Dynamic) symbol rather than ○ (Static), and serve Cache-Control: public, max-age=0, must-revalidate in HTTP headers.
- Avoid reading cookies() unless needed — force-dynamic is explicit
Test publish -> revalidate -> single GET
Check x-vercel-cache on Hit #1Publish a temporary post, POST to your HMAC-signed /api/revalidate endpoint, and immediately run ONE uncached GET against /sitemap.xml and /blog.
- With 'max', Hit #1 often returns HIT/stale and misses the new URL
- With { expire: 0 }, /blog returns REVALIDATED and /sitemap.xml returns MISS with the new URL on Hit #1
Test delete/unpublish -> revalidate -> single GET
Zero ghost URLs in Google Search ConsoleUnpublish or delete the test post, call /api/revalidate again, and confirm the URL vanishes on Hit #1 without triggering a Vercel rebuild.
- Unpublished drafts never linger in sitemap.xml
This exact zero-rebuild architecture is what powers the blog you are reading right now — connecting a standalone Next.js admin CMS and Neon Postgres directly to my portfolio. If you want to explore more real production engineering notes, check out Why AI Agent UIs Break in Production, browse case studies, or get in touch.