Skip to content
Security & PrivacyCSP

Content Security Policy

Definition

A Content Security Policy (CSP) is an HTTP response header or HTML meta tag that restricts the origins and resources (scripts, images, stylesheets, fonts, iframes) the browser is permitted to load and execute.

Why It Matters

CSP is the primary web application defense against Cross-Site Scripting (XSS), data exfiltration, clickjacking, and unauthorized third-party code injection. By whitelisting trusted sources and enforcing cryptographic nonces or hashes for inline scripts, CSP prevents attackers from running arbitrary malicious code in your users' browsers.

Content-Security-Policy Security Best Practices

Criterion / StateRequirement / TargetStatus
default-src'self' (disallow arbitrary fallback origins)Optimal
script-srcUse cryptographic nonces (strict-dynamic) instead of 'unsafe-inline'Optimal
object-src'none' (disallows Flash and vulnerable plugins)Optimal
base-uri'self' (prevents malicious <base> tag injection)Optimal

Practical Implementation Example

Using strict-dynamic with nonces allows modern browsers to trust dynamically loaded scripts while completely blocking classical reflected and stored XSS vectors.

src/middleware.ts
// Generate a per-request cryptographic nonce in Next.js middleware
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const cspHeader = `
  default-src 'self';
  script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
  style-src 'self' 'unsafe-inline';
  img-src 'self' blob: data: https:;
  font-src 'self';
  object-src 'none';
  base-uri 'self';
  form-action 'self';
  frame-ancestors 'none';
`;
response.headers.set('Content-Security-Policy', cspHeader.replace(/\s{2,}/g, ' ').trim());
Automated Verification

How to Audit CSP in ScanWise

ScanWise evaluates your security headers, scoring CSP policy strictness, flagging dangerous keywords ('unsafe-inline', 'unsafe-eval'), and recommending production-ready directives.

Audit your Content Security Policy and headers in ScanWise

Common CSP Mistakes & How to Fix Them

Common CSP Mistakes & How to Fix Them
MistakeWhy It HurtsThe Fix
Enabling 'unsafe-inline' and 'unsafe-eval' in script-src without nonces.'unsafe-inline' completely nullifies CSP protection against injected script tags, defeating the entire purpose of the header.Migrate to cryptographic nonces or sha256 script hashes, and refactor code to avoid eval().
Deploying a strict blocking CSP immediately to production without testing.Overly restrictive policies break legitimate analytics, payment gateways, and third-party widgets.Deploy using the Content-Security-Policy-Report-Only header first, monitor violation reports, then enforce.