Content Security Policy (CSP) Directives Explained: A Practical Guide

Learn how Content Security Policy (CSP) works, what default-src, script-src, and frame-ancestors do, how to use nonces and hashes, and how to build a safe policy.

· 4 min read

Cross-Site Scripting (XSS) remains one of the most common web application vulnerabilities. Even with modern frontend frameworks that automatically escape HTML, injected script tags, compromised dependencies, and third-party widgets can still execute malicious JavaScript in your users' browsers.

A Content Security Policy (CSP) is an HTTP response header that tells browsers exactly which sources of scripts, styles, images, and connections are trusted. If an attacker manages to inject a <script> tag or iframe pointing to an unauthorized server, the browser refuses to load or execute it.

This guide breaks down how CSP directives work, how to handle inline scripts with nonces and hashes, and how to safely deploy a policy without breaking production.

How a CSP works

When a browser loads a webpage, it parses the Content-Security-Policy header. Every time the page requests a resource—such as a stylesheet, JavaScript file, API request, or image—the browser checks the request against the policy's rules.

Here is a minimal example:

Content-Security-Policy: default-src 'self'; script-src 'self' https://trustedscripts.com; img-src 'self' data: https:;

A policy consists of directives separated by semicolons. Each directive has a name (like script-src) followed by one or more allowed sources separated by spaces.

If an inline script or external resource does not match an allowed source, the browser blocks it and logs an error in the developer console:

Refused to load the script 'https://evil-cdn.com/tracker.js' because it violates the following Content Security Policy directive: "script-src 'self' https://trustedscripts.com".

Core fetch directives

Fetch directives govern where different types of network resources can be retrieved from:

DirectiveControlsTypical sources
default-srcFallback for any fetch directive not explicitly specified'self', 'none'
script-srcJavaScript execution, <script> tags, and event handlers'self', CDNs, nonces
style-srcCSS stylesheets, <link rel="stylesheet">, and <style> blocks'self', 'unsafe-inline', fonts providers
img-srcImage assets (<img>, CSS backgrounds, favicons)'self', data:, https:
connect-srcEndpoints for fetch(), XMLHttpRequest, WebSockets, and EventSource'self', API domains
font-srcWeb fonts (@font-face)'self', https://fonts.gstatic.com
media-srcAudio and video elements (<audio>, <video>)'self', streaming CDNs
object-srcFlash, Java applets, and <object>, <embed>, or <applet> tags'none' (recommended)

Best practice: Always set object-src 'none' to block legacy plugins that can bypass origin boundaries.

Special source keywords

Source keywords must be enclosed in single quotes. Without quotes, the browser treats them as domain names:

  • 'self': Allows resources from the exact same protocol, host, and port as the document.
  • 'none': Denies all resources for that directive.
  • 'unsafe-inline': Allows inline elements like <script> blocks, inline style="..." attributes, and onclick event handlers. This significantly weakens XSS protection and should be avoided when possible.
  • 'unsafe-eval': Allows JavaScript dynamic code execution functions like eval(), new Function(), and setTimeout("string", ...).
  • 'wasm-unsafe-eval': Allows compilation and execution of WebAssembly without enabling arbitrary JavaScript eval().
  • 'strict-dynamic': Tells modern browsers to trust scripts loaded dynamically by already-trusted root scripts, simplifying policies for complex SPAs.

Some directives protect how your site interacts with the surrounding browser environment rather than what it downloads:

  • frame-ancestors: Specifies which parents may embed the page using <frame>, <iframe>, <object>, or <embed>. Setting frame-ancestors 'none' or frame-ancestors 'self' prevents Clickjacking attacks, completely superseding the older X-Frame-Options header.
  • form-action: Restricts the URLs to which HTML forms (<form action="...">) can submit data.
  • base-uri: Restricts the URLs that can be used in a <base> element, preventing attackers from redirecting relative script and asset links.

Handling inline scripts: Nonces vs Hashes

Modern web development often requires small inline scripts, such as theme initializers or analytics bootstrap snippets. Instead of allowing all inline scripts with 'unsafe-inline', you should use cryptographic nonces or hashes.

1. Using a Nonce (Number Used Once)

A nonce is a cryptographically random, base64-encoded string generated by your server on every single HTTP request.

  1. The server generates a random token: rAnd0m12345
  2. The server sends the header:
    Content-Security-Policy: script-src 'self' 'nonce-rAnd0m12345';
  3. The HTML page attaches the exact same nonce attribute to the script tag:
    <script nonce="rAnd0m12345">
      console.log("This script executes safely!");
    </script>

Because an attacker injecting HTML cannot guess the per-request nonce, injected <script> tags without the correct nonce are blocked.

2. Using a Hash

If your site is statically generated or hosted on a CDN where per-request server nonces are impossible, use a hash.

  1. Compute the SHA-256 hash of the exact contents between <script> and </script> (including whitespace).
  2. Add the hash to your policy:
    Content-Security-Policy: script-src 'self' 'sha256-qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng=';
  3. The browser hashes the script body before executing it. If the hash matches, it runs; otherwise, it is rejected.

Deploying safely with Report-Only

Deploying a strict CSP directly to production can easily break third-party analytics, payment widgets, or font loaders.

To test safely, use the Content-Security-Policy-Report-Only header instead:

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://trusted.cdn.com; report-to /csp-violations;

In report-only mode:

  1. The browser does not block any resources.
  2. Every policy violation triggers a JSON report sent via HTTP POST to the endpoint specified in report-to (or report-uri).
  3. You can review your logs for a week, catch missing third-party endpoints, refine the policy, and switch to the standard enforcement header with confidence.

Build your policy

Writing CSP headers manually is error-prone—missing a single single-quote can invalidate the directive. You can build, configure, and customize a complete policy using ToolDock's Content Security Policy Generator, and test your live website's configuration with the Security Headers Checker.