How to Add Subresource Integrity (SRI)
What is this?
Subresource Integrity (SRI) lets you verify that resources loaded from CDNs or third-party servers have not been tampered with. You include a cryptographic hash in the integrity attribute, and the browser refuses to execute the resource if the hash does not match.
Why it matters
- Security: Protects against supply-chain attacks where a CDN or third-party is compromised
- Trust: Ensures the exact code you tested is what runs in your users' browsers
- Compliance: Recommended by OWASP and required by some security audits
How to fix it
Add integrity attributes to script and link tags
<script
src="https://cdn.jsdelivr.net/npm/alpinejs@3.14.8/dist/cdn.min.js"
integrity="sha384-..."
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="https://cdn.example.com/framework.min.css"
integrity="sha384-..."
crossorigin="anonymous"
/>
Generate SRI hashes
# Generate hash from a local file
openssl dgst -sha384 -binary script.js | openssl base64 -A
# Output: sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC
# Or use curl to hash a remote file
curl -s https://cdn.example.com/script.js | openssl dgst -sha384 -binary | openssl base64 -A
You can also use the SRI Hash Generator web tool.
Webpack / build tool integration
// webpack.config.js
const SriPlugin = require('webpack-subresource-integrity');
module.exports = {
output: { crossOriginLoading: 'anonymous' },
plugins: [new SriPlugin({ hashFuncNames: ['sha384'] })],
};
Common mistakes
- Forgetting the
crossorigin="anonymous"attribute. SRI requires CORS to work with cross-origin resources. - Not updating the hash when the CDN resource is updated to a new version.
- Only adding SRI to scripts but not stylesheets. Both can be attack vectors.
Test your fix
After adding SRI, audit your site on BeaverCheck to verify in the Security tab.