Files
cloudflare__vinext/tests/app-router-next-config-dev.test.ts
T
Nathan Nguyen b7ef466742 fix(pages): preserve app props for GSSP requests (#1996)
* fix(pages): preserve app props for gssp requests

* docs(pages): update _next/data comment to reflect full props envelope

* fix(pages-router): preserve _app.getInitialProps during stale ISR regeneration

Stale ISR background regeneration called getStaticProps directly and rendered
HTML and __NEXT_DATA__ with only the page's pageProps, dropping app-level
props from _app.getInitialProps. The foreground path already loads
_app.getInitialProps first and merges its props, but the background
regeneration path skipped that step.

Extract a shared loadPagesAppInitialRenderProps helper from the production
foreground path and reuse it during background regeneration in both
pages-page-data.ts and dev-server.ts. This ensures regenerated pages carry the
same full props envelope as the original render.

Add a regression test in tests/pages-page-data.test.ts.

* fix(pages-router): skip _app.getInitialProps on ISR cache hits

The foreground render path ran _app.getInitialProps before consulting the
ISR cache, so fresh and stale cache hits executed userland App data code
even though the cached HTML was returned verbatim. That wasted work on the
hot path and ran side-effecting App code whose result the cached response
never reflected.

The eager App initial-props load happened up front, ahead of the HIT and
STALE short-circuits. Defer it until the request will actually render:
load it lazily inside the getServerSideProps / getStaticProps /
getInitialProps branches, after the cache short-circuits return.
Stale-while-revalidate already re-runs it inside the regeneration closure,
so regenerated HTML still carries app-level props. The dev SSR handler and
the production page-data resolver are updated in lockstep to preserve
dev/prod parity.

Tests cover the fresh-HIT skip and the stale foreground-skip vs
regeneration-run split at the page-data resolver boundary.

* refactor(pages-router): extract dev App getInitialProps loader into a tested helper

The dev SSR handler ran _app.getInitialProps inside an inline closure that
mutated captured pageProps/renderProps and read res directly, so its lazy
load-only-on-render behavior could only be covered by a heavyweight
integration test that vi.doMock'd the isr-cache and file-matcher modules —
a mock cascade with little signal.

Move the decision into loadDevAppInitialProps in pages-get-initial-props.ts.
It takes the App component, req/res, and an injected AppTree builder (keeping
React out of the module) and returns a discriminated result —
skip / response-sent / render — that the caller applies. The dev-server
closure is now thin glue: build the React tree, delegate, apply the result.

Adds focused unit tests that drive the helper through its real boundary
(genuine getInitialProps functions, plain req/res inputs) — no module mocks:
the skip path, App/page prop merging, pageProps normalization, the
response-sent short-circuit, and the router/ctx wiring passed to userland.

* fix(pages): preserve app props across data requests

* fix(pages): preserve fallback cache expiry

* fix(pages): preserve dev app context during ISR

* fix(pages): hydrate middleware rewrite fallbacks

* fix(pages): retarget middleware data rewrites

* fix(pages): preserve rewrite query on navigation

* fix(pages): finalize rewrite navigation state

* fix(pages): resolve rewrite data targets consistently

* fix(pages): await static props during regeneration

* fix(pages): preserve original query in resolved url

* Revert "fix(pages): await static props during regeneration"

This reverts commit cbdcdf65cd.

* test(app): cover rewrite params in app search

---------

Co-authored-by: James <james@eli.cx>
2026-06-14 20:17:05 +01:00

163 lines
6.9 KiB
TypeScript

import { type ViteDevServer } from "vite";
import { beforeAll, afterAll, describe, expect, it } from "vitest";
import { APP_FIXTURE_DIR, fetchHtml, startFixtureServer } from "./helpers.js";
describe("App Router next.config.js features (dev server integration)", () => {
let server: ViteDevServer;
let baseUrl: string;
beforeAll(async () => {
// Uses the permanent next.config.ts in the app-basic fixture.
// That config includes redirects, rewrites, and headers needed by
// both these Vitest tests and the Playwright E2E tests.
({ server, baseUrl } = await startFixtureServer(APP_FIXTURE_DIR, { appRouter: true }));
}, 30000);
afterAll(async () => {
await server?.close();
});
it("applies redirects from next.config.js (permanent)", async () => {
const res = await fetch(`${baseUrl}/old-about`, { redirect: "manual" });
expect(res.status).toBe(308);
expect(res.headers.get("location")).toContain("/about");
});
it("applies redirects with dynamic params", async () => {
const res = await fetch(`${baseUrl}/old-blog/hello`, { redirect: "manual" });
expect(res.status).toBe(307);
expect(res.headers.get("location")).toContain("/blog/hello");
});
it("applies redirects with repeated dynamic params in the destination", async () => {
const res = await fetch(`${baseUrl}/repeat-redirect/hello`, { redirect: "manual" });
expect(res.status).toBe(307);
expect(res.headers.get("location")).toContain("/blog/hello/hello");
});
it("applies beforeFiles rewrites from next.config.js", async () => {
const res = await fetch(`${baseUrl}/rewrite-about`);
expect(res.status).toBe(200);
const html = await res.text();
expect(html).toContain("About");
});
it("appends unused rewrite source params to App Router searchParams", async () => {
const res = await fetch(`${baseUrl}/rewrite-search-param/hello?lang=en&_rsc=test-token`);
expect(res.status).toBe(200);
const html = await res.text();
expect(html).toMatch(/Results for:\s*(<!--\s*-->)?\s*from-rewrite/);
expect(html).toMatch(/Lang:\s*(<!--\s*-->)?\s*en/);
expect(html).toMatch(/Term:\s*(<!--\s*-->)?\s*hello/);
});
it("applies rewrites with repeated dynamic params in the destination", async () => {
const res = await fetch(`${baseUrl}/repeat-rewrite/hello`);
expect(res.status).toBe(200);
const html = await res.text();
expect(html).toContain("hello/hello");
expect(html).toMatch(/Segments:.*2/);
});
it("applies afterFiles rewrites from next.config.js", async () => {
const res = await fetch(`${baseUrl}/after-rewrite-about`);
expect(res.status).toBe(200);
const html = await res.text();
expect(html).toContain("About");
});
// In App Router execution order, beforeFiles rewrites run after middleware.
// has/missing conditions on beforeFiles rules should therefore evaluate against
// middleware-modified headers/cookies, not the original pre-middleware request.
it("beforeFiles rewrite has/missing conditions see middleware-injected cookies", async () => {
// Without ?mw-auth, middleware does NOT inject mw-before-user=1.
// The has:[cookie:mw-before-user] beforeFiles rule should NOT match → no rewrite.
const noAuthRes = await fetch(`${baseUrl}/mw-gated-before`);
expect(noAuthRes.status).toBe(404);
// With ?mw-auth, middleware injects mw-before-user=1 into request cookies.
// The has:[cookie:mw-before-user] beforeFiles rule SHOULD match → rewrite to /about.
const authRes = await fetch(`${baseUrl}/mw-gated-before?mw-auth`);
expect(authRes.status).toBe(200);
const html = await authRes.text();
expect(html).toContain("About");
});
// Fallback rewrites run after middleware and after a 404 from route matching.
// has/missing conditions on fallback rules should evaluate against
// middleware-modified headers/cookies, not the original pre-middleware request.
it("fallback rewrite has/missing conditions see middleware-injected cookies", async () => {
// Without ?mw-auth, middleware does NOT inject mw-fallback-user=1.
// The has:[cookie:mw-fallback-user] fallback rule should NOT match → 404.
const noAuthRes = await fetch(`${baseUrl}/mw-gated-fallback`);
expect(noAuthRes.status).toBe(404);
// With ?mw-auth, middleware injects mw-fallback-user=1 into request cookies.
// The has:[cookie:mw-fallback-user] fallback rule SHOULD match → rewrite to /about.
const authRes = await fetch(`${baseUrl}/mw-gated-fallback?mw-auth`);
expect(authRes.status).toBe(200);
const html = await authRes.text();
expect(html).toContain("About");
});
it("fallback rewrites targeting Pages routes still work in mixed app/pages projects", async () => {
const noAuthRes = await fetch(`${baseUrl}/mw-gated-fallback-pages`);
expect(noAuthRes.status).toBe(404);
const { res, html } = await fetchHtml(`${baseUrl}`, "/mw-gated-fallback-pages?mw-auth", {
headers: {
authorization: "Bearer secret",
cookie: "a=1; b=2",
},
});
expect(res.status).toBe(200);
expect(html).toContain("Pages Header Override Delete");
expect(html).toContain('"page":"/pages-header-override-delete"');
});
it("applies custom headers from next.config.js on API routes", async () => {
const res = await fetch(`${baseUrl}/api/hello`);
expect(res.headers.get("x-custom-header")).toBe("vinext-app");
});
it("applies custom headers from next.config.js on page routes", async () => {
const res = await fetch(`${baseUrl}/about`);
expect(res.headers.get("x-page-header")).toBe("about-page");
});
it("does not redirect for non-matching paths", async () => {
const res = await fetch(`${baseUrl}/about`);
expect(res.status).toBe(200);
expect(res.redirected).toBe(false);
});
// ── Percent-encoded paths should be decoded before config matching ──
it("percent-encoded redirect path is decoded before config matching", async () => {
// /%6Fld-%61bout decodes to /old-about → /about (permanent redirect)
const res = await fetch(`${baseUrl}/%6Fld-%61bout`, { redirect: "manual" });
expect(res.status).toBe(308);
expect(res.headers.get("location")).toContain("/about");
});
it("percent-encoded header path is decoded before config matching", async () => {
// /%61bout decodes to /about → X-Page-Header: about-page
const res = await fetch(`${baseUrl}/%61bout`);
expect(res.headers.get("x-page-header")).toBe("about-page");
});
it("encoded slashes stay within a single segment for config header matching", async () => {
const res = await fetch(`${baseUrl}/api%2Fhello`);
expect(res.headers.get("x-custom-header")).toBeNull();
});
it("percent-encoded rewrite path is decoded before config matching", async () => {
// /rewrite-%61bout decodes to /rewrite-about → /about (beforeFiles rewrite)
const res = await fetch(`${baseUrl}/rewrite-%61bout`);
expect(res.status).toBe(200);
const html = await res.text();
expect(html).toContain("About");
});
});