What Is Subresource Integrity (SRI)?

On this page
  1. How does SRI work?
  2. What does SRI protect against?

Subresource Integrity (SRI) lets a browser verify that a script or stylesheet loaded from a third-party host has not been tampered with. You attach a cryptographic hash to the tag; the browser runs the file only if its hash matches. It is a small, powerful defense against one of the scarier modern risks — a trusted CDN serving compromised code to everyone who includes it.

How does SRI work?#

You add an integrity attribute containing the expected hash, and crossorigin for CORS:

<script
  src="https://cdn.example/lib.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
  crossorigin="anonymous"></script>

The browser fetches the file, computes its SHA hash, and compares it to the integrity value. A match runs the script; a mismatch — because the file was altered — blocks it entirely. Trust shifts from “wherever this URL points today” to “exactly the bytes I vetted.”

What does SRI protect against?#

ScenarioWithout SRIWith SRI
CDN compromised, file alteredMalicious code runsBlocked (hash mismatch)
Man-in-the-middle swaps fileMalicious code runsBlocked
Legitimate library updateRuns (as intended)Blocked until you update the hash

That last row is the trade-off: SRI pins an exact version, so you must update the hash when you intentionally upgrade the library.

SRI is a practical piece of supply-chain security at the browser layer. More at the Web Security hub.

Frequently asked questions#

What is Subresource Integrity?

Subresource Integrity (SRI) is a browser feature that lets you attach a cryptographic hash to a script or stylesheet tag. The browser computes the hash of the fetched file and runs it only if it matches. If a CDN is compromised and the file altered, the hash no longer matches and the browser refuses to load it.

What attack does SRI prevent?

SRI defends against a compromised or malicious third-party host — such as a CDN — serving altered code. Without SRI, if an attacker tampers with a hosted library, every site including it runs the malicious version. With SRI, the modified file fails the integrity check and is blocked, containing the supply-chain attack.

Sources & further reading