2 min read
A Content Security Policy for a mostly static Next.js site
Nonces are the textbook answer for inline scripts, and they don't fit pre-rendered pages. What this site's policy allows, what it still blocks, and the bug it surfaced on the way.
This site just got a Content Security Policy. The interesting part was not writing it, but deciding what to give up.
The nonce problem
The strongest CSP for scripts uses a nonce: a random value per response, allowed in the header and set on every legitimate <script>. Injected scripts don't know the nonce, so they don't run.
The catch: a nonce must be new for every response. Most pages here are pre-rendered at build time and served as they are. A nonce baked into a static file is the same for every visitor, so it protects nothing. Making it real means rendering every page on every request, which gives up the fast static pages.
For a personal site with no user-generated HTML, I chose the static pages and allowed inline scripts. Next.js needs them for hydration, and the site has a small theme script and JSON-LD.
What the policy still does
default-src 'self';script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com;style-src 'self' 'unsafe-inline';img-src 'self' data: blob: https:;font-src 'self';connect-src 'self';frame-src https://challenges.cloudflare.com;object-src 'none';base-uri 'self';form-action 'self';frame-ancestors 'none'
Even with 'unsafe-inline', this blocks a lot: scripts from any host except this one and Cloudflare Turnstile, plugins, <base> hijacking, forms posting to foreign hosts, and framing the site. connect-src 'self' means even a successful injection can't send data anywhere else with fetch.
In development, React needs eval for its debugging features, so 'unsafe-eval' is added only when NODE_ENV is development.
What testing found
Checking every page for violations turned up two things:
- A harmless one. Zod 4 probes whether it can use
new Function()for faster validation, catches the error and falls back. The browser still logs the blockedeval. Nothing breaks. - A real one, unrelated to the CSP. The contact form passed
size: 'invisible'to Turnstile, which isn't a valid value. Invisible mode is a setting of the site key, not a render option. The widget threw, no token was ever issued, and the form couldn't be sent. The CSP check just happened to be the first time anyone read the console on that page.
Run through every page type with the console open: static pages, forms, admin, uploads. Watch for blocked requests and for anything else that shows up.
Takeaways
- Nonces need per-request rendering. On static pages, decide consciously what you trade.
'unsafe-inline'weakens script protection, but a strictconnect-src,form-actionandframe-ancestorsstill do a lot.- Reading the console while testing finds more than CSP violations.