How to Implement Subresource Integrity
Pin the exact bytes of third-party scripts and styles with integrity hashes so a compromised CDN cannot run altered code in your pages.
On this page
Introduction
Loading a script or stylesheet from a third-party CDN hands that CDN the ability to run arbitrary code in your users’ browsers. If the CDN is compromised, or a package on it is republished, the bytes your page loads can change without any change on your side. Subresource Integrity pins the exact content: the browser computes the hash of the downloaded file and refuses to execute it if the hash does not match the one you declared. This article covers how SRI works, how to generate and maintain the hashes, and how it interacts with your Content Security Policy and with dynamic script loading.
Why Third-Party Scripts Are Risky
A script tag from a third-party origin runs with full privileges on your page: it can read the DOM, exfiltrate form values, and make requests as the user. You trust the CDN not only while you use it but for every future load, because the URL is stable while the content behind it can change. A compromised CDN or a hijacked account can serve altered JavaScript to every page that references it, and your own build shows no change.
Even without malice, CDNs have served the wrong file after an incident, and packages have been republished with breaking or harmful changes under the same version. SRI protects against all of these by binding the load to the exact content you reviewed, no matter what the CDN later serves.
Integrity Hashes
SRI works with a cryptographic hash of the resource, declared in the integrity attribute. The browser downloads the file, computes the hash, and only executes it if the computed value matches one of the declared hashes. If the CDN serves different bytes, the hash mismatches and the script does not run. Use sha384 or sha256; include the algorithm prefix.
<!-- Pin the exact bytes of a third-party script -->
<script
src="https://cdn.example.com/lib/[email protected]/widget.min.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>
<!-- Style sheets support integrity too -->
<link
rel="stylesheet"
href="https://cdn.example.com/lib/[email protected]/theme.min.css"
integrity="sha384-fF5y8Z0d8b6aN1x7wQk2mS2sUu1p3n0Jx7bG4p9wQ0e2b8r0u0m5o1w2Y4g9Q3p"
crossorigin="anonymous">
Generating and Updating Hashes
Compute the hash from the exact bytes you will serve, base64-encoded, and record which version it belongs to. Regenerate the hash whenever you upgrade the dependency, and never copy a hash from a CDN’s documentation without verifying it against the file you actually load, because documentation can be stale or wrong. Automate the hash generation in your build so it stays in sync with the version.
# Compute the SRI hash for a file you will load
curl -sSL https://cdn.example.com/lib/[email protected]/widget.min.js \
| openssl dgst -sha384 -binary \
| openssl base64 -A \
| sed 's/^/sha384-/'
# Local file, same computation
openssl dgst -sha384 -binary dist/widget.min.js | openssl base64 -A | sed 's/^/sha384-/'
# Verify a hash matches the file before trusting it
echo "sha384-$(openssl dgst -sha384 -binary widget.min.js | openssl base64 -A)" \
| grep -q "$EXPECTED_HASH" && echo "hash matches"
Integration with CSP
SRI and Content Security Policy reinforce each other. A policy that allows a CDN origin to load scripts still permits any content from that origin; SRI narrows the permission to the exact bytes. Together, a strict CSP restricts which origins may load, and SRI restricts which content from those origins is trusted. Use hash-based CSP for your own inline scripts as well, so a change to an inline script requires a policy change.
When the two are combined, remember that an SRI mismatch causes the resource to be blocked, which may look like a CSP violation in the console. Distinguish the two when debugging: an SRI failure names the integrity attribute, while a CSP failure names the directive. Both are failures to load, by design.
Handling Dynamic Scripts
Scripts injected at runtime with createElement need the integrity attribute set before the element is added to the document, because the fetch starts as soon as the src is set and the check happens at execution. Set both src and integrity programmatically, and verify the load succeeded so a mismatch does not fail silently. A script that fails SRI is not executed; handle the error event so the page degrades rather than breaking.
Cross-origin resources require the CORS header for SRI to work, which is why crossorigin=“anonymous” appears alongside integrity. Without it the browser cannot read the response body to hash it, and the check cannot be performed. If a CDN does not send the CORS header and you cannot enable it, that CDN cannot be used with SRI; prefer one that can.
Limitations
SRI pins content but not freshness: it does not stop you from loading an old vulnerable version that still hashes correctly. It also does not protect resources loaded in ways that bypass the attribute, such as a script fetched by another script. And it cannot protect inline scripts without hash-based CSP, which is a related but separate mechanism.
For dependencies you control, the stronger approach is to vendor them into your own build and serve them from your own origin, so the CDN is not a trust boundary at all. SRI is the mitigation when you must load from a third party; self-hosting removes the third party. Choose deliberately, and when you must use a CDN, pin the bytes and enable CORS so the pin can be enforced.
Conclusion
Subresource Integrity pins the exact bytes a browser will execute, so a compromised CDN cannot run altered code under your domain. Declare a sha384 hash for every third-party script and stylesheet, set crossorigin so the browser can hash the response, generate and update hashes in your build, and combine SRI with a strict CSP for defence in depth. Set integrity when injecting scripts at runtime, and remember that SRI pins content and not freshness. Where you can, vendor the dependency and remove the third-party trust boundary entirely.
Sources: MDN: Subresource Integrity, W3C: Subresource Integrity, MDN: Content Security Policy.
FAQ
- Why does SRI require the crossorigin attribute?
- The browser must read the response body to compute its hash, and cross-origin reads need CORS. Without crossorigin="anonymous" and a CORS header from the CDN, the browser cannot hash the file and the integrity check cannot be enforced.
- Does SRI protect against a vulnerable version of a library?
- No. It pins content, so if you reference an old vulnerable version and its hash matches, the browser loads it. SRI stops altered bytes, not stale ones. Use dependency scanning and upgrades for the version problem.
Report a problem with this articleOpens a pre-filled issue on GitHub.