CSP Header Builder With Nonce

Build Content-Security-Policy headers with nonces for inline scripts and strict directives to prevent XSS and data exfiltration.

JavascriptSecurity Boundaries

Code

javascriptsnippet
1 line
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

  • crypto exist 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

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.