What is Content Security Policy (CSP)? Header Examples & Guide

Content Security Policy glowing shield and network diagram
Share this article:

A Content Security Policy (CSP) is an added layer of security that helps detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. Think of it as a strict allowlist for your web application's resources.

Why Do You Need a Content Security Policy?

The foundational security model of the web relies heavily on the Same-Origin Policy (SOP). However, modern websites are incredibly complex. Your site likely pulls in analytics scripts, web fonts, external stylesheets, and third-party widgets from all over the internet.

Browsers are designed to execute code they receive. If a malicious actor manages to inject a script into your site, the browser inherently cannot distinguish between a script you wrote and a script injected by the hacker. This is the root cause of Cross-Site Scripting (XSS).

The Threat

Without a CSP, an attacker can steal user cookies, redirect visitors to malicious sites, or completely deface your application.

A CSP solves this problem directly by letting you explicitly declare exactly which domains are authorized to load resources. If a script tries to execute from a source not explicitly approved in your policy, the browser automatically blocks it, stopping the attack in its tracks.

How Does CSP Work?

You implement a CSP by configuring your web server to return the Content-Security-Policy HTTP header alongside your web pages. This header contains multiple "directives" that control different classifications of resources.

Let's look at a very basic but effective policy example that restricts everything strictly to your own domain:

Content-Security-Policy: default-src 'self';

Before building a complex policy, it is often helpful to see what your site is currently emitting. Use our Security Headers Grader to quickly analyze your current headers and find room for improvement.

Core CSP Directives Explained

According to the official W3C CSP Level 3 Specification, here are the primary directives you will use:

  • default-srcThe ultimate fallback directive. If you don't specify a rule for a specific resource type (like fonts or images), the browser uses the policy defined here.
  • script-srcControls where JavaScript can be loaded and executed from. This is arguably the most critical directive for preventing XSS.
  • style-srcControls where CSS stylesheets can be loaded from. Note that malicious CSS can also be used for data exfiltration.
  • connect-srcRestricts the URLs that your application can fetch data from using AJAX, the Fetch API, or WebSockets.

For a complete list of every available directive and keyword, bookmark our Ultimate CSP Cheat Sheet.

Handling Inline Scripts Securely

By default, a strict and secure CSP completely blocks inline scripts (<script>...</script> directly in your HTML) and inline styles. This is intentional. Inline code is the primary vector for Cross-Site Scripting.

Developers often make the mistake of adding 'unsafe-inline' to their policy to fix broken sites, but doing so completely negates the XSS protections of CSP. To see examples of how this fails, check out our guide on Insecure CSP Configurations.

If you absolutely must execute inline scripts, the modern web provides two highly secure alternatives:

1. Cryptographic Nonces

Generate a random, cryptographically secure string (a "nonce") for every page load. Add this nonce to your script tag and to your CSP header. If they match, the browser runs the script.

Try our Nonce Generator →

2. Content Hashes

Calculate the SHA-256 hash of the exact, verbatim script content (including whitespace) and include that hash inside your CSP header. The browser will hash the script it sees and compare it.

Calculate script hashes →

How to Deploy a CSP Without Breaking Your Website

Deploying a strict CSP overnight is dangerous. You will almost certainly block legitimate required resources, breaking your production website for users.

Instead, you must leverage the Content-Security-Policy-Report-Only HTTP header. This special header tells the browser to aggressively monitor for policy violations, but not to block anything. When a violation happens, the browser sends a JSON report to an endpoint URI that you define in the report-uri or report-to directive. CSP Radar collects the report-uri format (a csp-report body). It does not ingest report-to reports.

Here is the recommended workflow for a safe deployment:

  1. Draft an initial policy using our visual CSP Generator.
  2. Deploy the policy in Report-Only mode to your production site.
  3. Monitor the incoming reports to see what legitimate scripts are failing.
  4. Iteratively refine your policy based on those reports until no false positives remain.
  5. Finally, switch the header from Report-Only to enforced mode.

Before deploying, we strongly recommend evaluating your site with our active CSP Scanner to proactively identify external dependencies.

Further Authoritative Reading

Mastering application security takes continuous learning. We highly recommend reviewing these foundational resources from the architects of the web:

Need to audit an existing policy?

Our intelligent analysis engine can break down your current Content Security Policy, identify critical misconfigurations, and highlight dangerous security gaps instantly.