Content-Security-Policy nonces in Next.js
1 min read
By Juliano Alves
A strict CSP blocks inline scripts unless you allowlist hashes or nonces. Nonces (single-use random tokens per response) let first-party inline scripts execute while blocking injected XSS payloads.
Flow
- Middleware or
headers()generatesnonce = base64url(16 bytes). - Attach
Content-Security-Policyheader includingscript-src 'nonce-${nonce}'(often with'strict-dynamic'andhttps:origins for third-party SDKs). - Pass the nonce to
<Script nonce={nonce}>or your framework’s equivalent for any required inline bootstrapping.
Third-party scripts
Payment and analytics vendors may still use inline snippets—negotiate nonce-aware integrations or host their loader from your domain with a known hash.
Report-Only first
Roll out with Content-Security-Policy-Report-Only and collect violations before enforcing—broken CSP blocks revenue paths silently.
Summary
Nonces restore safe inline script capability for frameworks while keeping XSS harder. Pair with strict-dynamic cautiously and test checkout flows exhaustively.