SRI for CDN-Hosted JavaScript
Protect your website from compromised CDN scripts using Subresource Integrity. Learn how to add SRI hashes to every external JavaScript file loaded from a CDN.
Detailed Explanation
Securing CDN-Hosted JavaScript with SRI
Content Delivery Networks (CDNs) are a cornerstone of modern web performance, serving JavaScript libraries to millions of websites from edge servers worldwide. However, this centralization creates a single point of failure: if a CDN is compromised, every website loading scripts from it becomes vulnerable. SRI eliminates this risk.
The CDN Supply-Chain Threat
In 2018, the event-stream incident demonstrated how attackers can inject malicious code into widely-used packages. In a CDN context, the threat is even more direct:
- An attacker gains access to the CDN's storage or deployment pipeline
- The attacker modifies a popular library file (e.g.,
jquery.min.js) - Every website loading that file now executes the attacker's code
- User credentials, payment data, and session tokens can be stolen
SRI is the definitive defense against this attack vector.
Adding SRI to Script Tags
<!-- Without SRI (vulnerable) -->
<script src="https://cdn.example.com/lodash@4.17.21/lodash.min.js"></script>
<!-- With SRI (protected) -->
<script
src="https://cdn.example.com/lodash@4.17.21/lodash.min.js"
integrity="sha384-..."
crossorigin="anonymous"
></script>
The crossorigin="anonymous" attribute is required for SRI with cross-origin resources. Without it, the browser cannot access the response body to compute the hash.
Best Practices for CDN Scripts
- Pin exact versions — never use
latestor range URLs with SRI, because the file content will change - Generate hashes from the source — download the file and compute the hash yourself; do not rely solely on the CDN's published hash
- Include fallback loading — if the SRI check fails, load the script from your own server:
<script
src="https://cdn.example.com/lib.js"
integrity="sha384-..."
crossorigin="anonymous"
onerror="loadFallback()"
></script>
- Update hashes when upgrading — every version change requires a new SRI hash
- Automate generation — integrate SRI hash generation into your build pipeline
Common CDN Providers with SRI Support
All major CDN services support and encourage SRI: cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com, and the official Bootstrap and jQuery CDNs all publish integrity hashes alongside their hosted files.
Use Case
Any website loading JavaScript from a public CDN should add SRI integrity attributes. This includes marketing sites using jQuery from Google CDN, dashboards loading Chart.js from cdnjs, documentation sites using highlight.js from jsDelivr, and e-commerce platforms loading payment SDKs from third-party CDNs.