About Subresource Integrity (SRI)
Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.
Why Use SRI?
- Security: Protects your site from malicious content being injected into third-party resources
- Trust: Ensures the resource you're loading hasn't been tampered with
- Compliance: Helps meet security compliance requirements
- CDN Safety: Safely use CDNs without worrying about compromised files
How to Use SRI Hashes
- Generate a hash for your resource using this tool
- Add the
integrity
attribute to your<script>
or<link>
tag - Include the
crossorigin
attribute
Example for JavaScript:
<script src="https://example.com/example.js" integrity="sha384-generated-hash-here" crossorigin="anonymous"></script>
Example for CSS:
<link href="https://example.com/example.css" integrity="sha384-generated-hash-here" crossorigin="anonymous" rel="stylesheet">
Frequently Asked Questions
All modern browsers support SRI. This includes Chrome, Firefox, Edge, Safari, and Opera. Internet Explorer 11 does not support SRI.
SHA-256 is sufficient for most cases. SHA-384 and SHA-512 provide stronger security but result in longer hashes. Choose based on your security requirements.
Yes, but it's not necessary as the primary benefit is for external resources. Browsers enforce same-origin policy for local files.
The browser will block the resource from loading and display an error in the console. Your page will behave as if the resource failed to load.
It's recommended for all critical resources where integrity is important. However, be cautious with frequently updated resources as you'll need to update the hash each time.
Security Best Practices
- Use SRI for all third-party scripts and stylesheets
- Combine SRI with Content Security Policy (CSP) for stronger protection
- Regularly audit and update your SRI hashes when resources change
- Consider using build tools to automatically generate SRI hashes during deployment
- Test your site after implementing SRI to ensure no resources are blocked