Skip to the code

A CMS webhook that revalidates the journal

Leaf and Kettle's journal comes from a headless CMS. Its pages are cached for max and tagged, as @/lib/journal shows: the list at /journal under posts, each post's page under post:<slug>, also when there's no such post yet, so a 404 is cached too, and every post an author wrote under author:<id>. When an editor changes something, the CMS calls POST /api/revalidate. Write that Route Handler, app/api/revalidate/route.ts.

The CMS sends Authorization: Bearer <secret>, with CMS_WEBHOOK_SECRET from @/lib/env. Check it first, before reading the body, comparing with safeEqual from @/lib/secrets. Without it, or with anything else, answer 401 with { error: "Unauthorized" }.

The body is JSON like { "event": "post.updated", "slug": "first-flush" }. Revalidate these tags, in this order, with these profiles. post.updated: post:<slug> and posts, both "max", since an edit to a live post can show a moment late. post.published: post:<slug> with { expire: 0 }, because that page has a 404 cached and the editor opens the new post right away, then posts with "max". post.unpublished: post:<slug> and posts, both { expire: 0 }, since a post pulled from the journal must stop showing at once. author.updated, which sends author instead of slug: author:<author> with "max". Then answer 200 with { revalidated: [...] }, the tags in that order.

Answer 400 and revalidate nothing for a body that isn't a JSON object ({ error: "Bad payload" }), an event not in that list ({ error: "Unknown event" }), or a slug ({ error: "Bad slug" }) or author ({ error: "Bad author" }) that isn't made of lowercase letters, digits, and dashes, or would make a tag longer than 256 characters. Tags are case-sensitive, and Next.js never attaches a tag over 256 characters, so revalidating either kind would quietly do nothing, while a 400 shows up in the CMS's delivery log.

POST /api/revalidate
Authorization: Bearer whsec_…
{ "event": "post.unpublished", "slug": "first-flush" }
 
→ revalidateTag("post:first-flush", { expire: 0 })
→ revalidateTag("posts", { expire: 0 })
→ 200 { "revalidated": ["post:first-flush", "posts"] }

The app's other files

lib/env.ts, read-only. Import it as @/lib/env.

/** The secret the CMS sends with every call: process.env.CMS_WEBHOOK_SECRET in a real app. */
export const CMS_WEBHOOK_SECRET = "whsec_journal_7c1e9a40";

lib/secrets.ts, read-only. Import it as @/lib/secrets.

/**
 * Whether two strings are equal, taking the same time wherever they differ, so the response time
 * can't reveal how much of a guessed secret was right.
 */
export function safeEqual(a: string, b: string): boolean {
  let difference = a.length ^ b.length;
  for (let index = 0; index < Math.max(a.length, b.length); index++) {
    difference |= (a.charCodeAt(index) || 0) ^ (b.charCodeAt(index) || 0);
  }
  return difference === 0;
}

lib/journal.ts, read-only. Import it as @/lib/journal.

import { cacheLife, cacheTag } from "next/cache";
 
export type Post = { slug: string; title: string; author: string; body: string };
 
/** The journal's posts, as the CMS last sent them: a stand-in for its API. */
export const posts: Post[] = [
  { slug: "first-flush", title: "First flush, first sip", author: "mei", body: "Darjeeling's spring picking is in." },
  { slug: "cold-brew-oolong", title: "Cold-brew oolong in four steps", author: "ravi", body: "Leaves, cold water, a night in the fridge." },
];
 
/** The journal, /journal: every post's title. */
export async function getPosts() {
  "use cache";
  cacheTag("posts");
  cacheLife("max");
  return posts.map(({ slug, title }) => ({ slug, title }));
}
 
/**
 * A post's page, /journal/<slug>, with its author's bio. null renders the 404 page, and is cached
 * under the same tag, so a post that isn't published yet is cached as a 404.
 */
export async function getPost(slug: string) {
  "use cache";
  cacheLife("max");
  cacheTag(`post:${slug}`);
  const post = posts.find((entry) => entry.slug === slug) ?? null;
  if (post) cacheTag(`author:${post.author}`);
  return post;
}

What the tests check

  1. an edited post and the list are marked stale with max
    const hook = (body, authorization = "Bearer " + CMS_WEBHOOK_SECRET) =>
      POST(
        request("/api/revalidate", {
          method: "POST",
          headers: { "content-type": "application/json", ...(authorization === null ? {} : { authorization }) },
          body: typeof body === "string" ? body : JSON.stringify(body),
        }),
      );
    const revalidated = () => cache.calls.map((call) => [call.name, ...call.args]);
    const response = await hook({ event: "post.updated", slug: "first-flush" });
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ revalidated: ["post:first-flush", "posts"] });
    expect(revalidated()).toEqual([
      ["revalidateTag", "post:first-flush", "max"],
      ["revalidateTag", "posts", "max"],
    ]);
    
  2. a new post's page expires at once, and the list catches up
    const hook = (body, authorization = "Bearer " + CMS_WEBHOOK_SECRET) =>
      POST(
        request("/api/revalidate", {
          method: "POST",
          headers: { "content-type": "application/json", ...(authorization === null ? {} : { authorization }) },
          body: typeof body === "string" ? body : JSON.stringify(body),
        }),
      );
    const revalidated = () => cache.calls.map((call) => [call.name, ...call.args]);
    const response = await hook({ event: "post.published", slug: "spring-oolong" });
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ revalidated: ["post:spring-oolong", "posts"] });
    expect(revalidated()).toEqual([
      ["revalidateTag", "post:spring-oolong", { expire: 0 }],
      ["revalidateTag", "posts", "max"],
    ]);
    
  3. a pulled post expires at once, its page and the list
    const hook = (body, authorization = "Bearer " + CMS_WEBHOOK_SECRET) =>
      POST(
        request("/api/revalidate", {
          method: "POST",
          headers: { "content-type": "application/json", ...(authorization === null ? {} : { authorization }) },
          body: typeof body === "string" ? body : JSON.stringify(body),
        }),
      );
    const revalidated = () => cache.calls.map((call) => [call.name, ...call.args]);
    const response = await hook({ event: "post.unpublished", slug: "first-flush" });
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ revalidated: ["post:first-flush", "posts"] });
    expect(revalidated()).toEqual([
      ["revalidateTag", "post:first-flush", { expire: 0 }],
      ["revalidateTag", "posts", { expire: 0 }],
    ]);
    
  4. an author's change marks their posts stale
    const hook = (body, authorization = "Bearer " + CMS_WEBHOOK_SECRET) =>
      POST(
        request("/api/revalidate", {
          method: "POST",
          headers: { "content-type": "application/json", ...(authorization === null ? {} : { authorization }) },
          body: typeof body === "string" ? body : JSON.stringify(body),
        }),
      );
    const revalidated = () => cache.calls.map((call) => [call.name, ...call.args]);
    const response = await hook({ event: "author.updated", author: "mei" });
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ revalidated: ["author:mei"] });
    expect(revalidated()).toEqual([["revalidateTag", "author:mei", "max"]]);
    
  5. answers 401 without the right secret, before reading the body
    const hook = (body, authorization = "Bearer " + CMS_WEBHOOK_SECRET) =>
      POST(
        request("/api/revalidate", {
          method: "POST",
          headers: { "content-type": "application/json", ...(authorization === null ? {} : { authorization }) },
          body: typeof body === "string" ? body : JSON.stringify(body),
        }),
      );
    const revalidated = () => cache.calls.map((call) => [call.name, ...call.args]);
    const attempts = [null, "", "Bearer", "Bearer wrong-secret", CMS_WEBHOOK_SECRET, "Basic " + CMS_WEBHOOK_SECRET, "Bearer " + CMS_WEBHOOK_SECRET + "x", "Bearer  " + CMS_WEBHOOK_SECRET];
    for (const authorization of attempts) {
      const response = await hook("this is not JSON", authorization);
      expect(response.status).toBe(401);
      expect(await response.json()).toEqual({ error: "Unauthorized" });
    }
    expect(cache.calls).toEqual([]);
    
  6. answers 400 for a payload it can't use, and revalidates nothing
    const hook = (body, authorization = "Bearer " + CMS_WEBHOOK_SECRET) =>
      POST(
        request("/api/revalidate", {
          method: "POST",
          headers: { "content-type": "application/json", ...(authorization === null ? {} : { authorization }) },
          body: typeof body === "string" ? body : JSON.stringify(body),
        }),
      );
    const revalidated = () => cache.calls.map((call) => [call.name, ...call.args]);
    const cases = [
      ["stock changed", "Bad payload"],
      ["[]", "Bad payload"],
      ["null", "Bad payload"],
      ['"post.updated"', "Bad payload"],
      [{ event: "post.deleted", slug: "first-flush" }, "Unknown event"],
      [{ event: "toString", slug: "first-flush" }, "Unknown event"],
      [{ slug: "first-flush" }, "Unknown event"],
      [{ event: "post.updated" }, "Bad slug"],
      [{ event: "post.updated", slug: "First-Flush" }, "Bad slug"],
      [{ event: "post.updated", slug: "first flush" }, "Bad slug"],
      [{ event: "post.updated", slug: 42 }, "Bad slug"],
      [{ event: "post.published", slug: "a".repeat(252) }, "Bad slug"],
      [{ event: "author.updated", slug: "mei" }, "Bad author"],
      [{ event: "author.updated", author: "a".repeat(250) }, "Bad author"],
    ];
    for (const [body, error] of cases) {
      const response = await hook(body);
      expect(response.status).toBe(400);
      expect(await response.json()).toEqual({ error });
    }
    expect(cache.calls).toEqual([]);
    
  7. accepts ids whose tags are exactly 256 characters
    const hook = (body, authorization = "Bearer " + CMS_WEBHOOK_SECRET) =>
      POST(
        request("/api/revalidate", {
          method: "POST",
          headers: { "content-type": "application/json", ...(authorization === null ? {} : { authorization }) },
          body: typeof body === "string" ? body : JSON.stringify(body),
        }),
      );
    const revalidated = () => cache.calls.map((call) => [call.name, ...call.args]);
    expect((await hook({ event: "post.updated", slug: "a".repeat(251) })).status).toBe(200);
    expect((await hook({ event: "author.updated", author: "b".repeat(249) })).status).toBe(200);
    expect(cache.calls.map((call) => call.args[0].length)).toEqual([256, 5, 256]);
    

Learn more

app/api/revalidate/route.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).