Frontend Patterns

Pattern

Subresource Integrity

Use integrity hashes on external scripts and stylesheets to ensure resources haven't been tampered with.

Subresource Integrity

Problem

Loading scripts and stylesheets from external CDNs introduces a security risk: if the CDN is compromised or serves malicious content, your application executes that code without verification. Users trust your site, but you have no guarantee that external resources remain unchanged. A tampered script can steal user data, inject malware, or compromise your entire application.

Solution

Add cryptographic hashes to script and stylesheet tags to verify third-party resources haven’t been tampered with. This protects against compromised CDNs.

Example

This demonstrates adding cryptographic integrity hashes to external resources to verify they haven’t been tampered with, protecting against compromised CDNs or malicious code injection.

<script
  src="https://cdn.example.com/lib.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
  crossorigin="anonymous"
></script>
<!-- Browser verifies file hash before executing - blocks tampered scripts -->

Benefits

  • Protects against compromised or malicious CDN content.
  • Provides cryptographic verification that resources haven’t been altered.
  • Prevents silent injection of malicious code from third-party sources.
  • Adds negligible performance overhead for significant security benefit.

Tradeoffs

  • Breaks loading if CDN updates the resource without updating the hash.
  • Requires generating and maintaining hashes for all external resources.
  • Can complicate updates when third-party libraries change.
  • Needs careful coordination between resource updates and hash updates.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.