How-To Guide

How to Configure Content Security Policy

Start from default-src, move scripts to nonces with strict-dynamic, deploy through report-only, and tighten the policy per violation report.

On this page

  1. Introduction
  2. The directive budget
  3. Nonces and strict-dynamic
  4. Deploy through report-only
  5. Close the known gaps
  6. Verify and monitor enforcement
  7. Common pitfalls
  8. Conclusion

Introduction

Content Security Policy answers the question an injected script hopes nobody asked: what is this page actually allowed to load and execute. Without a policy, the answer is everything, any origin, any inline block, any eval, which makes every HTML injection a potential full compromise, because the payload runs with the page’s authority and can exfiltrate anywhere. CSP declares the allowed set in a response header, and the browser enforces it before anything executes: scripts only from listed sources, connections only to allowed origins, frames restricted, object embedding gone. The policy is a list of directives that reads like a budget, default-src as the fallback, specific directives for scripts, styles, images, connections, and the enforcement is absolute and silent unless reporting is configured. The deployment reality is the hard part: an existing application with third-party widgets, inline event handlers, and legacy analytics will violate any honest policy immediately, and the craft is the migration path, report-only mode, nonce-based scripts, and progressive tightening, that gets to a strict policy without breaking the product. This tutorial writes the policy, adopts nonces, runs the report-only phase, and closes the gaps that reports expose.

The directive budget

A policy is written from default-src outward, because any directive you omit inherits its rules from the default. Start conservative and open only what the audit found: default-src 'self' allows same-origin everything, then script-src narrows scripts further, connect-src governs fetch and WebSocket destinations, img-src and style-src cover their media, frame-ancestors replaces the legacy frame-busting and blocks clickjacking, and object-src 'none' plus base-uri 'self' close the plugin and base-tag injection paths.

Content-Security-Policy:
 default-src 'self';
 script-src 'nonce-r4nd0m' 'strict-dynamic';
 style-src 'self';
 img-src 'self' https://cdn.example.net data:;
 connect-src 'self' https://api.example.com;
 font-src 'self';
 frame-ancestors 'none';
 object-src 'none';
 base-uri 'self';
 form-action 'self';
 upgrade-insecure-requests

Three directives carry disproportionate value. script-src is the XSS defense and deserves the nonce treatment in the next section. connect-src is the exfiltration cap: an injected script that cannot execute is stopped, but any script that finds a hole still cannot phone home to an unlisted origin. frame-ancestors is the clickjacking defense and works only in the header, never in a meta tag, which is one of several reasons the header is the deployment vehicle.

Nonces and strict-dynamic

The script problem with host allowlists is that they trust origins, not code: a vulnerable script on an allowed CDN is an injection channel, and the allowlist must enumerate every origin that ever serves a script, including third-party widget loaders that chain further loaders. Nonces flip the model to per-response trust: the server generates a fresh random value per response, whitelists it in the policy, and marks its trusted script tags with the same value; the browser executes only matching tags, so an injected tag without the nonce is dead regardless of where it came from.

import { randomBytes } from 'node:crypto';

export function cspMiddleware(req, res, next) {
 const nonce = randomBytes(16).toString('base64');
 res.locals.nonce = nonce;
 res.setHeader('Content-Security-Policy', [
  "default-src 'self'",
  "script-src 'nonce-" + nonce + "' 'strict-dynamic'",
  "style-src 'self'",
  "object-src 'none'",
  "base-uri 'self'",
  "frame-ancestors 'none'",
 ].join('; '));
 next();
}

The strict-dynamic keyword completes the design: scripts blessed with the nonce may load their own dependencies, loader scripts pulling libraries from arbitrary CDNs, without those origins appearing in the policy, so the allowlist stops growing with the vendor list. The nonce must be unguessable and per-request, never a static value cached into a template, because a predictable nonce is unsafe-inline with extra steps. Templates reference the nonce for every legitimate inline script, and the migration is exactly the work of converting inline handlers and injected scripts to nonced tags.

Deploy through report-only

Enforcing an untested policy on a live application is a self-inflicted outage: pages silently lose scripts, widgets vanish, checkout breaks, and every failure is invisible to the server because the browser simply declines. Report-only mode is the migration vehicle: the Content-Security-Policy-Report-Only header carries the candidate policy, the browser evaluates it, violations do not block anything, and each violation is POSTed to the report-to endpoint with the document URL, the directive violated, and the blocked resource.

Content-Security-Policy-Report-Only:
 default-src 'self'; script-src 'nonce-x' 'strict-dynamic'; report-to csp-endpoint

Reporting-Endpoints: csp-endpoint="/csp-report"

The report endpoint is a real production service with volume expectations, a busy property generates thousands of reports per hour, mostly from extensions and security scanners injecting their own scripts, and it needs sampling, deduplication, and aggregation before the reports are readable. The migration loop is mechanical: deploy report-only, aggregate violations by document and resource, fix each class, nonced tags for first-party scripts, upgraded third-party loaders, https:// sources for the CDN images, and re-deploy until the report stream quiets. Only then does the same policy move to the enforcing header, and report-only stays deployed after enforcement as the early-warning channel for the next regression.

Close the known gaps

A deployed strict policy still has documented holes worth knowing by name. Inline styles: style-src 'self' blocks inline style attributes, and libraries that set them at runtime will need unsafe-inline for styles specifically, a weaker but common compromise, since style injection is a data-leak vector rather than a script-execution vector. Hash-based allowlisting: for the few inline scripts that cannot carry nonces, hash the exact bytes, 'sha256-abc...', which tolerates no whitespace drift and needs pipeline discipline. Framework-specific leaks: templating engines that inject JSON configuration into script tags need the JSON to be escaped against </script> breaks, and hydration payloads need nonce propagation or hash coverage. Extensions and injected clients: browser extensions violate any strict policy on your pages, which is their behavior, not your bug, and the report stream will say so constantly, hence the sampling. And the trust boundary to keep in mind: CSP constrains what runs in the page, it does not sanitize what the page renders, so the first line of defense remains output encoding, and the policy is the second line that makes the first line’s eventual failure cheap.

Verify and monitor enforcement

Policy correctness is observable from both sides. From the browser side: test pages with deliberate violations, an inline script without a nonce, an image from an unlisted origin, and assert they are blocked, in report-only they appear in the report stream, in enforcement the network panel shows the blocked requests with the CSP annotation, which validates that the header reaches real users rather than being stripped by a proxy. From the server side: the report endpoint’s aggregated stream is the monitor, alert on new violation shapes, a novel document with script violations means a feature shipped inline scripts past the policy, and on volume spikes, which usually mean an extension changed behavior rather than an attack. A quarterly policy review closes the loop: sources that no longer appear in reports are candidates for removal, every unsafe- keyword earns a re-audit, and the policy file is versioned and reviewed like the code whose behavior it governs, because a stale allowlist accumulates exactly the trust it exists to withhold.

Common pitfalls

  • **unsafe-inline for scripts. ** The policy executes injected payloads by design; treat it as a blocker, not a compromise to ship.
  • **Static nonces. ** A cached or predictable nonce equals unsafe-inline with extra steps; generate per response.
  • **Enforcing before reporting. ** Untested policies break pages silently, with no server-side error to alert on.
  • **Meta-tag deployment. ** frame-ancestors and report-only work only in headers; the header is the vehicle.
  • **Growing host allowlists. ** Every vendor adds script origins; nonces plus strict-dynamic stop the list’s growth.
  • **Policy as the only defense. ** CSP caps the blast radius of XSS; output encoding still owns preventing the injection itself.

Conclusion

Content Security Policy is the page’s loading budget, declared in the header and enforced by the browser, and it converts most XSS from a full compromise into a blocked request. Write the policy from default-src outward with the audit’s findings, give scripts the nonce plus strict-dynamic treatment so trust attaches to your responses rather than to vendor origins, and cap exfiltration with connect-src and clickjacking with frame-ancestors. Deploy through report-only with a real aggregated report endpoint, migrate violations class by class, and enforce only when the stream quiets, keeping report-only afterward as the regression channel. Verify with deliberate violations, monitor the report stream for new shapes, and review the policy quarterly so the allowlist shrinks with the codebase. The result is an XSS whose payload dies in the browser, which is the difference between an embarrassing bug and an incident report.

Sources: MDN: Content Security Policy, W3C: CSP Level 3, OWASP: CSP cheat sheet.

FAQ

Does CSP stop all XSS?
No. It stops the exploitation path of most XSS, injected scripts running and exfiltrating data, by denying them execution and outbound connections. It does not stop the injection itself: DOM manipulation bugs and same-origin script injection remain, so CSP is a second line behind output encoding.
Why is unsafe-inline so bad?
It permits any inline script or style to execute, which is exactly what an XSS payload is. A policy with unsafe-inline for scripts protects almost nothing, and most guides treat it as a deployment blocker rather than a compromise.
Nonces or hashes for inline scripts?
Nonces fit server-rendered pages with a handful of trusted inline scripts and work with strict-dynamic. Hashes fit static pages where the script bytes never change. Nonces are the usual starting point because they tolerate content changes without policy edits.

Related Examples