Next.js & App Router (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)
Content Security Policy (CSP) and Cryptographic Nonces in Next.js.
senior LevelSecurity & AuthSystem DesignData Structures
In Simple Words: Preventing Cross-Site Scripting (XSS) in Next.js with strict CSP:
- In
middleware.ts, generate a cryptographically random Base64 nonce per request (crypto.randomUUID()). - Attach nonce to
Content-Security-Policyheader:script-src 'self' 'nonce-${nonce}'. - Pass the nonce down to Next.js
<Script>and<Html>components so legitimate scripts execute while attacker-injected inline scripts are blocked by the browser.