Content Security Policy in the Next.js App Router: Field Notes on Nonces, strict-dynamic, and the Middleware That Made Every Page Dynamic
A Content Security Policy (CSP) is an HTTP response header that tells the browser which script, style, and connection sources a document is allowed to use, and in the Next.js App Router the only script policy that survives the framework's runtime chunk loading is a per-request nonce combined with 'strict-dynamic' . The cost I did not budget for: generating that nonce in middleware.ts…
The article discusses the use of Content Security Policy (CSP) in Next.js applications, specifically focusing on the App Router. It highlights that the only script policy that survives runtime chunk loading in Next.js is a per-request nonce combined with strict-dynamic. CSP serves as an HTTP response header that dictates which sources a document can use for scripts, styles, and connections.
The article emphasizes that a CSP nonce is a per-request random token appearing both in the script-src directive and as a nonce attribute on every allowed script. It explains that because a nonce cannot repeat, HTML carrying a nonce cannot be cached, leading to Next.js dropping the route to dynamic rendering. The article also mentions that a host allowlist cannot secure a Next.js app, as the App Router emits an inline bootstrap payload and creates further script elements at runtime.
The use of strict-dynamic is crucial for propagating trust from a nonce-allowed script to any script element that the script creates programmatically, enabling chunk loading without enumerating chunk URLs.
Brief written by urgent.news from Dev.to's own syndicated text. Machine-written — it may contain errors, so check the original before relying on it.