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

Handling SRI Failures and Fallbacks

Implementing error handling and local fallback strategies when SRI validation fails.

Handling SRI Failures and Fallbacks

You'll learn: How to gracefully handle situations where Subresource Integrity validation fails and implement fallback strategies to keep your application running.

Why SRI Can Fail

When a browser validates a resource using SRI (checking the cryptographic hash you provided), the validation might fail for several reasons: the CDN served corrupted data, the file was maliciously modified, or network issues altered the response. When this happens, the browser blocks the resource entirely—which could break your application if not handled properly.

Think of SRI like a security seal on a package. If the seal is broken, you don't accept the package. But you need a backup plan—otherwise your app stops working.

Implementing Fallbacks

The most common strategy is to provide a local fallback copy of critical resources. If the CDN version fails SRI validation, you load a trusted local version instead:

<script 
  src="https://cdn.example.com/library.js"
  integrity="sha384-abc123..."
  crossorigin="anonymous"
  onerror="handleSRIFailure(this)">
</script>

<script>
function handleSRIFailure(elem) {
  // Remove the failed script element
  elem.parentNode.removeChild(elem);
  
  // Load local fallback
  const fallback = document.createElement('script');
  fallback.src = '/vendor/library.js'; // Local copy
  document.head.appendChild(fallback);
}
</script>

The onerror handler fires when SRI validation fails (or any loading error occurs), letting you inject a fallback resource from your own server—a copy you control and trust.

Best Practices

Always keep local copies of critical dependencies. For non-critical resources, you might log the failure and continue. Monitor these failures—repeated SRI errors might indicate CDN compromise or misconfiguration.

Key Takeaway: Always implement onerror handlers and local fallbacks for SRI-protected resources to prevent single points of failure from breaking your application entirely.