Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions integration/vite-prerender-redirect-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { readFile } from "node:fs/promises";
import path from "node:path";

import { js } from "./helpers/create-fixture";
import { build, createProject, reactRouterConfig, test } from "./helpers/vite";
import { expect } from "@playwright/test";

for (let { template, previewServerPrerendering } of [
{ template: "vite-5-template", previewServerPrerendering: false },
{ template: "vite-6-template", previewServerPrerendering: true },
{ template: "rsc-vite-framework", previewServerPrerendering: false },
] as const) {
test.describe(`prerender redirects (${template})`, () => {
test("preserves redirect destinations and refresh timing", async ({
page,
}) => {
let location =
'https://example.invalid/?q="a&b"&content=<title>Example</title>';
let cwd = await createProject(
{
"react-router.config.ts": reactRouterConfig({
future: {
unstable_previewServerPrerendering: previewServerPrerendering,
},
prerender: ["/markup", "/permanent", "/temporary", "/target"],
}),
"app/routes/markup.tsx": js`
import { redirect } from "react-router";
export function loader() {
return redirect(${JSON.stringify(location)});
}
export default function Route() { return null; }
`,
"app/routes/permanent.tsx": js`
import { redirect } from "react-router";
export function loader() {
return redirect("/target?first=1&second=2", 301);
}
export default function Route() { return null; }
`,
"app/routes/temporary.tsx": js`
import { redirect } from "react-router";
export function loader() { return redirect("/target"); }
export default function Route() { return null; }
`,
"app/routes/target.tsx": js`
export default function Route() { return <h1>Target</h1>; }
`,
},
template,
);
let buildResult = build({ cwd });
expect(buildResult.status, buildResult.stderr.toString()).toBe(0);
let baseUrl = "http://prerender.test";
// Serve the generated artifacts as a static host would, in both modes.
await page.route(`${baseUrl}/**`, async (route) => {
let pathname = new URL(route.request().url()).pathname;
await route.fulfill({
path: path.join(
cwd,
"build/client",
pathname,
path.extname(pathname) ? "" : "index.html",
),
});
});
await page.route("https://example.invalid/**", (route) => route.abort());
await page.goto(`${baseUrl}/markup`, { waitUntil: "domcontentloaded" });
let result = await page.evaluate(() => {
let anchor = document.querySelector("a")!;
return {
attributes: anchor.getAttributeNames(),
href: anchor.getAttribute("href"),
title: document.title,
text: anchor.textContent,
refresh: document
.querySelector('meta[http-equiv="refresh"]')!
.getAttribute("content"),
titleElements: document.querySelectorAll("title").length,
};
});
expect(result).toEqual({
attributes: ["href"],
href: location,
title: `Redirecting to: ${location}`,
text: expect.stringContaining(location),
refresh: `2;url=${location}`,
titleElements: 1,
});
expect(result.text).toContain("/markup");

for (let [route, delay] of [
["permanent", 0],
["temporary", 2],
] as const) {
let html = await readFile(
path.join(cwd, `build/client/${route}/index.html`),
"utf8",
);
expect(html).toContain(`content="${delay};url=/target`);
}
await page.goto(`${baseUrl}/permanent`);
await expect(page).toHaveURL(`${baseUrl}/target?first=1&second=2`);
await expect(page.getByRole("heading", { name: "Target" })).toBeVisible();
});

test("validates redirect URL protocols", async () => {
let protocol = "JaVaScRiPt";
// Use an RSC resource route to exercise prerendering directly.
let cwd = await createProject(
{
"react-router.config.ts": reactRouterConfig({
prerender: ["/unsupported"],
future: {
unstable_previewServerPrerendering: previewServerPrerendering,
},
}),
"app/routes/unsupported.tsx": js`
import { redirect } from "react-router";
export function loader() {
return redirect(${JSON.stringify(`${protocol}:void(0)`)});
}
${template === "rsc-vite-framework" ? "" : "export default function Route() { return null; }"}
`,
},
template,
);
let result = build({ cwd });
expect(result.status).not.toBe(0);
expect(result.stderr.toString()).toMatch(
/Cannot prerender redirect for "\/unsupported\/?": unsafe URL protocol "javascript:"/,
);
});
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve handling of prerendered redirect destinations in Framework Mode and unstable RSC Framework Mode.
54 changes: 3 additions & 51 deletions packages/react-router-dev/vite/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ import { validatePluginOrder } from "./plugins/validate-plugin-order";
import { warnOnClientSourceMaps } from "./plugins/warn-on-client-source-maps";
import type { PrerenderRequest } from "./plugins/prerender";
import { prerender } from "./plugins/prerender";
import { getPrerenderRedirectHtml } from "./prerender-redirect";

export type LoadCssContents = (
viteDevServer: Vite.ViteDevServer,
Expand Down Expand Up @@ -2794,24 +2795,7 @@ export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
// approach used by Astro as well, so there's some precedent.
// https://github.com/withastro/roadmap/issues/466
// https://github.com/withastro/astro/blob/main/packages/astro/src/core/routing/3xx.ts
let location = response.headers.get("Location");
// A short delay causes Google to interpret the redirect as temporary.
// https://developers.google.com/search/docs/crawling-indexing/301-redirects#metarefresh
let delay = response.status === 302 ? 2 : 0;
let escapedLocation = escapeHtml(location ?? "");
let escapedPathname = escapeHtml(pathname);
html = `<!doctype html>
<head>
<title>Redirecting to: ${escapedLocation}</title>
<meta http-equiv="refresh" content="${delay};url=${escapedLocation}">
<meta name="robots" content="noindex">
</head>
<body>
<a href="${escapedLocation}">
Redirecting from <code>${escapedPathname}</code> to <code>${escapedLocation}</code>
</a>
</body>
</html>`;
html = getPrerenderRedirectHtml(response, pathname);
} else if (response.status !== 200) {
throw new Error(
`Prerender (html): Received a ${response.status} status code from ` +
Expand Down Expand Up @@ -3388,24 +3372,7 @@ async function prerenderRoute(
// approach used by Astro as well, so there's some precedent.
// https://github.com/withastro/roadmap/issues/466
// https://github.com/withastro/astro/blob/main/packages/astro/src/core/routing/3xx.ts
let location = response.headers.get("Location");
// A short delay causes Google to interpret the redirect as temporary.
// https://developers.google.com/search/docs/crawling-indexing/301-redirects#metarefresh
let delay = response.status === 302 ? 2 : 0;
let escapedLocation = escapeHtml(location ?? "");
let escapedNormalizedPath = escapeHtml(normalizedPath);
html = `<!doctype html>
<head>
<title>Redirecting to: ${escapedLocation}</title>
<meta http-equiv="refresh" content="${delay};url=${escapedLocation}">
<meta name="robots" content="noindex">
</head>
<body>
<a href="${escapedLocation}">
Redirecting from <code>${escapedNormalizedPath}</code> to <code>${escapedLocation}</code>
</a>
</body>
</html>`;
html = getPrerenderRedirectHtml(response, normalizedPath);
} else if (response.status !== 200) {
throw new Error(
`Prerender (html): Received a ${response.status} status code from ` +
Expand Down Expand Up @@ -4362,18 +4329,3 @@ function createSpaModeRequest(
metadata: { type: "spa", path: "/" },
};
}

// Note: Duplicated from react-router/lib/dom/ssr/markup
// Must be kept in sync with the original implementation.
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
const ESCAPE_LOOKUP: { [match: string]: string } = {
"&": "\\u0026",
">": "\\u003e",
"<": "\\u003c",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
};

function escapeHtml(html: string) {
return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
}
39 changes: 39 additions & 0 deletions packages/react-router-dev/vite/prerender-redirect-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { getPrerenderRedirectHtml } from "./prerender-redirect";

describe("prerender redirect HTML", () => {
test.each([
"data:text/plain,Example",
"file:///tmp/example.html",
"JaVa\tsCrIpT:void(0)",
"vbscript:0",
])("rejects unsupported redirect protocol in %s", (location) => {
expect(() =>
getPrerenderRedirectHtml(
new Response(null, { status: 302, headers: { Location: location } }),
"/redirect",
),
).toThrow("unsafe URL protocol");
});

test.each([
"../target",
"https://example.com/target",
"//example.com/target",
"mailto:hello@example.com",
])("preserves redirect target %s", (location) => {
let html = getPrerenderRedirectHtml(
new Response(null, { status: 301, headers: { Location: location } }),
"/source",
);
expect(html).toContain(`href="${location}"`);
});

test("escapes the source pathname as text", () => {
let html = getPrerenderRedirectHtml(
new Response(null, { status: 302, headers: { Location: "/target" } }),
'/source"&<name>',
);
expect(html).toContain("/source&quot;&amp;&lt;name&gt;");
expect(html).not.toContain("<name>");
});
});
61 changes: 61 additions & 0 deletions packages/react-router-dev/vite/prerender-redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Match invalidProtocols in react-router/lib/router/router.ts and also reject
// the legacy VBScript scheme. These utilities are not exported by react-router.
const invalidProtocols = new Set([
"about:",
"blob:",
"chrome:",
"chrome-untrusted:",
"content:",
"data:",
"devtools:",
"file:",
"filesystem:",
// eslint-disable-next-line no-script-url
"javascript:",
"vbscript:",
]);

// Keep in sync with escapeAttribute in react-router/lib/dom/ssr/markup.ts.
// HTML entities work in both text and double-quoted attributes;
// JavaScript escapes do not.
function escapeHtml(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}

export function getPrerenderRedirectHtml(response: Response, pathname: string) {
let location = response.headers.get("Location") ?? "";
let protocol: string | undefined;
try {
// Parse as the browser does, including case and embedded tabs/newlines.
protocol = new URL(location).protocol;
} catch {
// Relative URLs do not have a protocol.
}
if (protocol && invalidProtocols.has(protocol)) {
throw new Error(
`Cannot prerender redirect for ${JSON.stringify(pathname)}: unsafe URL protocol ${JSON.stringify(protocol)}`,
);
}

// A short delay causes Google to interpret the redirect as temporary.
// https://developers.google.com/search/docs/crawling-indexing/301-redirects#metarefresh
let delay = response.status === 302 ? 2 : 0;
let escapedLocation = escapeHtml(location);
let escapedPathname = escapeHtml(pathname);
return `<!doctype html>
<head>
<title>Redirecting to: ${escapedLocation}</title>
<meta http-equiv="refresh" content="${delay};url=${escapedLocation}">
<meta name="robots" content="noindex">
</head>
<body>
<a href="${escapedLocation}">
Redirecting from <code>${escapedPathname}</code> to <code>${escapedLocation}</code>
</a>
</body>
</html>`;
}
18 changes: 2 additions & 16 deletions packages/react-router-dev/vite/rsc/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { loadDotenv } from "../load-dotenv";
import { validatePluginOrder } from "../plugins/validate-plugin-order";
import { warnOnClientSourceMaps } from "../plugins/warn-on-client-source-maps";
import { prerender } from "../plugins/prerender";
import { getPrerenderRedirectHtml } from "../prerender-redirect";
import { getPrerenderPaths } from "../plugin";

const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
Expand Down Expand Up @@ -710,23 +711,8 @@ export function reactRouterRSCVitePlugin(): Vite.PluginOption[] {
// approach used by Astro as well, so there's some precedent.
// https://github.com/withastro/roadmap/issues/466
// https://github.com/withastro/astro/blob/main/packages/astro/src/core/routing/3xx.ts
let location = response.headers.get("Location");
// A short delay causes Google to interpret the redirect as temporary.
// https://developers.google.com/search/docs/crawling-indexing/301-redirects#metarefresh
let delay = response.status === 302 ? 2 : 0;
let redirectBody = isRedirect
? `<!doctype html>
<head>
<title>Redirecting to: ${location}</title>
<meta http-equiv="refresh" content="${delay};url=${location}">
<meta name="robots" content="noindex">
</head>
<body>
<a href="${location}">
Redirecting from <code>${url.pathname}</code> to <code>${location}</code>
</a>
</body>
</html>`
? getPrerenderRedirectHtml(response, url.pathname)
: "";

let files: { path: string; contents: Uint8Array | string }[] = [
Expand Down
Loading