How CSP limits cross-site scripting
Cross-site scripting (XSS) happens when an attacker gets their own script into your page. Output encoding and safe templates are the primary defense. A Content Security Policy is the second layer. It tells the browser which scripts are yours, so that an injected one is refused even when the first defense fails.
There are two ways to say which scripts are yours. An allowlist names hosts, as in
script-src 'self' https://cdn.example.com. It is easy to write but often weak, because a large host may serve
something that an attacker can use, such as a JSONP endpoint or an old library. A strict policy marks
individual scripts with a random nonce or a hash and adds 'strict-dynamic',
which lets those scripts load others. Host names then stop mattering.
Content-Security-Policy: script-src 'nonce-R4nd0mPerResponse' 'strict-dynamic'; object-src 'none'; base-uri 'none'
The companion directives close common bypasses. object-src 'none' blocks plugin content.
base-uri 'none' stops an injected base element from redirecting relative script URLs.
form-action limits where an injected form can send data.
How CSP prevents clickjacking
In a clickjacking attack, another site loads your page in an invisible frame and tricks the user into clicking it.
frame-ancestors lists who may frame the page, and 'none' forbids everyone. Two details catch people
out. It does not fall back to default-src, so leaving it out means no protection. It also has no effect in a
meta element, so it has to be sent as a header.
What the linter looks for
| Severity | Examples |
|---|---|
| Critical | Scripts unrestricted, 'unsafe-inline' without a nonce or hash, * or https: for scripts |
| High | 'unsafe-eval', no object-src 'none', data: scripts, unquoted keywords |
| Medium | No frame-ancestors or base-uri, http: sources, short nonces, unknown directives |
| Low | No form-action or default-src, wildcard images |
The grade is a summary to compare drafts. It cannot tell whether the policy suits your site, and a high grade on a policy that breaks checkout is no success. Read the findings and test in a browser.
Enforced and report-only policies
Content-Security-Policy blocks violations. Content-Security-Policy-Report-Only blocks nothing and
reports what would have been blocked. Both can be sent on the same response and are evaluated independently, which makes it
possible to enforce one policy while testing a stricter one.
Reports go to the URL in report-uri, or to an endpoint named by report-to and defined in the
Reporting-Endpoints header. Sending both covers more browsers, and the Report-Only preset does so. Expect
noise: browser extensions inject scripts and cause violations that have nothing to do with your code.
upgrade-insecure-requests and sandbox are ignored in a report-only policy. Remember that reports
contain page URLs, so treat the endpoint's data accordingly.
Using Google Analytics and AdSense
Google states that it supports only a strict, nonce-based policy for AdSense and not an allowlist, because its ad domains
change. The preset follows that published policy. It includes 'unsafe-eval', which costs points in the grade.
Every script tag needs the nonce, including the ad code, so a purely static site cannot use it without an edge function.
HSTS and preload pitfalls
Strict-Transport-Security tells a browser to use only HTTPS for your host for max-age seconds. It defeats
downgrade attacks after the first visit, and it removes the option to click through certificate warnings. That last property
is also the risk: if your certificate fails, users cannot get in.
- Start small. Use five minutes, then a week, then a month, and watch for problems before choosing a year.
- includeSubDomains reaches everything. Internal tools, old hosts and vendor-hosted subdomains without HTTPS become unreachable.
- Preload is close to permanent. The list needs a valid certificate, HTTP to HTTPS redirects, a max-age of at least 31536000, and both
includeSubDomainsandpreload. The maintainers warn that inclusion cannot easily be undone. - Do not send preload by accident. With the directive present, anyone may submit your domain.
- Browsers ignore HSTS over HTTP. You still need a redirect for the first visit.
How Nginx and Apache inherit headers
In Nginx, add_header directives are inherited from the level above only if the current level
defines none of its own. Adding a single cache header in a location block silently removes every security
header there. Put the shared headers in a file and include it in each block that adds its own, or use
add_header_inherit merge; in version 1.29.3 or later. The always parameter matters too. Without
it, headers are added only to a fixed list of success and redirect codes, so error pages are unprotected.
In Apache, mod_headers keeps two tables, onsuccess (the default) and always.
Header always set also covers errors and internal redirects such as custom error documents. The tables are
separate, so a header set by your application in one and by Apache in the other can be sent twice. If that happens, add
Header onsuccess unset for that name before the always line.
Escaping differs by server
The exports escape each value for their target. Nginx expands $name inside quotes and offers no escape, so a
literal dollar sign is written with a geo variable. Apache treats % as a format specifier, so it is
doubled. Cloudflare Pages limits each line of _headers to 2,000 characters, and neither Cloudflare Pages nor
Netlify applies the file to responses from functions. Express output creates a fresh nonce for each request.
The other headers
- X-Content-Type-Options: nosniff stops browsers from guessing a file type and running an upload as script.
- Referrer-Policy limits how much of the URL other sites receive.
strict-origin-when-cross-originsends only the origin. - Permissions-Policy turns off features such as the camera for your page and its frames. An empty list,
(), blocks everyone. - Cross-Origin-Opener-Policy isolates your window from others.
same-originbreaks sign-in popups that rely onwindow.opener.
After deploying, request a normal page, a redirect, an error page and a static file, and confirm the headers on each. Content delivery networks and application frameworks can add, remove or duplicate headers along the way.
Why is 'unsafe-inline' rated Critical in one policy and Info in another?
On its own it lets injected inline scripts run, which defeats the main purpose of CSP. When the same directive has a nonce or a hash, or 'strict-dynamic', browsers that support those ignore 'unsafe-inline'. It then remains only as a fallback for very old browsers.
Do I still need X-Frame-Options if I have frame-ancestors?
Browsers that support CSP use frame-ancestors from an enforced policy and ignore X-Frame-Options. Sending both is harmless and covers old clients, as long as they agree: DENY matches 'none', and SAMEORIGIN matches 'self'. X-Frame-Options cannot list several allowed sites, so use frame-ancestors for that.