csp

Set Content-Security-Policy headers on a Response. Supports automatic nonce generation — any directive value of 'nonce' is replaced with a cryptographically random 'nonce-{value}' token.

Import

import { csp } from 'catmint/server'

Signature

function csp(response: Response, directives: CSPDirectives): string | undefined

Parameters

ParameterTypeRequiredDescription
responseResponseYesThe Response object to set the Content-Security-Policy header on.
directivesCSPDirectivesYesCSP directive configuration using camelCase keys.

CSPDirectives

All properties are optional string[] arrays. Directive names are camelCase and converted to kebab-case in the header (e.g. scriptSrc becomes script-src).

PropertyHeader DirectiveDescription
defaultSrcdefault-srcFallback for other fetch directives.
scriptSrcscript-srcValid sources for JavaScript.
styleSrcstyle-srcValid sources for stylesheets.
imgSrcimg-srcValid sources for images.
connectSrcconnect-srcValid sources for fetch, XHR, WebSocket.
fontSrcfont-srcValid sources for fonts.
objectSrcobject-srcValid sources for <object>, <embed>.
mediaSrcmedia-srcValid sources for <audio>, <video>.
frameSrcframe-srcValid sources for <frame>, <iframe>.
childSrcchild-srcValid sources for web workers and nested contexts.
workerSrcworker-srcValid sources for Worker, SharedWorker.
frameAncestorsframe-ancestorsValid parents for embedding via <iframe>.
formActionform-actionValid targets for form submissions.
baseUribase-uriValid values for <base> element.
manifestSrcmanifest-srcValid sources for app manifests.

Additional custom directives can be added using string index keys.

Nonce Replacement

If any directive value is the string 'nonce', it is automatically replaced with 'nonce-{randomValue}' using a cryptographically random 16-byte base64 nonce. The nonce is generated once and reused across all directives.

Return Value

Returns the generated nonce string if any directive used 'nonce', or undefined if no nonce was needed.

Examples

import { csp } from 'catmint/server'

const response = new Response('<html>...</html>', {
  headers: { 'Content-Type': 'text/html' },
})

const nonce = csp(response, {
  defaultSrc: ["'self'"],
  scriptSrc: ["'self'", "'nonce'"],
  styleSrc: ["'self'", "'unsafe-inline'"],
  imgSrc: ["'self'", 'data:', 'https:'],
})

// Use the nonce in your HTML
// <script nonce={nonce}>...</script>
// Strict CSP without nonces
csp(response, {
  defaultSrc: ["'none'"],
  scriptSrc: ["'self'"],
  styleSrc: ["'self'"],
  connectSrc: ["'self'"],
  imgSrc: ["'self'"],
})

See Also