Replies: 3 comments 2 replies
-
You're right — this is a common problem when trying to use a strict Content-Security-Policy (CSP) in Next.js 13+ and 15 with the App Router. Next.js uses inline scripts during hydration (like __next_f.push([...])), and these get blocked unless you allow 'unsafe-inline' in script-src. However, 'unsafe-inline' does open your site to potential XSS attacks — so removing it is the right move. 🔐 Recommended solution: Use a CSP nonce All <script> tags (automatically handled by Next.js) Your Content-Security-Policy header ✅ Example CSP header: Use App Router Use useCSPNonce feature (in edge middleware or config) ⚙️ Example in middleware: import { NextResponse } from 'next/server'; export function middleware(request: NextRequest) { const response = NextResponse.next(); // Optionally set nonce for use in React return response; Instead, use a nonce and include it in your CSP Next.js hydration scripts will work as long as they include the correct nonce Let me know if you want a working repo or example setup. Happy to share! |
Beta Was this translation helpful? Give feedback.
-
Thanks for your suggestion. But during research i had gone through this solution of adding nonce dynamically. The part where i got stuck was "inject it into all script tags". How will I inject nonce in every internal script tag in my App router that does not consist any _document.ts file |
Beta Was this translation helpful? Give feedback.
-
below are my findings from ChatGpt can i not create or use any functionality such that all the dynamic scripts appended during hydration will automatically consits nonce from header X-nonce ChatGPT said:You’re asking the right question — and it’s one of the toughest to solve securely in a Next.js App Router setup today.
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Problem: In Next js 15 'Content-Security-Policy security header while defining script-src vlaue if I don't keep 'unsafe-inline' in the value then hydration does not work as expected because during hydration many inline scripts are automatically added in the html DOM and not keeping 'unsafe-inline' will block those scripts.
I am required to remove the 'unsafe-inline' value from script-src because it makes website vunerable for Cross-site scripting (XSS) attacks.
Resolution I want : Remove the 'unsafe-inline' from script-src in 'Content-Security-Policy security header.
Below is the example of hydrated html in my page.
Additional information
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions