fix: nonce #5522
main fromrefs/pull/5522/head·merged by schiller-manuel(GitHub profile, opens in a new tab) fixes #5511
Summary by CodeRabbit#
- New Features
- Improved Content Security Policy (CSP) support: nonces are now applied consistently to head tags, scripts, and styles.
- Automatic emission of a CSP nonce meta tag when a nonce is present.
- SSR hydration now reads and applies the CSP nonce so server-rendered pages and client hydration share the same nonce.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router
🤖 Nx Cloud AI Fix Eligible#
To disable these notifications, a workspace admin can disable them [in workspace settings.](https://cloud.nx.app/orgs/6412ca9d1c251d000efa21ba/workspaces/6442f7de8226a6291646a813/settings#selfHealingCISettings?utm_source=pull-request&utm_medium=comment)An automatically generated fix could have helped fix failing tasks for this run, but Self-healing CI is disabled for this workspace. Visit workspace settings to enable it and get automatic fixes in future runs.
View your CI Pipeline Execution ↗ for commit ae3976a6baf2d653355fe52d6cbc6a786c0277f5
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...❌ Failed 6m 17s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1m 3s View ↗
☁️ Nx Cloud last updated this comment at
2025-10-17 23:17:07UTCMore templates
- tanstack-router-solid-example-basic
- tanstack-router-solid-example-basic-devtools-panel
- tanstack-router-solid-example-basic-file-based
- tanstack-router-solid-example-basic-non-nested-devtools
- tanstack-router-solid-example-basic-solid-query
- tanstack-router-solid-example-basic-solid-query-file-based
- tanstack-router-solid-example-basic-ssr-streaming-file-based
- tanstack-router-solid-example-kitchen-sink-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-solid-start-example-bare
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-static
- tanstack-router-react-example-authenticated-routes
- tanstack-router-react-example-authenticated-routes-firebase
- tanstack-router-react-example-basic
- tanstack-router-react-example-basic-default-search-params
- tanstack-router-react-example-basic-devtools-panel
- tanstack-router-react-example-basic-file-based
- tanstack-router-react-example-basic-non-nested-devtools
- tanstack-router-react-example-react-query
- tanstack-router-react-example-basic-react-query-file-based
- tanstack-router-react-example-basic-ssr-file-based
- tanstack-router-react-example-basic-ssr-streaming-file-based
- tanstack-router-react-example-basic-virtual-file-based
- tanstack-router-react-example-basic-virtual-inside-file-based
- tanstack-router-react-example-deferred-data
- tanstack-router-i18n-paraglide
- tanstack-router-react-example-kitchen-sink
- tanstack-router-react-example-kitchen-sink-file-based
- tanstack-router-react-example-kitchen-sink-react-query
- tanstack-router-react-example-kitchen-sink-react-query-file-based
- tanstack-router-react-example-large-file-based
- tanstack-router-react-example-location-masking
- tanstack-router-react-example-navigation-blocking
- tanstack-router-react-example-quickstart
- tanstack-router-react-example-quickstart-esbuild-file-based
- tanstack-router-react-example-quickstart-file-based
- tanstack-router-react-example-quickstart-rspack-file-based
- tanstack-router-react-example-quickstart-webpack-file-based
- router-monorepo-react-query
- router-mono-simple
- router-mono-simple-lazy
- tanstack-router-react-example-scroll-restoration
- tanstack-search-validator-adapters
- tanstack-start-example-bare
- tanstack-start-example-basic
- tanstack-start-example-basic-auth
- tanstack-start-example-basic-cloudflare
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-static
- tanstack-start-bun-hosting
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-i18n-paraglide
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-streaming-data-from-server-functions
- tanstack-start-example-supabase-basic
- tanstack-start-tailwind-v4
- tanstack-start-example-trellaux
- tanstack-start-example-workos
- tanstack-router-react-example-view-transitions
- tanstack-router-react-example-with-framer-motion
- tanstack-router-react-example-with-trpc
- tanstack-router-react-example-with-trpc-react-query
@tanstack/arktype-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5522@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5522@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5522@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5522@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5522@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5522@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5522@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5522@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5522@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5522@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5522@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5522@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5522@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5522@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5522@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5522@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5522@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5522@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5522@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5522@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5522@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5522@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5522@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5522@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5522@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5522@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5522@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5522@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5522@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5522@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5522@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5522@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5522@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5522commit:
7adb203Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/react-router/src/HeadContent.tsx (1)
16-70: Missingnoncein useMemo dependency array.The
useMemousesnonce(line 47) androuter.options.ssr?.nonce(lines 58-63) but only includes[routeMeta]in its dependency array (line 70). If the nonce value changes between renders, the memoized meta tags will contain a stale nonce.Apply this diff to fix the dependency array:
return resultMeta - }, [routeMeta]) + }, [routeMeta, nonce, router.options.ssr?.nonce])Alternatively, since
nonceis derived fromrouter.options.ssr?.nonce, you could use just one:return resultMeta - }, [routeMeta]) + }, [routeMeta, nonce])🧹 Nitpick comments (2)
packages/solid-router/src/Scripts.tsx (1)
8-8: LGTM: Nonce extraction looks good.The nonce is correctly extracted from router options using optional chaining. When the nonce is undefined, Solid.js will skip rendering the attribute, which is the expected behavior.
For slightly cleaner code, you could conditionally spread the nonce only when defined:
- attrs: { ...asset.attrs, nonce }, + attrs: { ...asset.attrs, ...(nonce && { nonce }) },And similarly at line 47:
attrs: { ...script, - nonce, + ...(nonce && { nonce }), },However, the current implementation is simpler and Solid handles undefined attributes correctly, so this is purely optional.
packages/react-router/src/HeadContent.tsx (1)
188-195: Consider reusing nonce from useTags hook.The
nonceis read twice: once inuseTags(line 9) and again inHeadContent(line 191). While not incorrect, this is redundant. Consider threading the nonce through fromuseTagsor deriving tags with nonce already embedded.However, since
Assetneeds the nonce prop for link and style tags (lines 27, 33 in Asset.tsx), and the current approach is clear and explicit, this is a minor optimization opportunity rather than a defect.📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 4f9b7371746028fe207a3e2e5f31564eccb26b8a and 7adb20352515b9b86a75199375212b74b59d8da4.
📒 Files selected for processing (6)
packages/react-router/src/Asset.tsx(2 hunks)packages/react-router/src/HeadContent.tsx(6 hunks)packages/react-router/src/Scripts.tsx(4 hunks)packages/router-core/src/ssr/ssr-client.ts(1 hunks)packages/solid-router/src/HeadContent.tsx(7 hunks)packages/solid-router/src/Scripts.tsx(3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/solid-router/src/Scripts.tsxpackages/react-router/src/HeadContent.tsxpackages/react-router/src/Asset.tsxpackages/react-router/src/Scripts.tsxpackages/solid-router/src/HeadContent.tsxpackages/router-core/src/ssr/ssr-client.ts
packages/{react-router,solid-router}/**
📄 CodeRabbit inference engine (AGENTS.md)
Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/
Files:
packages/solid-router/src/Scripts.tsxpackages/react-router/src/HeadContent.tsxpackages/react-router/src/Asset.tsxpackages/react-router/src/Scripts.tsxpackages/solid-router/src/HeadContent.tsx
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/src/ssr/ssr-client.ts
🧬 Code graph analysis (1)
packages/react-router/src/Scripts.tsx (1)
packages/react-router/src/Asset.tsx (1)
Asset(11-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (5)
packages/solid-router/src/HeadContent.tsx (3)
10-10: LGTM! Nonce correctly extracted and applied to meta tags.The nonce is properly extracted from router options and threaded into meta tag attributes.
Also applies to: 49-49
144-144: LGTM! Nonce correctly applied to styles and scripts.The nonce is properly added to both style and script tags, which are the critical elements for Content Security Policy enforcement. This directly addresses the issue where inline scripts lacked nonce attributes.
Also applies to: 161-161
60-68: No issues found — this is an intentional framework pattern.Verification confirms the custom meta tag with
property: 'csp-nonce'is intentional. The client-side code inpackages/router-core/src/ssr/ssr-client.tsexplicitly queries this meta tag (document.querySelector('meta[property="csp-nonce"]')) and extracts the nonce value during hydration. This pattern is consistent across both solid-router and react-router and serves as the framework's mechanism for passing the nonce from server to client during SSR.packages/solid-router/src/Scripts.tsx (1)
43-50: LGTM: Inline script nonce propagation is correct.The nonce is correctly added to inline scripts, ensuring CSP compliance for all dynamically generated script tags. The spread order ensures the nonce from router options takes precedence, which is the correct behavior.
packages/react-router/src/Asset.tsx (1)
37-37: LGTM: Script nonce handling simplified.The nonce is correctly threaded through
attrsrather than as a separate prop, aligning with the Script component's implementation that reads fromattrs.nonce(line 98).@@ -23,6 +23,7 @@2323 .forEach((asset) => {2424 assetScripts.push({2525 tag: 'script',26- attrs: asset.attrs,26+ attrs: { ...asset.attrs, nonce },2727 children: asset.children,28+ nonce,2829 } as any)🛠️ Refactor suggestion | 🟠 Major
Redundant nonce assignment in asset construction.
The nonce is assigned twice:
- Line 26:
attrs: { ...asset.attrs, nonce } - Line 28:
nonce,
Since the
Scriptcomponent (in Asset.tsx) reads nonce fromattrs.nonce(line 98), and the asset object is spread into<Asset {...asset} />(line 63), including nonce as both a direct property and within attrs is redundant. Theas anytype assertion on line 29 suggests this structure doesn't align with the expected types.Apply this diff to remove the redundant direct nonce property:
.forEach((asset) => { assetScripts.push({ tag: 'script', attrs: { ...asset.attrs, nonce }, children: asset.children, - nonce, - } as any) + }) }),📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
assetScripts.push({ tag: 'script', attrs: { ...asset.attrs, nonce }, children: asset.children, })🤖 Prompt for AI Agents
In packages/react-router/src/Scripts.tsx around lines 24 to 29, the asset object redundantly sets nonce both inside attrs and as a top-level property; remove the top-level nonce field (leave attrs: { ...asset.attrs, nonce }) and return the object with the correct shape expected by <Asset />, dropping the redundant nonce and the unnecessary "as any" cast or replace it with the proper type so the asset aligns with the Asset component's props.✅ Addressed in commit ae3976a
packages/router-core/src/ssr/ssr-client.ts lines 89 to 95@@ -86,3 +86,10 @@8686 router.ssr = {8787 manifest,8888 }89+ const meta = document.querySelector('meta[property="csp-nonce"]') as90+ | HTMLMetaElement91+ | undefined92+ const nonce = meta?.content93+ router.options.ssr = {94+ nonce,95+ }⚠️ Potential issue | 🟠 Major
Potential data loss: entire
router.options.ssrobject is overwritten.Assigning
router.options.ssr = { nonce }discards any pre-existing properties onrouter.options.ssr. If other parts of the hydration flow or user configuration set additional properties on this object, they will be lost.Apply this diff to preserve existing properties:
const meta = document.querySelector('meta[property="csp-nonce"]') as | HTMLMetaElement | undefined const nonce = meta?.content - router.options.ssr = { - nonce, - } + router.options.ssr = { + ...router.options.ssr, + nonce, + }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const meta = document.querySelector('meta[property="csp-nonce"]') as | HTMLMetaElement | undefined const nonce = meta?.content router.options.ssr = { ...router.options.ssr, nonce, }🤖 Prompt for AI Agents
In packages/router-core/src/ssr/ssr-client.ts around lines 89 to 95, the code unconditionally assigns router.options.ssr = { nonce } which overwrites any existing properties; instead merge the nonce into the existing object (preserving existing properties) by shallow-merging into router.options.ssr (or initializing it if undefined) so the final object contains prior keys plus the nonce.packages/solid-router/src/HeadContent.tsx line 84@@ -71,3 +81,4 @@7181 tag: 'link',7282 attrs: {7383 ...link,84+ nonce,⚠️ Potential issue | 🟠 Major
Nonce applied to constructed links, but missing on preload and asset links.
While constructed links receive the nonce attribute (line 84), both:
- Preload links (modulepreload) at lines 119-125
- Manifest assets (link tags) at lines 97-102
do not receive the nonce. This inconsistency may cause CSP violations if those links contain resources that require nonce validation.
Apply this diff to add nonce to preload links:
router.ssr?.manifest?.routes[route.id]?.preloads ?.filter(Boolean) .forEach((preload) => { preloadMeta.push({ tag: 'link', attrs: { rel: 'modulepreload', href: preload, + nonce, }, }) }),And this diff to add nonce to manifest assets:
.map( (asset) => ({ tag: 'link', - attrs: asset.attrs, + attrs: { + ...asset.attrs, + nonce, + }, }) satisfies RouterManagedTag, )@@ -172,3 +185,5 @@172185 */173186 export function HeadContent() {174187 const tags = useTags()188+ const router = useRouter()189+ const nonce = router.options.ssr?.nonce⚠️ Potential issue | 🟡 Minor
Remove unused variables.
The
routerandnoncevariables are declared but never used in theHeadContentcomponent. The nonce is already properly threaded through tags generated byuseTags().Apply this diff to remove the unused variables:
export function HeadContent() { const tags = useTags() - const router = useRouter() - const nonce = router.options.ssr?.nonce - return ( <MetaProvider> {tags().map((tag) => (📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export function HeadContent() { const tags = useTags() return ( <MetaProvider> {tags().map((tag) => (🤖 Prompt for AI Agents
In packages/solid-router/src/HeadContent.tsx around lines 188-189, remove the unused declarations by deleting the lines that set const router = useRouter() and const nonce = router.options.ssr?.nonce; if that makes useRouter unused, also remove its import to satisfy the linter; keep existing behavior since nonce is already threaded via useTags().✅ Addressed in commit ae3976a
packages/solid-router/src/Scripts.tsx lines 23 to 29@@ -23,7 +23,7 @@2323 .forEach((asset) => {2424 assetScripts.push({2525 tag: 'script',26- attrs: asset.attrs,26+ attrs: { ...asset.attrs, nonce },2727 children: asset.children,2828 } as any)2929 }),🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
Verify the type assertion and ensure type safety.
The
as anycast at line 28 suggests a type mismatch between the constructed object andRouterManagedTag. This bypasses TypeScript's type checking and could hide issues.Please verify:
- Does the
RouterManagedTagtype properly account for thenonceattribute in script tags? - Can the type assertion be removed by updating the type definition?
Run the following script to check the
RouterManagedTagtype definition:
🏁 Script executed:
#!/bin/bash # Description: Find the RouterManagedTag type definition to verify if nonce is properly typed # Search for RouterManagedTag type definition ast-grep --pattern 'type RouterManagedTag = $$$' # Also search for interface definition ast-grep --pattern 'interface RouterManagedTag { $$$ }' # Search for nonce in type definitions rg -n --type=ts 'RouterManagedTag' -A 10 -B 2Length of output: 30501
Replace
as anywith type-safe pattern for consistency.The
RouterManagedTagtype properly supports thenonceattribute through its genericattrs?: Record<string, any>. Theas anyassertion is unnecessary and bypasses type checking. The codebase already uses thesatisfies RouterManagedTagpattern elsewhere (e.g.,HeadContent.tsxlines 86, 102). For consistency and type safety per the coding guidelines, replace theas anywith:} satisfies RouterManagedTag)Alternatively, remove the assertion entirely, since other scripts in react-router follow this approach without needing individual assertions.
🤖 Prompt for AI Agents
In packages/solid-router/src/Scripts.tsx around lines 23 to 29, the object pushed into assetScripts is asserted with "as any", which bypasses type checking; replace that assertion with a type-safe pattern by using "satisfies RouterManagedTag" on the object literal (or remove the assertion entirely like other script entries) so the nonce attribute is correctly type-checked and the codebase remains consistent.
Sign in to join this conversation.
Caution
Review failed#
The pull request is closed.
Walkthrough#
Removes explicit nonce prop from React Asset script handling and adds per-request CSP nonce extraction and propagation: HeadContent and Scripts in both React and Solid routers now derive nonce from router.options.ssr, attach it to generated head/link/style/script attrs, and ssr-client reads nonce from a meta[csp-nonce] during hydration.
Changes#
packages/react-router/src/Asset.tsxnoncefor Script; script elements no longer receive nonce via Script prop.packages/react-router/src/HeadContent.tsxnoncefromrouter.options.ssr, includesnonceon generated tag attrs (meta/link/style/script), and conditionally emits ameta[property="csp-nonce"]. Passes nonce into Asset rendering flow.packages/react-router/src/Scripts.tsxnoncefromrouter.options.ssrand merges it into asset/script attrs during script construction; Asset invocation no longer uses an explicit nonce prop.packages/router-core/src/ssr/ssr-client.tsmeta[property="csp-nonce"]and assigns its content torouter.options.ssr.nonce.packages/solid-router/src/HeadContent.tsxnoncefromrouter.options.ssr, spreadsnonceinto generated meta/link/style/script attrs, and conditionally emitsmeta[property="csp-nonce"].packages/solid-router/src/Scripts.tsxnoncefromrouter.options.ssrand includes it in both asset script attrs and inline script attrs during rendering.Sequence Diagram(s)#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs#
Suggested reviewers#
Poem#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning, 1 inconclusive)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (3 passed)
📜 Recent review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 7adb20352515b9b86a75199375212b74b59d8da4 and ae3976a6baf2d653355fe52d6cbc6a786c0277f5.
📒 Files selected for processing (3)
packages/react-router/src/HeadContent.tsx(8 hunks)packages/react-router/src/Scripts.tsx(4 hunks)packages/solid-router/src/HeadContent.tsx(9 hunks)Comment `@coderabbitai help` to get the list of available commands and usage tips.