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
88 changes: 88 additions & 0 deletions integration/nonce-hydration-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { expect } from "@playwright/test";

import { test, viteConfig } from "./helpers/vite.js";

const js = String.raw;

test("hydrates Links with a server-only nonce", async ({ page, dev }) => {
let { port } = await dev(async ({ port }) => ({
"vite.config.ts": await viteConfig.basic({ port }),
"app/entry.server.tsx": js`
import { renderToReadableStream } from "react-dom/server";
import { ServerRouter } from "react-router";

export default async function handleRequest(request, status, headers, context) {
let body = await renderToReadableStream(
<ServerRouter context={context} url={request.url} nonce="server-nonce" />,
{ nonce: "server-nonce" }
);
headers.set("Content-Type", "text/html");
headers.set("Content-Security-Policy", "style-src 'self' 'nonce-server-nonce'");
return new Response(body, { status, headers });
}
`,
"app/root.tsx": js`
import { useEffect, useState } from "react";
import { Links, Scripts } from "react-router";
import "./critical.css";

export const links = () => [
{ rel: "stylesheet", href: "/route.css" },
{ page: "/other" },
];

export default function Root() {
let [count, setCount] = useState(0);
let [hydrated, setHydrated] = useState(false);
useEffect(() => setHydrated(true), []);
return (
<html>
<head><Links /></head>
<body>
<button disabled={!hydrated} onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<Scripts />
</body>
</html>
);
}
`,
"app/critical.css": "button { color: rgb(255, 0, 0); }",
"app/routes/other.tsx": js`
export function loader() { return null; }
export default function Other() { return <p>Other</p>; }
`,
"public/route.css": "button { padding: 20px; }",
}));

let hydrationWarnings: string[] = [];
page.on("console", (message) => {
if (/hydrat|didn't match|did not match/i.test(message.text())) {
hydrationWarnings.push(message.text());
}
});

let response = await page.goto(`http://localhost:${port}/`);
let html = await response!.text();
expect(html).toContain('nonce="server-nonce"');
expect(html).toContain("data-react-router-critical-css");
expect(html).toContain('href="/other.data"');

let button = page.getByRole("button", { name: "Count: 0" });
await expect(button).toBeEnabled();
await button.click();
await expect(page.getByRole("button", { name: "Count: 1" })).toBeVisible();
expect(
await page
.locator('link[href="/route.css"]')
.evaluate((link: HTMLLinkElement) => link.nonce),
).toBe("server-nonce");
expect(
await page
.locator('link[rel="prefetch"][href="/other.data"]')
.evaluate((link: HTMLLinkElement) => link.nonce),
).toBe("server-nonce");
expect(hydrationWarnings).toEqual([]);
expect(page.errors).toEqual([]);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Suppress nonce hydration warnings on critical CSS and HTML link descriptors rendered by `<Links>`, and on the developer scripts rendered by the default root error boundary and hydrate fallback, when using `<ServerRouter nonce>`.
150 changes: 150 additions & 0 deletions packages/react-router/__tests__/dom/ssr/nonce-hydration-test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import * as React from "react";
import { act } from "@testing-library/react";
import { hydrateRoot } from "react-dom/client";
import { renderToString } from "react-dom/server.node";

import { createMemoryRouter, Links, RouterProvider } from "../../../index";
import { RSCRouterContext } from "../../../lib/context";
import { FrameworkContext } from "../../../lib/dom/ssr/components";
import { RemixRootDefaultErrorBoundary } from "../../../lib/dom/ssr/errorBoundaries";
import { RemixRootDefaultHydrateFallback } from "../../../lib/dom/ssr/fallback";
import {
ENABLE_DEV_WARNINGS,
ErrorResponseImpl,
} from "../../../lib/router/utils";
import { mockFrameworkContext } from "../../utils/framework";

let routeError = new ErrorResponseImpl(404, "Not Found", null);

it.each([
{
name: "page descriptor data and module links",
element: <Links />,
selector: "link",
targetCount: 2,
links: () => [{ page: "/other" }],
},
{
name: "RSC page descriptor data link",
element: <Links />,
selector: "link",
rsc: true,
links: () => [{ page: "/other" }],
},
{
name: "inline critical CSS",
element: <Links />,
criticalCss: ".critical { color: red; }",
selector: "style[data-react-router-critical-css]",
},
{
name: "external critical CSS",
element: <Links />,
criticalCss: { href: "/critical.css" },
selector: 'link[href="/critical.css"]',
},
{
name: "route stylesheet",
element: <Links />,
selector: 'link[href="/route.css"]',
links: () => [{ rel: "stylesheet", href: "/route.css" }],
},
{
name: "default error boundary developer script",
element: <RemixRootDefaultErrorBoundary error={routeError} />,
selector: "script",
},
{
name: "default hydrate fallback developer script",
element: <RemixRootDefaultHydrateFallback />,
selector: "script",
},
])(
"preserves the server nonce without hydration warnings for $name",
async ({
element,
criticalCss,
selector,
links,
rsc = false,
targetCount = 1,
}) => {
// The default error/fallback scripts must actually render in these tests.
expect(ENABLE_DEV_WARNINGS).toBe(true);
let context = mockFrameworkContext({
criticalCss,
routeModules: {
root: {
default: () => null,
Layout: ({ children }) => <>{children}</>,
links,
},
other: { default: () => null },
},
});
context.manifest.routes.other = {
...context.manifest.routes.root,
id: "other",
parentId: "root",
path: "other",
module: "other.js",
hasLoader: true,
};
let router = createMemoryRouter([
{
id: "root",
path: "/",
element,
children: [{ id: "other", path: "other" }],
},
]);
function getTree(nonce?: string) {
return (
<RSCRouterContext.Provider value={rsc}>
<FrameworkContext.Provider value={{ ...context, nonce }}>
<RouterProvider router={router} />
</FrameworkContext.Provider>
</RSCRouterContext.Provider>
);
}

let consoleError = jest
.spyOn(console, "error")
.mockImplementation(() => {});
let container = document.createElement("div");
document.body.appendChild(container);
let root: ReturnType<typeof hydrateRoot> | undefined;

try {
container.innerHTML = renderToString(getTree("server-nonce"));
let targets = Array.from(
container.querySelectorAll<HTMLElement>(selector),
);
expect(targets).toHaveLength(targetCount);
expect(targets.map((target) => target.nonce)).toEqual(
Array(targetCount).fill("server-nonce"),
);
await act(async () => {
root = hydrateRoot(container, getTree());
});

// The error boundary logs the supplied error on each render.
expect(
consoleError.mock.calls.filter(([error]) => error !== routeError),
).toEqual([]);
let hydratedTargets = Array.from(container.querySelectorAll(selector));
expect(hydratedTargets).toHaveLength(targetCount);
expect(
hydratedTargets.every((target, index) => target === targets[index]),
).toBe(true);
expect(targets.map((target) => target.nonce)).toEqual(
Array(targetCount).fill("server-nonce"),
);
} finally {
await act(async () => root?.unmount());
container.remove();
router.dispose();
consoleError.mockRestore();
}
},
);
3 changes: 3 additions & 0 deletions packages/react-router/lib/dom/ssr/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ export function Links({ nonce, crossOrigin }: LinksProps): React.JSX.Element {
<style
{...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" }}
nonce={nonce}
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: criticalCss }}
/>
) : null}
Expand All @@ -284,6 +285,7 @@ export function Links({ nonce, crossOrigin }: LinksProps): React.JSX.Element {
rel="stylesheet"
href={criticalCss.href}
nonce={nonce}
suppressHydrationWarning
crossOrigin={crossOrigin}
/>
) : null}
Expand All @@ -299,6 +301,7 @@ export function Links({ nonce, crossOrigin }: LinksProps): React.JSX.Element {
<link
key={key}
nonce={nonce}
suppressHydrationWarning
{...link}
crossOrigin={link.crossOrigin ?? crossOrigin}
/>
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/lib/dom/ssr/errorBoundaries.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export function RemixRootDefaultErrorBoundary({
let heyDeveloper = (
<script
nonce={nonce}
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: `
console.log(
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/lib/dom/ssr/fallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export function RemixRootDefaultHydrateFallback() {
{ENABLE_DEV_WARNINGS ? (
<script
nonce={nonce}
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: `
console.log(
Expand Down