Request Integrity and Subresource Integrity
You'll learn how to use the integrity option to ensure fetched resources haven't been tampered with by verifying them against cryptographic hashes.
What Is Integrity Checking?
When you fetch resources from external servers (like CDNs), there's a risk the file could be modified—either through a compromised server or a man-in-the-middle attack. Subresource Integrity (SRI) lets you specify a cryptographic hash of the expected content. The browser will only use the resource if its hash matches what you provided, rejecting it if tampered with.
Think of it like a security seal on medication: if the seal is broken, you know not to trust the contents.
Using the integrity Option with Fetch
The Fetch API supports integrity verification through the integrity option in the request configuration:
fetch('https://cdn.example.com/library.js', {
integrity: 'sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/ux...',
method: 'GET'
})
.then(response => {
if (!response.ok) throw new Error('Fetch failed');
return response.text();
})
.catch(error => {
console.error('Integrity check failed or network error:', error);
});
If the fetched file's hash doesn't match sha384-oqVuAfXRKap7..., the browser will reject the response and trigger an error.
How Integrity Hashes Work
The integrity value contains:
- An algorithm prefix (
sha256,sha384, orsha512) - A Base64-encoded hash of the file's contents
You generate these hashes using tools or online generators before deployment. The stronger the algorithm (sha512 > sha384 > sha256), the more secure.
Why This Matters
Integrity checking protects against:
- Compromised CDNs: Malicious code injected into third-party resources
- Network attacks: Modified responses during transit
- Supply chain attacks: Altered dependencies
Key Takeaway: Use the integrity option in fetch() to verify that external resources match expected cryptographic hashes, protecting your application from tampered or malicious content.