Skip to content

fix: map route segment revalidate to Nitro routeRules SWR#669

Open
Divkix wants to merge 6 commits intocloudflare:mainfrom
Divkix:fix/nitro-route-rules-swr
Open

fix: map route segment revalidate to Nitro routeRules SWR#669
Divkix wants to merge 6 commits intocloudflare:mainfrom
Divkix:fix/nitro-route-rules-swr

Conversation

@Divkix
Copy link
Contributor

@Divkix Divkix commented Mar 23, 2026

Summary

  • Add generateNitroRouteRules() to convert ISR routes (App Router export const revalidate = N and Pages Router getStaticProps with revalidate) to Nitro's routeRules format with swr values
  • Add vinext:nitro-route-rules writeBundle hook that emits routeRules to .output/nitro.json when Nitro plugin is detected

Fixes

Closes #648

Testing

  • All 9 new generateNitroRouteRules unit tests pass
  • All 85 build-report tests pass
  • All 176 routing + build-report tests pass

- Add generateNitroRouteRules() to convert ISR routes to Nitro format
- Add writeBundle hook (vinext:nitro-route-rules) that emits routeRules
  to .output/nitro.json when Nitro plugin is detected
- Closes cloudflare#648
Copilot AI review requested due to automatic review settings March 23, 2026 04:33
@pkg-pr-new
Copy link

pkg-pr-new bot commented Mar 23, 2026

Open in StackBlitz

npm i https://pkg.pr.new/vinext@669

commit: 5ff1d4e

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds Nitro integration to propagate Next.js ISR revalidate values into Nitro’s routeRules (as swr) so caching behavior is preserved in Nitro deployments.

Changes:

  • Introduces generateNitroRouteRules() to convert build-report ISR rows into Nitro routeRules with swr.
  • Adds a vinext:nitro-route-rules build hook that merges generated rules into .output/nitro.json when the Nitro plugin is detected.
  • Adds unit tests for generateNitroRouteRules().

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.

File Description
tests/build-report.test.ts Adds unit tests covering generateNitroRouteRules() mapping behavior.
packages/vinext/src/build/report.ts Adds NitroRouteRules type and generateNitroRouteRules() implementation.
packages/vinext/src/index.ts Adds a post-build hook to emit/merge ISR-derived routeRules into Nitro output.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

export function generateNitroRouteRules(rows: RouteRow[]): NitroRouteRules {
const rules: NitroRouteRules = {};
for (const row of rows) {
if (row.type === "isr" && row.revalidate !== undefined && row.revalidate > 0) {
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generateNitroRouteRules currently allows any number > 0, which would include Infinity. Infinity cannot be represented in JSON (JSON.stringify turns it into null), so writing these rules into .output/nitro.json would silently generate an invalid/incorrect config. Consider explicitly requiring Number.isFinite(row.revalidate) (and > 0) when generating SWR rules.

Suggested change
if (row.type === "isr" && row.revalidate !== undefined && row.revalidate > 0) {
if (
row.type === "isr" &&
typeof row.revalidate === "number" &&
Number.isFinite(row.revalidate) &&
row.revalidate > 0
) {

Copilot uses AI. Check for mistakes.
Comment on lines +818 to +826
it("handles ISR routes with Infinity revalidate (treated as static)", () => {
const rows = [
{ pattern: "/static", type: "static" as const },
{ pattern: "/isr", type: "isr" as const, revalidate: Infinity },
];
const result = generateNitroRouteRules(rows);
expect(result).toEqual({
"/isr": { swr: Infinity },
});
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test case constructs an ISR row with revalidate: Infinity, but classifyPagesRoute/classifyAppRoute classify revalidate === Infinity as static, so buildReportRows should never emit an isr row with Infinity. Keeping this test encourages behavior that will also serialize incorrectly to nitro.json (Infinity becomes null). Suggest removing this test or updating it to assert no rule is produced for Infinity.

Suggested change
it("handles ISR routes with Infinity revalidate (treated as static)", () => {
const rows = [
{ pattern: "/static", type: "static" as const },
{ pattern: "/isr", type: "isr" as const, revalidate: Infinity },
];
const result = generateNitroRouteRules(rows);
expect(result).toEqual({
"/isr": { swr: Infinity },
});
it("does not generate swr rules for ISR routes with Infinity revalidate (treated as static)", () => {
const rows = [
{ pattern: "/static", type: "static" as const },
{ pattern: "/isr", type: "isr" as const, revalidate: Infinity },
];
const result = generateNitroRouteRules(rows);
expect(result).toEqual({});

Copilot uses AI. Check for mistakes.
Comment on lines +790 to +794
{ pattern: "/blog/posts/[slug]", type: "isr" as const, revalidate: 20 },
];
expect(generateNitroRouteRules(rows)).toEqual({
"/blog/posts": { swr: 10 },
"/blog/posts/[slug]": { swr: 20 },
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RouteRow.pattern in vinext uses :param syntax (e.g. "/blog/:slug") rather than Next's bracket syntax ("/blog/[slug]"). Using bracket patterns in this test doesn't match real buildReportRows() output and could mask issues with routeRules generation for dynamic routes. Suggest updating the expected patterns to :slug (and :slug+ / :slug* for catch-alls) to reflect actual route patterns.

Suggested change
{ pattern: "/blog/posts/[slug]", type: "isr" as const, revalidate: 20 },
];
expect(generateNitroRouteRules(rows)).toEqual({
"/blog/posts": { swr: 10 },
"/blog/posts/[slug]": { swr: 20 },
{ pattern: "/blog/posts/:slug", type: "isr" as const, revalidate: 20 },
];
expect(generateNitroRouteRules(rows)).toEqual({
"/blog/posts": { swr: 10 },
"/blog/posts/:slug": { swr: 20 },

Copilot uses AI. Check for mistakes.
nitroJson.routeRules = {};
}

Object.assign(nitroJson.routeRules, routeRules);
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Object.assign(nitroJson.routeRules, routeRules) replaces any existing per-route rule object wholesale. If Nitro (or user config) already set other fields for a route (e.g. headers/redirects/cors), they will be lost when an ISR rule is added. Consider merging per-route keys instead (e.g. keep existing rule object and only set/override the swr field).

Suggested change
Object.assign(nitroJson.routeRules, routeRules);
for (const [route, rule] of Object.entries(routeRules)) {
nitroJson.routeRules[route] = {
...(nitroJson.routeRules[route] ?? {}),
...rule,
};
}

Copilot uses AI. Check for mistakes.
Comment on lines +4423 to +4430
if (fs.existsSync(nitroOutputPath)) {
try {
nitroJson = JSON.parse(fs.readFileSync(nitroOutputPath, "utf-8"));
} catch {
// ignore parse errors
}
}

Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The nitro.json parse error is silently ignored and then the file is rewritten, which can clobber an existing Nitro config (dropping fields other than routeRules) if the JSON is temporarily invalid/partially written. Consider failing the build or at least logging a warning and skipping the write when parsing fails, to avoid producing a broken .output/nitro.json.

Suggested change
if (fs.existsSync(nitroOutputPath)) {
try {
nitroJson = JSON.parse(fs.readFileSync(nitroOutputPath, "utf-8"));
} catch {
// ignore parse errors
}
}
let nitroJsonParseError = false;
if (fs.existsSync(nitroOutputPath)) {
try {
nitroJson = JSON.parse(fs.readFileSync(nitroOutputPath, "utf-8"));
} catch (error) {
nitroJsonParseError = true;
console.warn(
`[vinext] Failed to parse existing nitro.json at ${nitroOutputPath}:`,
error instanceof Error ? error.message : error,
);
}
}
if (nitroJsonParseError) {
// Skip writing to avoid clobbering an existing but temporarily invalid nitro.json
return;
}

Copilot uses AI. Check for mistakes.
Divkix added 4 commits March 22, 2026 23:18
- Add Number.isFinite() guard to prevent Infinity serializing to null in JSON
- Replace Object.assign with per-route deep merge to preserve existing Nitro route fields
- Add parse error handling with warning + skip to avoid clobbering invalid nitro.json
- Fix Infinity test case to assert no rule is produced (reflects real behavior)
- Fix test pattern from [slug] to :slug (matches AppRoute.pattern syntax)

Note: shims.test.ts failures are pre-existing on main (React 19 SSR hook issues)
@james-elicx
Copy link
Collaborator

/bigbonk review

Copy link
Contributor

@ask-bonk ask-bonk bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Good feature — mapping ISR revalidate values to Nitro's swr is the right approach for Nitro deployment parity. The generateNitroRouteRules function is clean and well-guarded (with Number.isFinite and > 0 checks). I see the Copilot feedback on merge behavior and parse-error handling has already been addressed. A few issues remain.

Summary of issues

  1. Duplicate execution (medium): The writeBundle hook fires for both rsc and ssr environments. In App Router builds (where hasNitroPlugin implies isMultiEnv), this re-scans all routes and re-writes nitro.json twice — wasted work and a potential ordering issue if Nitro hasn't finished its own writeBundle between the two calls.
  2. Missing mkdirSync for .output/ (medium): If Nitro hasn't created .output/ before this hook runs, fs.writeFileSync throws ENOENT. Need fs.mkdirSync(path.dirname(nitroOutputPath), { recursive: true }) before the write.
  3. Route pattern format mismatch (needs investigation): vinext patterns use :param syntax (/blog/:slug), but Nitro routeRules use glob-style patterns (/blog/**). Passing vinext-internal patterns directly may not work as expected in Nitro's route matching. This should be validated against Nitro's route matching behavior.
  4. No integration test for the writeBundle hook: The unit tests for generateNitroRouteRules are solid, but there's no test verifying the writeBundle hook actually writes correct nitro.json output (file I/O, merge logic, directory creation). Consider at minimum a test that mocks fs or uses a temp directory.

if (!hasNitroPlugin) return;

const envName = this.environment?.name;
if (envName !== "rsc" && envName !== "ssr") return;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This hook runs for both rsc and ssr environments. In an App Router + Nitro build, both environments exist (since hasNitroPlugin sets isMultiEnv = true), so this hook will fire twice — re-scanning all routes and re-writing nitro.json redundantly.

The other writeBundle hooks that accept both environments (like vinext:server-manifest) do so intentionally because they need the options.dir which differs per environment. This hook doesn't use options.dir at all — it writes to a fixed .output/nitro.json path.

Pick one environment to gate on (probably rsc since App Router is the primary target, and for Pages Router only ssr exists):

Suggested change
if (envName !== "rsc" && envName !== "ssr") return;
if (envName !== "rsc" && envName !== "ssr") return;
// Avoid running twice in multi-environment builds (App Router has both
// rsc and ssr). Prefer rsc; fall back to ssr for Pages Router builds.
if (envName === "ssr" && this.environment?.config?.environments?.rsc) return;

Alternatively, a simpler approach: just gate on rsc || (ssr && !hasAppDir) using the existing hasAppDir closure variable.

};
}

fs.writeFileSync(nitroOutputPath, JSON.stringify(nitroJson, null, 2));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If .output/ doesn't exist yet when this hook runs (possible if Nitro's own writeBundle hasn't executed first), this will throw ENOENT. Add a mkdirSync call before writing:

Suggested change
fs.writeFileSync(nitroOutputPath, JSON.stringify(nitroJson, null, 2));
fs.mkdirSync(path.dirname(nitroOutputPath), { recursive: true });
fs.writeFileSync(nitroOutputPath, JSON.stringify(nitroJson, null, 2));


if (!appDir && !pagesDir) return;

let appRoutes: any[] = [];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: any[] loses type safety. The router functions return typed arrays (AppRoute[] and Route[]). Consider:

Suggested change
let appRoutes: any[] = [];
let appRoutes: Awaited<ReturnType<typeof appRouter>> = [];
let pageRoutes: Awaited<ReturnType<typeof pagesRouter>> = [];
let apiRoutes: Awaited<ReturnType<typeof apiRouter>> = [];

Or import the AppRoute and Route types from the routing modules.

Number.isFinite(row.revalidate) &&
row.revalidate > 0
) {
rules[row.pattern] = { swr: row.revalidate };
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This passes vinext's internal route pattern (:param syntax like /blog/:slug) directly as the Nitro routeRules key. Nitro uses its own route matching which expects glob-style patterns (/blog/**) or exact paths.

For static ISR routes (no dynamic segments) this works fine. But for dynamic ISR routes like /blog/:slug, Nitro won't recognize the :slug parameter syntax. You'll likely need a conversion step here, e.g.:

  • /blog/:slug/blog/**
  • /docs/:slug+/docs/**
  • /docs/:slug*/docs/**

Please verify against Nitro's routeRules docs to confirm the expected format. If this is intentionally deferred, add a TODO comment.

it("does not generate swr rules for ISR routes with Infinity revalidate", () => {
const rows = [
{ pattern: "/static", type: "static" as const },
{ pattern: "/isr", type: "isr" as const, revalidate: Infinity },
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good that you test the Infinity edge case after incorporating the Number.isFinite guard. Worth noting in a comment that this case should never arise from buildReportRows in practice (since classifyAppRoute maps revalidate === Infinity to type: "static"), but it's still valid as a defensive test for generateNitroRouteRules in isolation.

Suggested change
{ pattern: "/isr", type: "isr" as const, revalidate: Infinity },
// In practice, buildReportRows never produces an ISR row with Infinity
// (classifyAppRoute maps Infinity to "static"), but generateNitroRouteRules
// should handle it defensively since Infinity serializes to null in JSON.
{ pattern: "/isr", type: "isr" as const, revalidate: Infinity },

@ask-bonk
Copy link
Contributor

ask-bonk bot commented Mar 23, 2026

Review posted successfully. Here's a summary of the feedback I left on PR #669:

Key issues raised

  1. Duplicate execution — The writeBundle hook fires for both rsc and ssr environments, causing redundant route scanning and double-writing of nitro.json in App Router builds. Suggested gating to run only once per build.

  2. Missing .output/ directory creationfs.writeFileSync will throw ENOENT if .output/ doesn't exist yet when the hook runs. Needs mkdirSync with { recursive: true }.

  3. Route pattern format mismatch — vinext uses :param syntax (/blog/:slug) but Nitro's routeRules expect glob-style patterns (/blog/**). Dynamic ISR routes will likely not match correctly in Nitro without a conversion step. Flagged for investigation/validation.

  4. Type safety — The any[] variable declarations for routes lose type information unnecessarily.

  5. Test comment clarification — Noted that the Infinity test case is a valid defensive test but should document that buildReportRows never produces this combination in practice.

github run

…ype safety, and tests

- Add hasAppDir guard to prevent duplicate writeBundle execution in App Router multi-env builds
- Add mkdirSync with recursive:true before writing nitro.json to handle missing .output/ dir
- Use proper AppRoute[] and Route[] types instead of any[]
- Add clarifying comment on Infinity revalidate defensive test case
- Add TODO note (verified with URLPattern test) that vinext :param syntax works natively with Nitro's rou3 router
- Add integration tests for nitro.json file I/O: directory creation, content correctness, merge behavior, and empty routeRules handling
@james-elicx
Copy link
Collaborator

/bigbonk review

Copy link
Contributor

@ask-bonk ask-bonk bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Good idea — mapping ISR revalidate to Nitro swr routeRules is the right approach. The generateNitroRouteRules function itself is clean and well-guarded. The previous review feedback (duplicate execution, mkdirSync, merge semantics, parse error handling) has been incorporated. However, there are two issues that need to be addressed before this is mergeable.

Issues

  1. Route pattern format mismatch (blocking) — The comment on line 846 claims "Nitro uses rou3" but Nitro actually uses radix3 (the older library) with toRouteMatcher. While :param syntax technically works in radix3's route matcher, it's undocumented for routeRules. The documented and conventional format is /** glob patterns for dynamic segments. This needs investigation and either a conversion step or explicit validation that :param syntax works correctly with the specific Nitro version being targeted.

  2. Redundant route scanning at build time (design concern) — The writeBundle hook re-scans app/ and pages/ directories from scratch, even though the exact same scanning already happened during the build (for the build report in cli.ts). This is unnecessary I/O and file-system analysis. Consider either (a) caching the route rows from the build report step and passing them through, or (b) at minimum documenting why the re-scan is intentional.

  3. Top-level import of build/report.js in index.ts — The main plugin file now eagerly imports buildReportRows, generateNitroRouteRules, and findDir from build/report.js. Note that cli.ts deliberately uses dynamic import() for printBuildReport to avoid loading build-report code during dev. This new static import means the entire report module (including classifyAppRoute, classifyPagesRoute, regex patterns, etc.) is loaded at plugin initialization time, including in dev mode where it's never used. Consider using a dynamic import inside the writeBundle handler instead.


// Note: Nitro uses rou3 (URLPattern-compatible) which natively supports vinext's
// :param syntax. URLPattern test confirms /blog/:slug matches /blog/my-post correctly.
// Patterns like /blog/:slug work directly in Nitro routeRules without conversion.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is inaccurate. Nitro uses radix3 (specifically toRouteMatcher from radix3), not rou3. While :param syntax technically works in radix3's internal parser (it creates PLACEHOLDER nodes), it is undocumented for Nitro's routeRules. All Nitro documentation and examples use either exact paths (/blog) or glob patterns (/blog/**).

The :param syntax also has a subtle semantic difference: /blog/:slug matches exactly one segment (/blog/foo but not /blog/foo/bar), while /blog/** matches any depth. For ISR routes with dynamic segments, the glob form is likely what users expect.

Please either:

  1. Add a conversion step (:slug/**, :slug+/**, etc.) and update the comment, or
  2. Validate that :param syntax works correctly with the specific Nitro/radix3 version and document the intentional choice with a link to supporting evidence
Suggested change
// Patterns like /blog/:slug work directly in Nitro routeRules without conversion.
// Note: Nitro uses radix3's toRouteMatcher for routeRules matching. While radix3
// internally parses :param syntax, Nitro's documented format uses exact paths ("/blog")
// and glob patterns ("/blog/**"). Static ISR routes (no dynamic segments) work as-is.
// TODO: Dynamic ISR routes need pattern conversion (:slug → /**) for Nitro compatibility.

import { generateClientEntry as _generateClientEntry } from "./entries/pages-client-entry.js";
import { appRouter, invalidateAppRouteCache } from "./routing/app-router.js";
import { appRouter, invalidateAppRouteCache, type AppRoute } from "./routing/app-router.js";
import { buildReportRows, generateNitroRouteRules, findDir } from "./build/report.js";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a new static import that pulls in the entire build/report.js module at plugin initialization time. In cli.ts, printBuildReport is deliberately loaded via dynamic import() (line 900 of report.ts) to avoid loading build/report code during dev.

Since this code is only needed in the writeBundle hook (build-only), consider using a dynamic import inside the handler instead:

const { buildReportRows, generateNitroRouteRules, findDir } = await import("./build/report.js");

This keeps the dev server lean.

let apiRoutes: Route[] = [];

if (appDir) {
appRoutes = await appRouter(appDir, nextConfig?.pageExtensions);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This re-scans app/ and pages/ directories and re-reads every route file's source code to extract revalidate values — the same work that printBuildReport already does in cli.ts after the build completes. In a large project this could add noticeable time to the build.

Consider storing the buildReportRows result from the build report step (or from an earlier build phase) and making it available to this hook, rather than re-scanning from scratch. Even a simple module-level cache (set by the build report, read by this hook) would eliminate the duplicate work.

If re-scanning is intentional (e.g., because the hook runs in a different process or the ordering isn't guaranteed), a comment explaining why would be helpful.

return JSON.parse(fsSync.readFileSync(outputPath, "utf-8"));
}

function mergeNitroRouteRules(routeRules: NitroRouteRules): void {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This mergeNitroRouteRules helper reimplements the merge logic from index.ts but with different error handling behavior — it silently ignores parse errors (line 873-874), while the actual hook warns and returns early. The tests exercise this local copy, not the real code path.

This means:

  • The mkdirSync fix in the actual hook isn't tested (this helper has its own mkdirSync)
  • The parse-error-and-bail behavior in the actual hook isn't tested
  • If someone changes the merge logic in index.ts, these tests still pass

Consider extracting the merge logic into a shared, testable function (e.g., mergeNitroRouteRules in build/report.ts) that both the writeBundle hook and these tests use. That way the tests exercise the real code.

if (envName === "ssr" && hasAppDir) return;

const buildRoot = this.environment?.config?.root ?? process.cwd();
const nitroOutputPath = path.join(buildRoot, ".output", "nitro.json");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: this.environment?.config?.root returns the environment-specific root, which should be the same as the project root in normal builds. But for clarity and consistency with how printBuildReport works (it receives root explicitly in cli.ts), consider using the resolved config root that's already available in the plugin closure. Is there a root variable available from the configResolved hook?

@ask-bonk
Copy link
Contributor

ask-bonk bot commented Mar 24, 2026

Review posted successfully. Here's a summary of the feedback I left on PR #669:

Key issues raised

  1. Route pattern format mismatch (blocking) — The comment claims "Nitro uses rou3" but Nitro actually uses radix3 with toRouteMatcher. While :param syntax technically works in radix3's internal parser, it's undocumented for Nitro's routeRules. All Nitro docs/examples use exact paths or /** glob patterns. Dynamic ISR routes (e.g., /blog/:slug) need a conversion step to /blog/** or explicit validation.

  2. Redundant route scanning — The writeBundle hook re-scans app/ and pages/ directories from scratch, duplicating the same work that printBuildReport already does in cli.ts. Suggested caching or sharing the results.

  3. Top-level import bloatbuild/report.js is now statically imported in index.ts, pulling the entire report module (classification regexes, etc.) into the dev server where it's never used. cli.ts deliberately uses dynamic import() for this. Suggested using dynamic import inside the writeBundle handler.

  4. Test isolation concern — The file I/O tests reimplement the merge logic locally (mergeNitroRouteRules helper) with different error-handling behavior than the actual hook. Tests don't exercise the real code path. Suggested extracting the merge logic into a shared testable function.

  5. Minor: config root — Suggested using the plugin closure's resolved root instead of this.environment?.config?.root.

github run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Next.js Route Segment Config (revalidate) is not mapped to Nitro routeRules (SWR)

3 participants