SQLite Testing: CSP nonce

https://wackowiki.org/test     Version: 3 (05/21/2026 16:15)

CSP nonce

When to Use a CSP Nonce (and When Not To)


A Content Security Policy (Nonce) is a security mechanism used to allow specific, trusted inline <script> or <style> elements to execute on a webpage, even when a strict CSP is in place that otherwise blocks all inline code (e.g., by omitting 'unsafe-inline').

1. When You Need a CSP Nonce


You need a CSP nonce in the following scenarios:

Example (Next.js):
JAVASCRIPT
// A nonce is generated for every request
export function proxy(request) {
  const nonce = crypto.randomUUID(); // Generate unique nonce
  const cspHeader = `script-src 'nonce-${nonce}' 'strict-dynamic'`;
  // ... set header and inject nonce into script tags
}

2. When You Do NOT Need a CSP Nonce


You should avoid using a nonce and opt for other methods when possible:


Best Practices Summary


Approach Use Case Pros Cons
Nonce Dynamic, server-rendered inline code Easy to implement with SSR, works with strict-dynamic Must be unique per request, prevents HTML caching, requires server-side logic
Hash Static inline code Highly secure, allows static caching, header can be static Hash must be recalculated if code changes, not suitable for dynamic content
No Inline (Best) All code in external files Maximum security, simple CSP, optimal caching Requires refactoring legacy code

In short: Use a nonce when you have dynamic, server-rendered inline code and cannot avoid it. Do not use a nonce (and prefer hashes or external files) for static content or when you can refactor to eliminate inline code entirely. Always prioritize moving code to external files.