Basic Content Security Policy Header

Learn the fundamentals of Content Security Policy headers, how they protect your site from XSS and data injection, and how to write your first CSP header from scratch.

CSP Basics

Detailed Explanation

What Is a Content Security Policy Header?

A Content Security Policy (CSP) is an HTTP response header that tells browsers which resources are allowed to load on a page. By defining a whitelist of trusted sources, CSP drastically reduces the risk of Cross-Site Scripting (XSS) and other code-injection attacks.

The Basic Structure

A CSP header is a single string composed of directives separated by semicolons. Each directive controls a specific resource type:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'

Key Concepts

  • 'self' — allows resources from the same origin (scheme + host + port)
  • 'none' — blocks all resources of that type
  • 'unsafe-inline' — permits inline <script> and <style> tags (weakens CSP)
  • 'unsafe-eval' — permits eval() and similar dynamic code execution
  • Host sources — explicit origins like https://cdn.example.com
  • Scheme sources — protocols like https: or data:

A Minimal Starter Policy

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

This single directive restricts all resource types (scripts, styles, images, fonts, frames, etc.) to the same origin. It is the most restrictive starting point and is easy to loosen selectively by adding more specific directives.

How Browsers Enforce CSP

  1. The server sends the Content-Security-Policy header with the HTTP response
  2. The browser parses the directives and builds an allowlist
  3. Any resource request that does not match the allowlist is blocked and logged to the browser console
  4. If a report-uri or report-to directive is present, violations are also sent to a reporting endpoint

Testing Before Enforcing

Use Content-Security-Policy-Report-Only instead of Content-Security-Policy to monitor violations without blocking resources. This lets you audit your policy before rolling it out.

Use Case

Every web application benefits from a basic CSP header. When launching a new site or hardening an existing one, start with a restrictive default-src 'self' policy and iteratively relax it as needed. This approach catches accidental third-party script injections and prevents stored XSS from executing even if malicious content reaches the page.

Try It — CSP Header Generator

Open full tool