CSP Header Builder With Nonce
Build Content-Security-Policy headers with nonces for inline scripts and strict directives to prevent XSS and data exfiltration.
Code
export function buildCSP({nonce,allowedOrigins=[],imgSrc=["'self'"]}={}){const scriptSrc=nonce?["'strict-dynamic'",'nonce-'+nonce]:["'self'"];const d={'default-src':["'self'"],'script-src':scriptSrc,'style-src':["'self'","'unsafe-inline'"],'img-src':imgSrc,'connect-src':["'self'",...allowedOrigins],'font-src':["'self'",'data:'],'object-src':["'none'"],'base-uri':["'none'"],'frame-ancestors':["'none'"]};return Object.entries(d).map(([k,v])=>k+' '+v.join(' ')).join('; ');}export function generateNonce(){return crypto.randomBytes(16).toString('base64');}Inside the snippet
The working surface is the functions buildCSP and generateNonce — everything else is wiring.
What to watch for
cryptoexist only in browsers — a Node runtime has no shims for them out of the box.
Putting the pieces to work
The primary signature is export function buildCSP({nonce,allowedOrigins=[],imgSrc=["'self'"]}={})
Import buildCSP from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `buildCSP`, `generateNonce` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.