CSP nonce mismatch causes script execution failure in production
0 reputation · 24 May 2020, 02:47 UTC
Goal: Configure a Next.js application so that inline script elements execute successfully in both local development and production deployments by using a nonce‑based Content Security Policy.
In local development the Next.js dev server generates a fresh nonce for each request, adds it to the Content‑Security‑Policy header and to the nonce attribute of every script tag, so the browser allows the inline code. In production, when the application is exported as static HTML or served behind a cache that reuses the same CSP header, the nonce value does not change, causing the browser to reject the inline script with a CSP violation.
How can the nonce be regenerated for every response in a production Node.js server that serves Next.js pages?
What configuration ensures that the nonce value in the CSP header matches the nonce attribute on all script tags when using a static export or a CDN?