Content Security Policy (CSP) Directive Regex for JavaScript
/^(default-src|script-src|style-src|img-src|connect-src|font-src|object-src|media-src|frame-src|child-src|form-action|frame-ancestors|base-uri|report-uri|report-to|upgrade-insecure-requests|block-all-mixed-content|sandbox|worker-src|manifest-src|prefetch-src)(?:\s+(.+))?$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching content security policy (csp) directive, ported and verified for JavaScript. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.
Javascript Implementation
// Content Security Policy (CSP) Directive
// ReDoS-safe | RegexVault — Security > Security Headers
const contentSecurityPolicyCspDirectiveRegex = /^(default-src|script-src|style-src|img-src|connect-src|font-src|object-src|media-src|frame-src|child-src|form-action|frame-ancestors|base-uri|report-uri|report-to|upgrade-insecure-requests|block-all-mixed-content|sandbox|worker-src|manifest-src|prefetch-src)(?:\s+(.+))?$/i;
function validateContentSecurityPolicyCspDirective(input: string): boolean {
return contentSecurityPolicyCspDirectiveRegex.test(input);
}
// Example
console.log(validateContentSecurityPolicyCspDirective("default-src 'self'")); // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
default-src 'self' | evil-src 'self' |
script-src 'self' https://cdn.example.com 'nonce-abc123' | src 'self' |
object-src 'none' | — |
upgrade-insecure-requests | — |
When to use this pattern
This pattern is drawn from the Security > Security Headers category and carries a ReDoS-safe certification. That matters for JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
'unsafe-inline' and 'unsafe-eval' negate much of CSP's protection. Prefer nonce-based CSP where a random nonce is generated per request. The CSP Evaluator tool (from Google) checks CSP policies for weaknesses.
Technical Notes
CSP source keywords: 'self' (same origin), 'none' (block all), 'unsafe-inline' (dangerous), 'unsafe-eval' (dangerous), 'nonce-{base64}' (nonce), 'sha256-{hash}' (hash). A strong CSP eliminates most XSS attack surfaces. object-src 'none' and base-uri 'self' are critical.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern