How Next.js App Router CSP with Nonces Forces Every Route into Dynamic Rendering
Implementing a Content Security Policy in Next.js App Router requires a per-request nonce combined with the 'strict-dynamic' directive, as static domain allowlists cannot cover the framework's runtime chunk loading behavior. The nonce must be generated in middleware.ts and passed through both request and response headers so Next.js can apply it to its own bootstrap script tags. A key trade-off is that calling headers() to read the nonce opts every matched route out of static rendering, adding a performance cost developers should plan for. Four directives — object-src, base-uri, form-action, and frame-ancestors — can be safely added via next.config.js without nonces and remain fully cacheable. The 'strict-dynamic' keyword grants inherited trust to scripts loaded by an already-trusted script, eliminating the need for build-time hash enumeration or chunk URL lists.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in