Esc

    ↑ ↓ to moveEnter to openEsc to close

    Guide

    How to Write a CSP

    How to build a Content-Security-Policy from what your site actually loads, without breaking it.

    A strict policy written from memory is an easy way to break a site's forms in one go. It's safer to build it from what your site actually loads.

    What a CSP Actually Does

    A CSP is an HTTP response header with a list of rules, called directives. Each directive covers one kind of resource and lists where it may come from.

    Text
    Content-Security-Policy: script-src 'self' https://plausible.io; object-src 'none'
    

    With that header, the browser only runs scripts from your own domain and from plausible.io. If an attacker manages to inject <script src="https://evil.example/x.js"> into a comment or a form field, the browser refuses to load it and logs an error instead.

    That's the main job: limiting the damage from cross-site scripting. The hole that let the script in still needs fixing, and the CSP stops most of what that script could do in the meantime.

    The Directives That Matter

    There are a lot of directives. These are the ones you'll use on almost every site.

    DirectiveControlsTypical value
    default-srcThe fallback for any type you don't list'self'
    script-srcJavaScript'self' plus your script hosts
    style-srcCSS'self' plus font or widget hosts
    img-srcImages'self' data: plus image CDNs
    connect-srcfetch and WebSocket connections'self' plus your APIs and analytics
    font-srcWeb fonts'self' plus font hosts
    frame-srcIframes you embedYouTube, Stripe, and so on
    frame-ancestorsWho may embed your page'none' or 'self'
    object-src<object> and <embed>'none', always
    base-uriThe <base> tag'self'
    form-actionWhere forms may submit'self' plus form services

    Keywords like 'self' (your own origin) and 'none' go in single quotes, and hostnames go in as they are. data: allows inline data URIs, which a lot of sites use for small images.

    Step 1: List What Your Site Loads

    Open your site with the browser's developer tools on the Network tab and click around the pages that matter, writing down every outside host that shows up. Check the pages people forget: checkout, the contact form, the logged-in area, and anything with an embed.

    For most sites the list looks something like an analytics host, a font host, a payment provider, and maybe a newsletter or chat widget. Note which type each one is, because a font host goes in font-src and its stylesheet in style-src.

    If you'd rather start from a list of common services than from scratch, the CSP Generator has the hosts for analytics, payments, embeds, fonts, and newsletter tools built in. Tick what your site uses and it writes the policy for you, ready for nginx, Apache, Caddy, or a few other servers.

    Step 2: Start in Report-Only Mode

    This is the step that keeps you from breaking production. Instead of Content-Security-Policy, send the same policy as Content-Security-Policy-Report-Only:

    Nginx
    add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' https://plausible.io; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self' https://plausible.io; object-src 'none'; base-uri 'self'; frame-ancestors 'self'" always;
    

    The browser enforces nothing in this mode. It loads everything as usual and logs a warning in the console for each thing your policy would have blocked. So you can deploy it and browse your own site with the console open, seeing what's missing without any visitor noticing.

    Leave it in report-only for a few days. If you want reports from real visitors' browsers too, add a report-uri directive pointing at an endpoint that collects them. The newer report-to directive does the same job but names an endpoint you define in a separate Reporting-Endpoints header, and since older browsers only understand report-uri, it's simplest to send both. A service like report-uri.com handles that if you don't want to build one.

    Step 3: Fix Inline Scripts

    The warnings you'll see most are about inline scripts: <script> tags with code inside them, and attributes like onclick="...". A policy without 'unsafe-inline' blocks all of them, and adding 'unsafe-inline' would undo most of the protection.

    You have a few ways around it.

    Move the code into a file. For most inline scripts this is the cleanest fix. Put it in a .js file you serve yourself, and 'self' covers it.

    Use a hash. For a small script that has to stay inline, like one that sets the theme before the page paints, you can allow that exact script by its SHA-256 hash:

    Text
    script-src 'self' 'sha256-cgqvfUkQoUREgzTpHZjLszgwBKkT1KSdz8q0c9RBal4='
    

    That's the real hash from this site, for a short script that remembers whether you chose the light or dark theme. The browser hashes each inline script and only runs one whose hash is in the list. The catch is that changing a single character in the script changes the hash, so the two have to be updated together.

    Use a nonce. If your server renders pages per request, it can generate a fresh random value for each response and put it in the header as 'nonce-r4nd0m'. Each script tag it trusts then gets nonce="r4nd0m". An injected script won't know the nonce, so it doesn't run. Nonces don't work with pages cached as static HTML, since every visitor would get the same value.

    Inline event handlers like onclick can't be given a nonce, and hashing them only works with the extra 'unsafe-hashes' keyword, so it's better to turn them into addEventListener calls in a script file.

    Step 4: Enforce It

    Once a few days of browsing go by without warnings you didn't expect, switch the header name from Content-Security-Policy-Report-Only to Content-Security-Policy, and nothing else has to change.

    I'd keep watching the console for the first week, and remember that every new third-party script from now on needs its host added. On this site, the policy lives next to the code that serves pages, so adding a script and allowing it happen in the same commit.

    You Don't Have to Cover Everything at Once

    A full policy with every directive is the goal, but it's fine to start smaller. The CSP on this site only sets script-src, object-src, base-uri, and form-action. Scripts are where most of the risk is, and those four directives cover it without having to track every image and font host.

    A policy that only controls scripts and ships this week is better than a perfect one that sits in a branch for months.

    A Policy to Start From

    For a typical small site with Google Fonts and privacy-friendly analytics, this is a reasonable first enforced policy:

    Text
    default-src 'self';
    script-src 'self' https://plausible.io;
    style-src 'self' https://fonts.googleapis.com;
    font-src 'self' https://fonts.gstatic.com;
    img-src 'self' data:;
    connect-src 'self' https://plausible.io;
    frame-ancestors 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self'
    

    In the actual header it all goes on one line, with each directive separated by a semicolon.

    Check It

    Once it's live, run your site through the Redirect and Header Checker to confirm the header is actually being sent, since a common reason a policy quietly does nothing is nginx dropping it. An add_header inside a location block replaces every header set above it, and without always the header is left off error pages. A CDN stripping headers is the other usual suspect. A CSP also pairs naturally with the rest of the security headers, like HSTS and X-Content-Type-Options, and the CSP Generator writes those for you too.