From de73f1ebcb65f519ee6752236c4e7f21f031b882 Mon Sep 17 00:00:00 2001 From: leejpsd Date: Fri, 13 Nov 2026 15:29:19 +0900 Subject: [PATCH] fix(seed): write routes under the key the runtime actually looks up Two independent problems made seeded routes unreadable. Next.js 16.3.8+ scopes response-cache keys by source route (/route-cache///$/) and never asks a custom cache handler for a bare pathname. The build records the exact key in each artifact's .meta (routeCache.key). App Router and Pages Router routes are now seeded under that key when it is present. Before 16.3.8, routes are stored and looked up under Next's normalized page path, where / is /index. The seed wrote the root route under /, so it was never read, and read /index-prefixed routes from the wrong files. The artifact path and the fallback key now follow normalizePagePath. No option is needed for either case. Closes #16 Co-authored-by: jeroendegloire <13023723+jeroendegloire@users.noreply.github.com> --- .changeset/seed-page-path-normalization.md | 5 + .changeset/seed-route-scoped-keys.md | 5 + src/seed/index.ts | 36 ++++- tests/unit/seed.test.ts | 159 ++++++++++++++++++++- 4 files changed, 198 insertions(+), 7 deletions(-) create mode 100644 .changeset/seed-page-path-normalization.md create mode 100644 .changeset/seed-route-scoped-keys.md diff --git a/.changeset/seed-page-path-normalization.md b/.changeset/seed-page-path-normalization.md new file mode 100644 index 0000000..bd6257f --- /dev/null +++ b/.changeset/seed-page-path-normalization.md @@ -0,0 +1,5 @@ +--- +"@leejpsd/nextjs-cache-handler": patch +--- + +Fix seeding of the root route on Next.js versions before 16.3.8. Those versions store and look up prerendered routes under Next's normalized page path, where `/` is `/index`, but the seed wrote the root route under `/`, so it was never read and the first request to the home page after a deploy was a `MISS`. Routes whose path starts with `/index` were also read from the wrong build files. The seed now uses the same normalization as Next for both the artifact path and the key. diff --git a/.changeset/seed-route-scoped-keys.md b/.changeset/seed-route-scoped-keys.md new file mode 100644 index 0000000..bed03ed --- /dev/null +++ b/.changeset/seed-route-scoped-keys.md @@ -0,0 +1,5 @@ +--- +"@leejpsd/nextjs-cache-handler": patch +--- + +`seedBuildOutput` and the `seed` CLI now write prerendered App Router and Pages Router routes under the route-scoped key that Next.js 16.3.8+ records in each build artifact (`routeCache.key` in `.meta`). From 16.3.8 the runtime never asks a custom cache handler for a bare pathname, so pathname-keyed seeds were written but never read and the first request after a deploy was still a `MISS` (#16). Builds from older Next.js versions carry no such metadata and are seeded under the page path as before; no option or flag is needed. diff --git a/src/seed/index.ts b/src/seed/index.ts index 1f00b0b..0bfb45a 100644 --- a/src/seed/index.ts +++ b/src/seed/index.ts @@ -19,6 +19,13 @@ * PPR `.segments/`) → APP_PAGE records * - Pages Router routes (`.next/server/pages/.{html,json}`) → PAGES * - fetch cache (`.next/cache/fetch-cache/`) → FETCH records + * + * Route keys: Next.js 16.3.8+ scopes response-cache keys by source route + * (`/route-cache///$/`) and never asks a custom handler + * for a bare pathname. The build records the exact key in each artifact's + * `.meta` (`routeCache.key`), so routes are seeded under that key when it is + * present. Builds from older Next versions carry no such key and are looked + * up by normalized page path (`/` is `/index`), which is what gets used then. */ import fs from "node:fs"; @@ -80,8 +87,16 @@ function clampTtl(revalidate: number | false | undefined): number { return MIN_TTL_SEC; } +/** + * Mirrors Next's `normalizePagePath` for a concrete prerendered route: + * `/` → `/index`, `/index/sub` → `/index/index/sub`. This is where the build + * stores the route's artifacts and, before Next.js 16.3.8, the key Next's + * IncrementalCache derives for it. + */ function routeToFileBase(route: string): string { - return route === "/" ? "/index" : route; + if (route === "/") return "/index"; + if (/^\/index(\/|$)/.test(route)) return `/index${route}`; + return route; } function readMeta(file: string): { @@ -89,6 +104,7 @@ function readMeta(file: string): { headers?: Record; segmentPaths?: string[]; postponed?: string; + routeCache?: { key?: unknown }; } | null { try { return JSON.parse(fs.readFileSync(file, "utf8")) as ReturnType; @@ -97,6 +113,17 @@ function readMeta(file: string): { } } +/** + * The key the runtime will look this route up by. Next.js 16.3.8+ writes it + * into the build artifact's `.meta`; without it (older Next, or a missing or + * malformed `.meta`) the lookup key is the normalized page path, i.e. the + * same `base` the artifact files are stored under. + */ +function resolveRouteKey(base: string, meta: ReturnType): string { + const key = meta?.routeCache?.key; + return typeof key === "string" && key.length > 0 ? key : base; +} + async function writeRecord( client: RedisClientLike, key: string, @@ -166,6 +193,7 @@ export async function seedBuildOutput(options: SeedOptions): Promise { skippedIncomplete: 1, // "/broken" errors: [], }); - expect(client.kv.has("next-incremental:entry:deploy-1:/")).toBe(true); + expect(client.kv.has("next-incremental:entry:deploy-1:/index")).toBe(true); expect(client.kv.has("next-incremental:entry:deploy-1:/blog")).toBe(true); expect(client.kv.has("next-incremental:entry:deploy-1:/legacy")).toBe(true); expect(client.kv.has("next-incremental:entry:deploy-1:abc123")).toBe(true); @@ -124,7 +124,8 @@ describe("seedBuildOutput", () => { buildNamespace: "deploy-1", }); const h = new Handler(); - const out = await h.get("/", { kind: "APP_PAGE" }); + // Next < 16.3.8 asks for the normalized page path: "/" is "/index". + const out = await h.get("/index", { kind: "APP_PAGE" }); expect(out).not.toBeNull(); const value = out!.value as { kind: string; html: string; status: number }; expect(value.kind).toBe("APP_PAGE"); @@ -150,9 +151,9 @@ describe("seedBuildOutput", () => { it("NX: never overwrites an existing (newer) live entry", async () => { const client = mock(); - client.kv.set("next-incremental:entry:d:/", "live-entry"); + client.kv.set("next-incremental:entry:d:/index", "live-entry"); const summary = await seedBuildOutput({ client: () => client, dir, buildNamespace: "d" }); - expect(client.kv.get("next-incremental:entry:d:/")).toBe("live-entry"); + expect(client.kv.get("next-incremental:entry:d:/index")).toBe("live-entry"); expect(summary.skippedExisting).toBe(1); expect(summary.routes).toBe(1); // "/blog" still seeded }); @@ -208,3 +209,153 @@ describe("seedBuildOutput", () => { ).rejects.toThrow(/next build/); }); }); + +describe("seedBuildOutput — route-scoped keys (Next.js 16.3.8+, #16)", () => { + // Key shapes as emitted by `next build` on 16.4.6. + const APP_KEY = + "/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index"; + const PAGES_KEY = + "/route-cache/PAGES/15486b37abb374f051d18b6144500dc7d20cbed764c27b2cea8a3bd79ab9af48/$/legacy"; + + function writeAppMeta(routeCache: unknown) { + fs.writeFileSync( + path.join(dir, "server", "app", "index.meta"), + JSON.stringify({ status: 200, headers: { "x-next-cache-tags": "home" }, routeCache }) + ); + } + + it("seeds an App Router route under meta.routeCache.key, not the pathname", async () => { + writeAppMeta({ + key: APP_KEY, + owner: { kind: "APP_PAGE", sourceRoute: "/page" }, + isFallback: false, + }); + + const client = mock(); + const summary = await seedBuildOutput({ client: () => client, dir, buildNamespace: "deploy-1" }); + + expect(summary).toMatchObject({ routes: 2, pages: 1, errors: [] }); + expect(client.kv.has(`next-incremental:entry:deploy-1:${APP_KEY}`)).toBe(true); + expect(client.kv.has("next-incremental:entry:deploy-1:/index")).toBe(false); + // "/blog" has no routeCache metadata → still seeded by page path. + expect(client.kv.has("next-incremental:entry:deploy-1:/blog")).toBe(true); + }); + + it("seeds a Pages Router route under the key in its .meta", async () => { + fs.writeFileSync( + path.join(dir, "server", "pages", "legacy.meta"), + JSON.stringify({ + routeCache: { + key: PAGES_KEY, + owner: { kind: "PAGES", sourceRoute: "/legacy" }, + isFallback: false, + }, + }) + ); + + const client = mock(); + const summary = await seedBuildOutput({ client: () => client, dir, buildNamespace: "deploy-1" }); + + expect(summary).toMatchObject({ routes: 2, pages: 1, errors: [] }); + expect(client.kv.has(`next-incremental:entry:deploy-1:${PAGES_KEY}`)).toBe(true); + expect(client.kv.has("next-incremental:entry:deploy-1:/legacy")).toBe(false); + }); + + it("the handler serves the seeded entry when asked for the scoped key", async () => { + writeAppMeta({ key: APP_KEY }); + + const client = mock(); + await seedBuildOutput({ client: () => client, dir, buildNamespace: "deploy-1" }); + + const Handler = createIncrementalCacheHandler({ + client: () => client, + abortTimeoutMs: 100, + buildNamespace: "deploy-1", + }); + const h = new Handler(); + const out = await h.get(APP_KEY, { kind: "APP_PAGE" }); + expect(out).not.toBeNull(); + const value = out!.value as { kind: string; html: string }; + expect(value.html).toContain("home"); + // The page path is not a key the 16.3.8+ runtime ever asks for. + h.resetRequestCache(); + expect(await h.get("/index", { kind: "APP_PAGE" })).toBeNull(); + }); + + it.each([ + ["an empty key", { key: "" }], + ["a non-string key", { key: 42 }], + ["no key", {}], + ["a null routeCache", null], + ])("falls back to the page path for %s", async (_label, routeCache) => { + writeAppMeta(routeCache); + + const client = mock(); + const summary = await seedBuildOutput({ client: () => client, dir, buildNamespace: "deploy-1" }); + + expect(summary.errors).toEqual([]); + expect(client.kv.has("next-incremental:entry:deploy-1:/index")).toBe(true); + }); + + it("an unreadable Pages .meta falls back to the page path", async () => { + fs.writeFileSync(path.join(dir, "server", "pages", "legacy.meta"), "{not json"); + + const client = mock(); + const summary = await seedBuildOutput({ client: () => client, dir, buildNamespace: "deploy-1" }); + + expect(summary).toMatchObject({ pages: 1, errors: [] }); + expect(client.kv.has("next-incremental:entry:deploy-1:/legacy")).toBe(true); + }); +}); + +describe("seedBuildOutput — page path normalization (Next.js < 16.3.8)", () => { + // Next stores and looks up prerendered routes under normalizePagePath(): + // "/" → "/index", "/index" → "/index/index", "/index/sub" → "/index/index/sub". + function addIndexNamedRoutes() { + const app = path.join(dir, "server", "app"); + const manifestPath = path.join(dir, "prerender-manifest.json"); + const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as { + routes: Record; + }; + manifest.routes["/index"] = { initialRevalidateSeconds: 60, dataRoute: "/index.rsc" }; + manifest.routes["/index/sub"] = { initialRevalidateSeconds: 60, dataRoute: "/index/sub.rsc" }; + fs.writeFileSync(manifestPath, JSON.stringify(manifest)); + + fs.mkdirSync(path.join(app, "index", "index"), { recursive: true }); + fs.writeFileSync(path.join(app, "index", "index.html"), "index-named"); + fs.writeFileSync(path.join(app, "index", "index.meta"), JSON.stringify({ status: 200 })); + fs.writeFileSync(path.join(app, "index", "index", "sub.html"), "index-sub"); + fs.writeFileSync(path.join(app, "index", "index", "sub.meta"), JSON.stringify({ status: 200 })); + } + + async function seededHtml(client: MockRedisClient, key: string): Promise { + const Handler = createIncrementalCacheHandler({ + client: () => client, + abortTimeoutMs: 100, + buildNamespace: "deploy-1", + }); + const out = await new Handler().get(key, { kind: "APP_PAGE" }); + return out ? (out.value as { kind: string; html: string }).html : null; + } + + it("seeds the root route under /index, the key the runtime asks for", async () => { + const client = mock(); + await seedBuildOutput({ client: () => client, dir, buildNamespace: "deploy-1" }); + + expect(client.kv.has("next-incremental:entry:deploy-1:/index")).toBe(true); + expect(client.kv.has("next-incremental:entry:deploy-1:/")).toBe(false); + expect(await seededHtml(client, "/index")).toContain("home"); + }); + + it("an /index-prefixed route reads its own files and gets its own key", async () => { + addIndexNamedRoutes(); + + const client = mock(); + const summary = await seedBuildOutput({ client: () => client, dir, buildNamespace: "deploy-1" }); + + expect(summary).toMatchObject({ routes: 4, skippedExisting: 0, errors: [] }); + expect(await seededHtml(client, "/index")).toContain("home"); + expect(await seededHtml(client, "/index/index")).toContain("index-named"); + expect(await seededHtml(client, "/index/index/sub")).toContain("index-sub"); + }); +});