Difficulty: Intermediate
What is Subresource Integrity (SRI), how does the browser enforce it, and when should you use it for scripts loaded from a CDN?
Subresource Integrity is a browser feature that lets you pin the exact contents of a script or stylesheet you load from somewhere else, usually a CDN. You add an integrity attribute containing a cryptographic hash of the file; the browser hashes what it downloads and refuses to execute or apply it if the hashes do not match. This protects you if the CDN, or the domain serving the file, is compromised and starts serving modified code.
integrity="sha384-<base64 hash>" along with crossorigin="anonymous".Supported algorithms are sha256, sha384 and sha512. You can list several hashes separated by spaces, and the browser uses the strongest algorithm it supports.
crossorigin is requiredFor cross-origin resources the browser can only check integrity if the response is CORS-enabled. Without CORS the response would be opaque and its bytes not inspectable by the page, so the browser blocks it instead. The CDN must send Access-Control-Allow-Origin, which all major public CDNs (jsDelivr, cdnjs, unpkg) do.
Loading third-party JavaScript means trusting whoever controls that server forever. A real example: in 2024 the polyfill.io domain changed hands and began serving malicious code to sites that embedded it, affecting a very large number of websites. Any site that had pinned a specific file with SRI would have had the modified response blocked rather than executed. More generally SRI protects against:
/latest/lib.js or the server varies content by user agent, the hash will break on the next change. Always pin an exact version.<script> and <link rel="stylesheet"> (plus <link rel="preload"/"modulepreload">). It does not apply to images, iframes or code that a script loads later itself.webpack-subresource-integrity or Vite plugins).# Download the exact pinned version
curl -sL https://cdn.jsdelivr.net/npm/dayjs@1.11.13/dayjs.min.js -o dayjs.min.js
# Compute base64-encoded SHA-384 digest
echo "sha384-$(openssl dgst -sha384 -binary dayjs.min.js | openssl base64 -A)"
Always hash the exact versioned file you will reference. The output goes straight into the integrity attribute.
<!-- Pinned version, hash, and CORS mode -->
<script
src="https://cdn.jsdelivr.net/npm/dayjs@1.11.13/dayjs.min.js"
integrity="sha384-REPLACE_WITH_GENERATED_HASH"
crossorigin="anonymous"
defer></script>
If the CDN ever serves different bytes for this URL, the browser refuses to run it and logs an integrity error.
Subresource Integrity, integrity attribute, SHA-384, CDN Compromise, Supply Chain Security, CORS