01 What is SRI?
Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (like scripts or stylesheets) are delivered without unexpected manipulation.
It works by allowing you to provide a cryptographic hash that the fetched file must match. If the file has been modified in any way—by a hacker, a malicious CDN employee, or even a bit-flip error—the hash won't match, and the browser will reject it.
02 The Risks of CDNs
Using a Content Delivery Network (CDN) like cdnjs or jsdelivr is great for performance, but it introduces a security risk: you are trusting a third party with your code execution.
If an attacker compromises the CDN, they could replace jquery.min.js with a version that includes a keylogger or a cryptocurrency miner. Without SRI, every website using that CDN link would instantly serve the malware to its users.
03 How SRI Works
You generate a base64-encoded cryptographic hash (usually SHA-384) of the file you intend to use.
Then, you add an integrity attribute to your <script> or <link> tag:
<script src="https://example.com/example-framework.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script> When the browser downloads the file, it hashes it and compares the result to the integrity attribute. If they don't match, the script is blocked.
04 Implementation Guide
1. Generate the Hash
You can use openssl on the command line:
openssl dgst -sha384 -binary filename.js | openssl base64 -A Or use an online tool like SRI Hash Generator.
2. Add the Attribute
Add the integrity="sha384-..." attribute to your tag.
3. Add Crossorigin
Critical: You MUST add crossorigin="anonymous". Without this, the browser sends the request without credentials and, due to CORS policies, may not be able to access the file content to verify the hash, causing the check to fail.
05 Frequently Asked Questions
Do all browsers support SRI?
Yes, all modern browsers (Chrome, Firefox, Safari, Edge) support Subresource Integrity. It is a widely adopted standard.
What happens if the hash doesn't match?
The browser will refuse to execute the script or apply the stylesheet. This causes the resource to fail silently (though an error is logged to the console), which protects the user but might break site functionality.
Can I use SRI for images?
Currently, the SRI specification is primarily used for scripts and stylesheets (<script> and <link> elements). It is not typically executed for images.
How do I update the hash when the library updates?
You must generate a new hash every time the file content changes. This is why SRI is best used for versioned libraries (e.g., jquery-3.6.0.min.js) rather than 'latest' versions.