Course contentsShow
← Web Development
Lesson 2940 of 2,98252. Frontend SecurityFree lesson

SRI with CDNs and Third-Party Libraries

Protecting your application from compromised CDNs by validating popular library resources.

SRI with CDNs and Third-Party Libraries

What you'll learn: How to protect your application from compromised or malicious code served by CDNs and third-party library hosts.

Why This Matters

When you load libraries from external CDNs (like Bootstrap from cdn.jsdelivr.net or React from unpkg.com), you're trusting that server to deliver safe, unmodified code. But what if that CDN gets hacked? Or their DNS is hijacked? Without protection, attackers could inject malicious code into millions of websites simultaneously.

The SRI Shield

Subresource Integrity (SRI) acts like a seal on a medicine bottle. You specify exactly what the file should contain (via its hash), and the browser refuses to execute anything that doesn't match—even if the CDN serves something different.

<!-- Protected: jQuery from CDN with SRI -->
<script 
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha384-vtXRMe3mGCbOeY7l30aIg8H9p3GdeSe4IFlP6G8JMa7o7lXvnz3GFKzPxzJdPfGK"
  crossorigin="anonymous">
</script>

<!-- Protected: Bootstrap CSS -->
<link 
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
  crossorigin="anonymous">

Real-World Protection

Most popular CDNs actually provide SRI hashes directly on their sites. When including jQuery, React, Vue, or Bootstrap, copy the full tag with integrity attributes from their official documentation—don't just grab the URL.

If the CDN is compromised and serves altered code, your users' browsers will block it completely and throw a console error, protecting them from execution.

Key Takeaway: Always use SRI hashes when loading libraries from CDNs—it's your last line of defense against supply chain attacks where external resources are compromised.