diff --git a/integration/nonce-hydration-test.ts b/integration/nonce-hydration-test.ts new file mode 100644 index 0000000000..65b5224816 --- /dev/null +++ b/integration/nonce-hydration-test.ts @@ -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( + , + { 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 ( + + + + + + + + ); + } + `, + "app/critical.css": "button { color: rgb(255, 0, 0); }", + "app/routes/other.tsx": js` + export function loader() { return null; } + export default function Other() { return

Other

; } + `, + "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([]); +}); diff --git a/packages/react-router/.changes/patch.links-nonce-hydration-warning.md b/packages/react-router/.changes/patch.links-nonce-hydration-warning.md new file mode 100644 index 0000000000..dfb4084983 --- /dev/null +++ b/packages/react-router/.changes/patch.links-nonce-hydration-warning.md @@ -0,0 +1 @@ +Suppress nonce hydration warnings on critical CSS and HTML link descriptors rendered by ``, and on the developer scripts rendered by the default root error boundary and hydrate fallback, when using ``. diff --git a/packages/react-router/__tests__/dom/ssr/nonce-hydration-test.tsx b/packages/react-router/__tests__/dom/ssr/nonce-hydration-test.tsx new file mode 100644 index 0000000000..2a109e5b31 --- /dev/null +++ b/packages/react-router/__tests__/dom/ssr/nonce-hydration-test.tsx @@ -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: , + selector: "link", + targetCount: 2, + links: () => [{ page: "/other" }], + }, + { + name: "RSC page descriptor data link", + element: , + selector: "link", + rsc: true, + links: () => [{ page: "/other" }], + }, + { + name: "inline critical CSS", + element: , + criticalCss: ".critical { color: red; }", + selector: "style[data-react-router-critical-css]", + }, + { + name: "external critical CSS", + element: , + criticalCss: { href: "/critical.css" }, + selector: 'link[href="/critical.css"]', + }, + { + name: "route stylesheet", + element: , + selector: 'link[href="/route.css"]', + links: () => [{ rel: "stylesheet", href: "/route.css" }], + }, + { + name: "default error boundary developer script", + element: , + selector: "script", + }, + { + name: "default hydrate fallback developer script", + element: , + 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 ( + + + + + + ); + } + + let consoleError = jest + .spyOn(console, "error") + .mockImplementation(() => {}); + let container = document.createElement("div"); + document.body.appendChild(container); + let root: ReturnType | undefined; + + try { + container.innerHTML = renderToString(getTree("server-nonce")); + let targets = Array.from( + container.querySelectorAll(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(); + } + }, +); diff --git a/packages/react-router/lib/dom/ssr/components.tsx b/packages/react-router/lib/dom/ssr/components.tsx index a56bd2638f..4c855bc48a 100644 --- a/packages/react-router/lib/dom/ssr/components.tsx +++ b/packages/react-router/lib/dom/ssr/components.tsx @@ -275,6 +275,7 @@ export function Links({ nonce, crossOrigin }: LinksProps): React.JSX.Element {