---
url: "https://web.dev/articles/strict-csp"
titulek: "Mitigate cross-site scripting (XSS) with a strict Content Security Policy (CSP) | Articles | web.dev"
h1: "Mitigate cross-site scripting (XSS) with a strict Content Security Policy (CSP) Stay organized with collections Save and categorize content based on your preferences."
popis: "Learn how to deploy a CSP based on script nonces or hashes as a defense-in-depth against cross-site scripting."
jazyk: "en"
kanonicka: "https://web.dev/articles/strict-csp"
drobecky: ["Articles", "Mitigate cross-site scripting (XSS) with a strict Content Security Policy (CSP)"]
zdroj: "live"
wayback_snapshot: ""
stazeno: "2026-09-13 22:28:10"
znaku: 17457
slov: 2566
kodovani: "iso-8859-2"
sha256: "1b75ec6a722d1f8b5ba7bfd00a52a8909455be8e4b1f4ec8ca07291630ed0b4e"
---
Mitigate cross-site scripting (XSS) with a strict Content Security Policy (CSP)
Stay organized with collections
Save and categorize content based on your preferences.
Lukas Weichselbaum
Browser Support
52
79
52
15.4
[Cross-site scripting (XSS)](https://www.google.com/about/appsecurity/learning/xss/),
the ability to inject malicious scripts into a web app, has been one of the
biggest web security vulnerabilities for over a decade. [Content Security Policy (CSP)](https://developer.mozilla.org/docs/Web/HTTP/CSP)
is an added layer of security that helps to mitigate XSS. To configure a CSP,
add the `Content-Security-Policy` HTTP header to a web page and set values that
control what resources the user agent can load for that page. This page explains how to use a CSP based on nonces or hashes to mitigate XSS,
instead of the commonly used host-allowlist-based CSPs that often leave the page
exposed to XSS because they can be [bypassed in most configurations](https://research.google.com/pubs/pub45542.html). Key term: A *nonce* is a random number used only once that you can use to mark a
`
To let this script run, you must calculate the inline script's hash
and add it to the CSP response header, replacing the `{HASHED_INLINE_SCRIPT}`
placeholder. To reduce the amount of hashes, you can merge all inline
scripts into a single script. To see this in action, refer to this
[example](https://strict-csp-codelab.glitch.me/solution_hash_csp)
and its [code](https://glitch.com/edit/#!/strict-csp-codelab?path=demo%2Fsolution_hash_csp.html%3A1%3A).
Blocked by CSP
CSP blocks these scripts because they were not dynamically added and they have no [`integrity`](https://developer.mozilla.org/docs/Web/Security/Subresource_Integrity#subresource_integrity_with_the_script_element) attribute which matches an allowed source.
Script loading considerations
The inline script example adds `s.async = false`to ensure
that `foo` executes before `bar`, even if
`bar` loads first. In this snippet, `s.async = false`
doesn't block the parser while the scripts load, because the scripts are
added dynamically. The parser stops only while the scripts execute, as
it would for `async` scripts. However, with this snippet,
keep in mind:
One or both scripts might execute before the document has finished
downloading. If you want the document to be ready by the time the
scripts execute, wait for the [`DOMContentLoaded` event](https://developer.mozilla.org/docs/Web/API/Window/DOMContentLoaded_event) before
you append the scripts. If this causes a performance issue because the
scripts don't start downloading early enough, use [preload tags](https://developer.mozilla.org/docs/Web/HTML/Preloading_content) earlier on the page.
`defer = true` doesn't do anything. If you need that
behaviour, run the script manually when it's needed.
Step 3: Refactor HTML templates and client-side code Inline event handlers (such as `onclick="âŚ"`, `onerror="âŚ"`) and JavaScript URIs
(``) can be used to run scripts. This means an
attacker who finds an XSS bug can inject this kind of HTML and execute malicious
JavaScript. A nonce- or hash-based CSP prohibits the use of this kind of markup.
If your site uses any of these patterns, you'll need to refactor them into safer
alternatives. If you enabled CSP in the previous step, you'll be able to see CSP violations in
the console every time CSP blocks an incompatible pattern. Console errors for blocked code. In most cases, the fix is straightforward: Refactor inline event handlers Allowed by CSP A thing.
CSP allows event handlers that are registered using JavaScript.
Blocked by CSP A thing.
CSP blocks inline event handlers.
Refactor `javascript:` URIs Allowed by CSP foo
CSP allows event handlers that are registered using JavaScript.
Blocked by CSP foo
CSP blocks javascript: URIs.
Remove `eval()` from your JavaScript If your application uses `eval()` to convert JSON string serializations into JS
objects, you should refactor such instances to `JSON.parse()`, which is also
[faster](https://v8.dev/blog/cost-of-javascript-2019#json). If you can't remove all uses of `eval()`, you can still set a strict nonce-based
CSP, but you have to use the `'unsafe-eval'` CSP keyword, which makes your
policy slightly less secure. You can find these and more examples of such refactoring in this strict CSP
codelab: Step 4 (Optional): Add fallbacks to support old browser versions Browser Support
52
79
52
15.4
If you need to support older browser versions: Using `strict-dynamic` requires adding `https:` as a fallback for earlier
versions of Safari. When you do this:
All browsers that support `strict-dynamic` ignore the `https:` fallback,
so this won't reduce the strength of the policy. In old browsers, externally sourced scripts can load only if they come from
an HTTPS origin. This is less secure than a strict CSP, but it still
prevents some common XSS causes like injections of `javascript:` URIs. To ensure compatibility with very old browser versions (4+ years), you can add
`unsafe-inline` as a fallback. All recent browsers ignore `unsafe-inline`
if a CSP nonce or hash is present. `Content-Security-Policy: script-src 'nonce-{random}' 'strict-dynamic' https: 'unsafe-inline'; object-src 'none'; base-uri 'none';` Step 5: Deploy your CSP After confirming that your CSP doesn't block any legitimate scripts in your
local development environment, you can deploy your CSP to staging, then to your
production environment: (Optional) Deploy your CSP in report-only mode using the
`Content-Security-Policy-Report-Only` header. Report-only mode is handy to
test a potentially breaking change like a new CSP in production before you
start enforcing CSP restrictions. In report-only mode, your CSP doesn't
affect your app's behavior, but the browser still generates console errors
and violation reports when it encounters patterns incompatible with your CSP,
so you can see what would have broken for your end users. For more
information, see [Reporting API](/articles/reporting-api). When you're confident that your CSP won't break your site for your end-users,
deploy your CSP using the `Content-Security-Policy` response header. We
recommend setting your CSP using an HTTP header server-side because it's more
secure than a `` tag. After you complete this step, your CSP starts
protecting your app from XSS. Limitations A strict CSP generally provides a strong added layer of security that helps to
mitigate XSS. In most cases, CSP reduces the attack surface significantly, by
rejecting dangerous patterns like `javascript:` URIs. However, based on the type
of CSP you're using (nonces, hashes, with or without `'strict-dynamic'`), there
are cases where CSP doesn't protect your app as well: If you nonce a script, but there's an injection directly into the body or the
`src` parameter of that `