{"canonical_url":"https://engineer.company/glossary/csp/","content_markdown":"# Content Security Policy\n\n## What it is\n\nContent Security Policy is a set of rules a website hands to the browser about\nwhat its pages may run, fetch and submit, which the browser then enforces on the\nsite's behalf. It is almost always shortened to CSP. The site sends the rules in\na `Content-Security-Policy` response header, or writes them into the page in a\n`meta` element, and from that moment any script, stylesheet, image, font, frame\nor connection the rules do not allow is refused before it loads.\n\nA policy is a short string of directives separated by semicolons. Each directive\nnames one kind of resource or behaviour and the sources it accepts. Shown one\ndirective per line for reading, though on the wire it is a single header value,\na strict policy looks like this:\n\n```text\ndefault-src 'self';\nscript-src 'nonce-q8Zt3VwR1mKx7NpL2cYfJA==' 'strict-dynamic';\nobject-src 'none';\nbase-uri 'none';\nform-action 'self';\nframe-ancestors 'none'\n```\n\nThe vocabulary is small. `'self'` means the page's own origin. A host such as\n`https://static.example.com` or a scheme such as `https:` widens that. `'none'`\nallows nothing. A nonce is a random value the server generates for one response\nand writes both into the policy and onto each script element it vouches for. A\nhash is the digest of an inline script's exact text, so that one script and no\nother may run. Two keywords, `'unsafe-inline'` and `'unsafe-eval'`, switch\nprotections back off, and their names are a fair warning.\n\n`default-src` is the fallback for the fetch directives a policy leaves out, such\nas `script-src`, `style-src`, `img-src` and `connect-src`. It is a fallback for\nthose alone. Directives that govern behaviour rather than fetching, among them\n`base-uri`, `form-action` and `frame-ancestors`, stay unrestricted unless they\nare written out.\n\nA policy can also run in a watching mode. Sent as\n`Content-Security-Policy-Report-Only`, it blocks nothing and instead reports\neach violation to an endpoint named with `report-to`, which uses the browser's\nReporting API. The older `report-uri` directive is deprecated in its favour. The\ncurrent text of the standard is Content Security Policy Level 3, a W3C Working\nDraft from the Web Application Security Working Group.\n\n## Why it matters\n\nThe attack CSP was built against is cross-site scripting. Somebody gets text of\ntheir choosing into a page, through a comment field, a search term echoed back\ninto the HTML or a compromised dependency, and the browser runs it as script\nwith all the authority the site's own code has: it can read the page, act as the\nlogged-in user and send what it finds anywhere. The first defence is escaping\noutput correctly, and that has to be right in every template, on every line,\nevery time. CSP is the second defence. When an escaping mistake does slip\nthrough, the injected script still has to get past the policy, and a policy that\nonly runs scripts carrying this response's nonce turns it away.\n\nIt also limits what a script that does run can reach. `connect-src` decides\nwhich hosts script may talk to, which narrows where a skimmer can post what it\ncollects. `frame-ancestors` decides which sites may show the page inside a\nframe, the standard defence against clickjacking, where a page is overlaid on\nanother so that a click lands somewhere the user never meant. `form-action`\ndecides where forms may submit, and `base-uri` stops an injected `base` element\nfrom quietly redirecting every relative address on the page.\n\nIt is worth being exact about who CSP protects. It runs in the browser, so it\nguards the person reading the page from content an attacker planted there. It\ndoes nothing for the server against that same person, who can edit or strip the\nheader in their own browser in seconds. A policy is a reason to trust less of\nthe page, never a reason to trust more of the request.\n\nThe cost is mostly inventory. A policy forces a team to know every origin its\npages load from, every inline script and every event handler written as an\nattribute. A new site can be built to a strict policy from its first commit for\nvery little. An older site with inline handlers, a tag manager and several\nwidgets pays for the clean-up first, and that clean-up is usually the real\nproject.\n\n## What it looks like in practice\n\nThis site holds itself to one. The [security page](/security/) lists a strict\nContent Security Policy, declared in the page itself, with `form-action 'none'`,\nbecause the site posts no forms anywhere. Every HTML page states\n`script-src 'none'`: no executable JavaScript or service worker runs. The site\nmakes no third-party requests; everything a page needs comes from its own host,\nso there is very little to allow.\n\nAn application with logged-in users needs more than a short allowlist. On a\nplatform holding professional and organisational data,\n[the Next.js proxy middleware sets a Content-Security-Policy with a per-request nonce and `strict-dynamic`](/portfolio/hardened-the-application-with-nonce-based-csp/),\nalongside HSTS and SameSite cookies. A fresh nonce on every response means that\nonly the script elements the server stamped on that response will run. With\n`strict-dynamic` in the policy, a script the nonce trusts may load further\nscripts itself, so the policy does not have to name every host a bundle fetches\nits chunks from. That platform works from the assumption that the client is\nhostile. Each request's entitlements are therefore checked again by the server,\nand the gates in the frontend count for user experience only. CSP is one layer\nof several there, protecting users from injected code, and authorisation is\ndecided elsewhere.\n\n## Where it goes wrong\n\n**The policy goes live and half the site stops working.** A strict policy sent\nstraight to enforcement blocks the inline script nobody remembered and the\ntracking tag someone added two years ago. Ship it as\n`Content-Security-Policy-Report-Only` first, read the reports until they settle,\nallow or remove each source they name, and only then enforce. The report-only\nheader has to be a real header: the specification does not support it in a\n`meta` element.\n\n**The allowlist trusts a whole host.** `script-src https://cdn.example.com`\nallows every file on that host, including old library versions and endpoints\nthat echo a caller's input back as script. The specification itself says that\ndeploying a policy that works against cross-site scripting is a challenge, and\nrecommends what it names a Strict CSP: `script-src` built from nonces or hashes\nwith `'strict-dynamic'`, plus `base-uri` set to `'self'` or `'none'`.\n\n**`'unsafe-inline'` is assumed to allow every inline script.** Once a nonce or a\nhash appears in the same source list, browsers that understand them ignore\n`'unsafe-inline'`. The rule lets a policy keep `'unsafe-inline'` as a fallback\nfor browsers too old to know nonces while current ones apply the strict list,\nand it surprises a team that adds a nonce to one script and finds its other\ninline scripts blocked.\n\n**The nonce stops being a secret.** The specification requires a new value every\ntime a policy is sent and asks for at least 128 bits from a cryptographically\nsecure generator. A nonce hard-coded into a template, or a whole page with its\nnonce stored in a shared cache and served to everyone, gives an attacker the\nvalue they need to stamp their own script.\n\n**A policy in a `meta` element does less than the same policy in a header.** The\nbrowser ignores `frame-ancestors`, `report-uri` and `sandbox` when they arrive\nthat way, and the policy only governs what comes after the element in the\ndocument, so anything above it in the head loads unchecked. A site with no say\nover its response headers still gets real protection from a `meta` policy,\nplaced as early in the head as it will go, but anti-framing needs the header.\n\n**A second policy tightens instead of loosening.** A response can carry several\npolicies, from a framework, a proxy and a CDN, and a resource has to pass every\none of them. Adding a policy can only restrict, so a permissive header added\ndownstream to fix a blocked request does nothing, and the fix has to go into the\npolicy that blocked it.\n\n## Further reading\n\n- [Content Security Policy Level 3](https://www.w3.org/TR/CSP3/) — the standard\n  itself, with the Strict CSP recommendation and a section on how nonces get\n  stolen.\n- [HTML Standard: the meta element](https://html.spec.whatwg.org/multipage/semantics.html)\n  — the pragma that applies a policy declared in the page, the directives it\n  drops, and why resources fetched before it may slip past.\n- [Reporting API](https://www.w3.org/TR/reporting-1/) — the endpoint mechanism\n  behind `report-to`, for reading violations before enforcing.\n- [Trusted Types](https://www.w3.org/TR/trusted-types/) — the companion standard\n  that a `require-trusted-types-for` directive switches on, aimed at script\n  injected through the DOM.\n\n\u003chttps://engineer.company/glossary/csp/\u003e\n","date_modified":"2026-10-30T12:43:03Z","description":"How a Content Security Policy stops injected script from running, how to roll one out without breaking a site, and the mistakes that quietly leave it open.","formats":{"gemtext":"https://engineer.company/glossary/csp/index.gmi","gopher":"https://engineer.company/glossary/csp/gophermap","html":"https://engineer.company/glossary/csp/","json":"https://engineer.company/glossary/csp/index.json","markdown":"https://engineer.company/glossary/csp/index.md","pdf":"https://engineer.company/glossary/csp/index.pdf"},"kind":"page","language":"en","title":"What is Content Security Policy?","url":"https://engineer.company/glossary/csp/","version":1}