How to Set Up a Content-Security-Policy (CSP): Start with Report-Only
By the IDEAVALU team · Updated
A CSP tells the browser where the page is allowed to load scripts, images and other resources from. Even if an XSS bug lets someone inject a script, scripts from sources you did not allow will not run.
Start with Report-Only
Adding Content-Security-Policy straight away can break pages when you forget to allow a third-party service (analytics, payments, maps). Content-Security-Policy-Report-Only blocks nothing and instead prints violations to the browser console. Switch to the enforcing header once the violations are gone.
Keep 'unsafe-inline' out of script-src
With 'unsafe-inline' in script-src, every script written directly into the HTML can run, which removes most of the protection against XSS. If you need inline scripts, use a per-request nonce or script hashes instead.
For the Next.js App Router, the "Content Security Policy" page of the official docs shows how to issue a nonce in middleware and pass it in the header.
Check it yourself
Check the header with curl and look for violations in the browser console.
Is a CSP set?
curl -sI https://example.com | grep -i content-security-policy
How to fix
CSP (allowed script sources)
Use Content-Security-Policy to limit where scripts can load from. Enforcing it right away can break pages, so start with Report-Only.
Start with a policy that only reports violations
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https:; frame-ancestors 'self'
Check violations in the browser console, add the domains of services you use (Google Analytics, Supabase and so on), then switch to Content-Security-Policy.
For inline scripts in Next.js, the official docs (Content Security Policy) show how to issue a nonce in middleware. Putting 'unsafe-inline' in script-src removes most of the protection.
FAQ
- Can I use a CSP with Google Analytics or Stripe?
- Yes. Add the domains each service documents for CSP to script-src, connect-src and frame-src. Adding them while watching Report-Only violations keeps you from missing one.