Full answer
CSP is a second line of defence against XSS. Even if an attacker finds a way to inject markup, the browser refuses to run what the policy does not allow.
The policy is a list of directives:
default-src 'self'is the fallback for every type of resource, here the site's own origin.script-srccontrols scripts. Sources can be origins, hashes or nonces.object-src 'none'removes old plugin content.base-uri 'self'stops an injected<base>tag from changing relative URLs.frame-ancestorscontrols who may embed the page.report-toorreport-urisends violation reports to an endpoint.
Allowing inline scripts with 'unsafe-inline' removes most of the value of the policy, because injected inline scripts are inline scripts. The better way is a nonce or a hash.
- A nonce is a random value generated for each response. The server puts it in the header,
script-src 'nonce-R4nd0m', and on every script tag it trusts,<script nonce="R4nd0m">. An attacker who injects markup cannot know the nonce for this response. It must be unpredictable and new each time. A fixed nonce is useless. - A hash allows one exact inline script by its content hash, which suits a static page.
'strict-dynamic'lets a trusted script load further scripts, which helps with bundlers and tag managers.
Roll out in steps. First use Content-Security-Policy-Report-Only and read the reports. Then enforce the policy and keep monitoring. Inline event handler attributes such as onclick are blocked, so they must become addEventListener calls.
The Node server below sends a policy with a fresh nonce on each response. The page has one script with the nonce, one without, and an image with an inline onerror attribute. The test shows that only the first script runs and the browser reports violations for the others.
import http from 'node:http';
import { randomBytes } from 'node:crypto';
http.createServer((req, res) => {
const nonce = randomBytes(16).toString('base64');
res.setHeader('Content-Security-Policy',
`default-src 'self'; script-src 'nonce-${nonce}'; object-src 'none'; base-uri 'self'`);
res.setHeader('Content-Type', 'text/html');
res.end(`<!doctype html><title>csp</title>
<script nonce="${nonce}">window.trusted = true;</script>
<script>window.injected = true;</script>
<img src="/missing.png" onerror="window.handler = true">`);
}).listen(process.env.PORT, () => console.log('listening'));Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Run with a Node server and headless Chrome. Only the script with the nonce ran, the unmarked inline script and the inline error handler were blocked, the console reported violations, and the nonce differed between two responses.
Key points
- CSP is a header that allowlists the sources the browser may use.
- unsafe-inline weakens script-src, so avoid it.
- A nonce is random for each response and appears in the header and on trusted scripts.
- Inline event handlers are blocked and must become addEventListener calls.
- Roll out with Report-Only first, then enforce.
Common mistakes
- Using a fixed nonce, or one generated at build time.
- Adding unsafe-inline to make the errors go away.
- Setting the policy only in a meta tag and expecting every directive to work there.
- Skipping the report-only step and breaking the site.
Follow-ups
- Why is a hash a better fit for a static page?
- What does strict-dynamic do?
- Which directives cannot be set in a meta tag?
Tips
- Explain why a nonce beats unsafe-inline in one sentence.
- Mention the Report-Only rollout.