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
| Parameter | Type | Required | Description |
|---|---|---|---|
response | Response | Yes | The Response object to set the Content-Security-Policy header on. |
directives | CSPDirectives | Yes | CSP 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).
| Property | Header Directive | Description |
|---|---|---|
defaultSrc | default-src | Fallback for other fetch directives. |
scriptSrc | script-src | Valid sources for JavaScript. |
styleSrc | style-src | Valid sources for stylesheets. |
imgSrc | img-src | Valid sources for images. |
connectSrc | connect-src | Valid sources for fetch, XHR, WebSocket. |
fontSrc | font-src | Valid sources for fonts. |
objectSrc | object-src | Valid sources for <object>, <embed>. |
mediaSrc | media-src | Valid sources for <audio>, <video>. |
frameSrc | frame-src | Valid sources for <frame>, <iframe>. |
childSrc | child-src | Valid sources for web workers and nested contexts. |
workerSrc | worker-src | Valid sources for Worker, SharedWorker. |
frameAncestors | frame-ancestors | Valid parents for embedding via <iframe>. |
formAction | form-action | Valid targets for form submissions. |
baseUri | base-uri | Valid values for <base> element. |
manifestSrc | manifest-src | Valid 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'"],
})
