Inline scripts are duplicated after hydration when the CSP nonce is sent in a header
Which project does this relate to?
Router
Describe the bug
After hydration, Script looks for an existing inline script with the same text, type and nonce before it creates a new one:
When the CSP arrives in a response header, browsers apply nonce hiding. On a connected element, getAttribute('nonce') returns '', and only the .nonce property keeps the value. So the comparison is '' vs. the real nonce, and the server-rendered script never matches. Script then creates a new <script type="module" nonce>import("/assets/index-….js")</script>, sets its textContent, and appends it to <head>.
Complete minimal reproducer
https://github.com/gabriel-le/tanstack-nonce-inline-scripts-duplication
Steps to Reproduce the Bug
This works in any Start app:
- Set
ssr.nonceon the router and sendContent-Security-Policy: script-src 'nonce-<n>'as a response header. - Load a page.
document.head.querySelectorAll('script[type=module]')includes a re-addedimport("/assets/…")script. ItsgetAttribute('nonce')is'', and its.noncehas the value. - Control: send the same policy in a
<meta http-equiv>, or send no policy. Nonces aren't hidden, the lookup matches, and nothing is added. - Add
; require-trusted-types-for 'script'to the header. Hydration fails with the error above.
I tested this using react-router, but the issue is likely the same in solid and vue
Expected behavior
The lookup matches the server-rendered script, and nothing is created or appended.
Proposed fix
- const sNonce = el.getAttribute('nonce') ?? undefined
+ const sNonce = el.nonce || undefinedThe fix uses || rather than ?? because .nonce is '' when an element has no nonce. With ??, apps that don't use a nonce would start creating duplicates.
Screenshots or Videos
No response
Platform
- Router / Start Version: 1.170.40
- OS: macOS
- Browser: Tested in chrome, safari and firefox
- Browser Version: Safari Version 27.2 (22625.2.5.11.1)
- Bundler: vite
- Bundler Version: 8.0.0
Additional context
No response
Source: TanStack/router