Skip to main content
Juliano Alves
Back to blog

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#

  1. Middleware or headers() generates nonce = base64url(16 bytes).
  2. Attach Content-Security-Policy header including script-src 'nonce-${nonce}' (often with 'strict-dynamic' and https: origins for third-party SDKs).
  3. 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.

© 2026 Juliano Alves. All rights reserved.