Next.js 13: How to pass nonce as prop so that initial scripts receive it? #49648
-
Describe the feature you'd like to requestIn Next.js 12, we simply add a nonce attribute to Please clarify where we pass a nonce as a prop so that Next 13 adds the nonce to the initial scripts. Describe the solution you'd likeClarification on the above matter. Describe alternatives you've consideredI cannot see how it can be done provided the current design pattern. |
Beta Was this translation helpful? Give feedback.
Replies: 12 comments 25 replies
-
@tmb-github Have you figured out how to do it? We are struggling with CSP due to this missing nonce. 😕 |
Beta Was this translation helpful? Give feedback.
-
@mlbiche Yes, I send all of the security headers in next.config.js, in an async headers() function in the nextConfig object. See this article for the syntax. Next, in every page.js file in the app folder, I include |
Beta Was this translation helpful? Give feedback.
-
@tmb-github Thanks for the explanations. But, I don't understand how you provide the per-page generated nonce in the CSP configured in the security headers in |
Beta Was this translation helpful? Give feedback.
-
@mlbiche Sorry about the oversight. Yes, the nonce is generated in the next.config.js and set as an environment variable so it can be retrieved with
The
|
Beta Was this translation helpful? Give feedback.
-
Hi there, " Nonces should be generated differently each time the page loads" https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce After looking in next.js source code, the way to implement this it to pass a CSP header to the Request object from the middleware. // middleware.ts
//...
const nonce = generateContentSecurityPolicyScriptNonce()
const cspNonceCondition = `'nonce-${nonce}'`
// ...
const response = NextResponse.next({
request: {
headers: new Headers({
'content-security-policy': securityPolicy,
// Custom header for use in server component
'x-mss-script-nonce': nonce,
}),
},
})
// ...
response.headers.append('Content-Security-Policy-Report-Only', securityPolicy)
// ...
return response Then the nonce is different for each request and Next injects it automatically to its scripts ! (This seems weird and it is not documented but it works as intended by Next) Then I added 'x-mss-script-nonce' header to get it back in server component (similar to your process.env, but with Hope this helps ! |
Beta Was this translation helpful? Give feedback.
-
Note that this is not compatible with static site generation as the nonce must be injected for each page view. |
Beta Was this translation helpful? Give feedback.
-
@hugues-m Thanks for that...although I'm having trouble understanding how to revise my existing next.config.js file to incorporate that design pattern. It currently follows the syntax here: https://nextjs.org/docs/api-reference/next.config.js/headers How would I revise that to incorporate the middleware, or would I use it outside next.config.js, and if so, where? (Also, I'm not using TypeScript, so if the code could exclude that, it'd be helpful for me to read.) |
Beta Was this translation helpful? Give feedback.
-
@hugues-m is correct that you need to set the Here's my middleware function (full source): export async function middleware(request: NextRequest) {
// generate CSP and nonce
const { csp, nonce } = generateCsp();
// Clone the request headers
const requestHeaders = new Headers(request.headers);
// set nonce request header to read in pages if needed
requestHeaders.set('x-nonce', nonce);
// set CSP header
// switching for report-only or regular for repro on
// https://github.com/vercel/next.js/issues/48966
const headerKey =
request.nextUrl.pathname === '/csp-report-only'
? 'content-security-policy-report-only'
: 'content-security-policy';
// Set the CSP header so that `app-render` can read it and generate tags with the nonce
requestHeaders.set(headerKey, csp);
// create new response
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
// Also set the CSP so that it is outputted to the browser
response.headers.set(headerKey, csp);
return response;
} You can see this working here: https://nextjs-csp-report-only.vercel.app/csp Repo: https://github.com/Sprokets/nextjs-csp-report-only Note - you'll need to be on at least Next.js 13.4.0 for this to work (see comment) |
Beta Was this translation helpful? Give feedback.
-
I'm struggling to find any info about how to implement a nonce for scripts with the App router in Next 13. Previously, I used a custom document
I can't find any documentation about the use of a nonce in Next (possibly since release of 13.4; I must have had something to go on prior to that, since I had this working with the A strict CSP is a prerequisite of my application. I'm surprised there aren't more people in the same position. Any advice or pointers would be hugely appreciated. 🙇♂️ |
Beta Was this translation helpful? Give feedback.
-
I have a question, how can I put nonce to _app? Today I use MUI in the dashboard and I need to implement nonce for cache providers. The one option is to change the pages folder to app dir and use get headers in server components |
Beta Was this translation helpful? Give feedback.
-
I'm incrementally migrating to Next.js and for now we're using the static export. Can I use middleware to put a placeholder nonce for our python webserver to fill in when serving the html? |
Beta Was this translation helpful? Give feedback.
-
Hey folks, wanted to swing back here with an update. After digging through many different issues and discussions, I've made a new page in the documentation (PR) specifically for Content Security Policy and nonces. This docs page:
Further, we've patched some bugs and made improvements to Really hope this helps out, thank you all 🙏 I'll be closing this discussion out. To continue the discussion, please go here. |
Beta Was this translation helpful? Give feedback.
Hey folks, wanted to swing back here with an update. After digging through many different issues and discussions, I've made a new page in the documentation (PR) specifically for Content Security Policy and nonces. This docs page:
nonce
with Middlewarenonce
in a route withheaders()
unsafe
nonce
Middleware from running on prefetches / static assetsFurther, we've patched some bugs and made improvements to
nonce
handling in Next.js that will be available in the latestcanary
version (for those of you time traveling from the future, upgrade to Next.js 13.5). We also …