Security guide

How to Add Subresource Integrity (SRI)

In June 2024 the Polyfill.io CDN was acquired by new owners who used it to inject malicious JavaScript into over 100,000 websites. Every site loading from that CDN without an integrity attribute ran the attacker’s code. Every site with a correct SRI hash got a browser-blocked load error instead. One attribute, one hash: that is the entire defence.

How SRI works

Subresource Integrity adds two attributes to a <script> or <link rel="stylesheet"> tag: integrity and crossorigin. The integrity value is a hash algorithm name followed by a hyphen and a base64-encoded hash of the file’s exact bytes:

<script
  src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"
  integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ=="
  crossorigin="anonymous"
  referrerpolicy="no-referrer"></script>

When the browser fetches the resource, it hashes the response body using the algorithm specified and compares it to your hash. If they match, the file is executed or applied. If they differ — because the CDN was compromised, the file was modified, or an attacker performed a man-in-the-middle attack — the browser blocks the resource and logs a network error. The page sees a failed script load, not an injected script.

SRI is your defence when the CDN is the attacker. It does nothing to protect against XSS from your own origin, malicious code in npm packages you bundle yourself, or dynamically loaded scripts. It specifically targets the scenario where a third-party file host delivers something different than what you originally validated.

Three hash algorithms are supported: sha256, sha384, and sha512. Use sha384 or sha512 — sha256 is no longer recommended for new deployments. You can specify multiple hashes separated by spaces if you want to support parallel file versions:

integrity="sha384-abc123... sha512-def456..."
<!-- browser accepts the resource if ANY listed hash matches -->

Generating the hash

There are three reliable methods:

1. openssl (always available)

# Download the file and hash it in one pipeline
curl -s https://cdn.example.com/library.min.js \
  | openssl dgst -sha384 -binary \
  | openssl base64 -A

# Then prefix with the algorithm name:
# integrity="sha384-<output>"

2. CDN documentation pages

Most major CDNs provide pre-generated SRI hashes on each version’s download page — they are the authoritative source since they hash the canonical file. Check:

  • jsDelivr — every package version page has a “Show SRI” link
  • cdnjs — copy icon next to each file shows the tag with integrity pre-filled
  • Bootstrap, jQuery, React official docs — CDN install snippets always include integrity attributes

Copy SRI hashes from the CDN’s own docs rather than computing them yourself when available, because you verify the file as the CDN intended to serve it.

3. npm package hash (for known versions)

# If you have the package locally (e.g. from node_modules)
cat node_modules/react/umd/react.production.min.js \
  | openssl dgst -sha384 -binary \
  | openssl base64 -A
Regenerate the hash every time the file changes. If you upgrade a library version, the hash changes. A stale integrity value blocks your own legitimate file update and breaks the site. Build tool integration (below) handles this automatically.

The crossorigin attribute

SRI requires the browser to read the full response body of the fetched resource to compute its hash. For cross-origin resources (a CDN URL), the same-origin policy blocks this unless the server opts in to CORS. The crossorigin="anonymous" attribute tells the browser to make the request in CORS mode without sending credentials.

This means the CDN must respond with Access-Control-Allow-Origin: * (or the requesting origin). All major public CDNs (jsDelivr, cdnjs, Cloudflare CDN, unpkg) support CORS on their served files. If a CDN does not send a CORS header, the browser cannot perform SRI verification and the resource load fails.

ScenarioResult
CDN supports CORS, hash correctLoad succeeds
CDN supports CORS, hash mismatch (compromised file)Browser blocks load
CDN supports CORS, no integrity attributeLoads without verification
CDN has no CORS header, integrity presentBrowser blocks load
Same-origin resource, no crossorigin neededSRI works without crossorigin

What SRI covers — and what it does not

✅ Covered

<script src="..."> tags
with an integrity attribute

✅ Covered

<link rel="stylesheet" href="..."> tags with an integrity attribute

⚠️ Not covered

fetch(), XMLHttpRequest, dynamic import() — runtime-loaded resources cannot be SRI-verified

⚠️ Not covered

Scripts you bundle yourself via npm — the hash is of your bundle, not the CDN’s copy

⚠️ Not covered

Resources loaded by scripts (scripts that load other scripts, analytics injecting tags)

⚠️ Not covered

Images, fonts, <iframe> content — SRI is specified only for script and link elements

SRI + CSP together. A Content-Security-Policy with require-sri-for script style (partial browser support) enforces that every loaded script and stylesheet has a valid integrity attribute — the browser refuses any that don’t. Combined with a tight script-src allowlist, this closes the gap where an attacker adds a new CDN script tag without a hash.

Build tool integration

Manual hash management is error-prone. Build tools can generate and inject SRI hashes at build time, which is the recommended approach for production sites that update dependencies regularly.

Vite — vite-plugin-sri

// Install
npm install -D vite-plugin-sri3

// vite.config.js
import { defineConfig } from 'vite'
import sri from 'vite-plugin-sri3'

export default defineConfig({
  plugins: [
    sri({
      // default algorithm is sha384
      algorithm: 'sha384',
    }),
  ],
})

// After build, script tags in dist/index.html
// automatically get integrity attributes

webpack — webpack-subresource-integrity

// Install
npm install -D webpack-subresource-integrity

// webpack.config.js
const { SubresourceIntegrityPlugin } = require('webpack-subresource-integrity')

module.exports = {
  output: {
    crossOriginLoading: 'anonymous',
  },
  plugins: [
    new SubresourceIntegrityPlugin({
      hashFuncNames: ['sha384'],
      enabled: process.env.NODE_ENV === 'production',
    }),
  ],
}

Next.js (experimental)

// next.config.js
module.exports = {
  experimental: {
    sri: {
      algorithm: 'sha384',
    },
  },
}
// Adds integrity attributes to all script tags in the generated HTML
// Requires Next.js 13.4+ and is marked experimental

Manual HTML (static sites, CDN includes)

For libraries loaded directly from a CDN in static HTML, add the attributes by hand. Check the CDN’s own documentation for the correct hash — do not compute it from a local copy that might differ from what the CDN serves:

<!-- Bootstrap 5.3 from jsDelivr -->
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
  integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
  crossorigin="anonymous">

<script
  src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
  integrity="sha384-YvpcrYf0tY3lHB60NNkmXc4s9bIOgUxi8T/jzmqdl12WBQIB20cVqbSx3iJqfHhV"
  crossorigin="anonymous"></script>

What to do when an SRI-blocked load breaks your site

When you update a library version, the hash changes. If the integrity value in your HTML still references the old hash, the browser blocks the new file. You’ll see a console error like:

Failed to find a valid digest in the 'integrity' attribute for resource
'https://cdn.example.com/library.min.js' with computed SHA-384 integrity
'sha384-XYZ...'. The resource has been blocked.

The fix: regenerate the hash for the new file version (method 1 or 2 above) and update the integrity attribute. If you are using a build tool plugin, rebuilding the project handles this automatically.

Verify with HardenCheck

HardenCheck grades your HTTP response headers including your Content-Security-Policy, which can include a require-sri-for directive. To check that SRI attributes are actually present on your external resource tags, inspect your page HTML directly — browser DevTools → Sources lists all loaded scripts and their origin, and View Source shows whether each external tag has an integrity attribute.

Check my headers with HardenCheck →

Frequently asked questions

What is Subresource Integrity and how does it work?

SRI is a browser security feature that lets you pin a cryptographic hash to an external <script> or <link> tag. You add an integrity attribute containing a base64-encoded sha384 (or sha512) hash of the file. When the browser fetches the resource, it hashes what it receives and compares it to your value. A match means the file is identical to what you validated. A mismatch — caused by a compromised CDN, a modified file, or a network attack — causes the browser to block the resource from executing.

Does SRI protect against CDN supply chain attacks like the Polyfill.io compromise?

Yes — exactly. In June 2024 the polyfill.io CDN was acquired by new owners who modified served JavaScript to inject malicious redirects into over 100,000 websites. Any site without an integrity attribute ran the attacker’s code silently. Any site with a correct SRI hash got a browser-blocked load error instead — the user sees a broken widget, not a compromised session. This is the canonical case SRI was designed for: a CDN you don’t control serving something different than what you originally validated.

How do I generate an SRI hash for a CDN resource?

Three methods: (1) curl -s URL | openssl dgst -sha384 -binary | openssl base64 -A — prefix the output with sha384-. (2) Copy from the CDN’s own documentation — jsDelivr, cdnjs, Bootstrap, and jQuery all show pre-generated SRI hashes on each version’s page. (3) Use a build tool plugin (vite-plugin-sri3, webpack-subresource-integrity) that generates and injects hashes automatically at build time, which is the most reliable approach for projects that update dependencies regularly.

Why do I need the crossorigin attribute with SRI?

The browser needs to read the full response body to compute its hash, which is blocked by the same-origin policy for cross-origin resources. crossorigin="anonymous" triggers a CORS request (no credentials), and the CDN must respond with Access-Control-Allow-Origin: *. All major public CDNs support this. Without crossorigin, the browser cannot verify the hash and either blocks the resource or skips verification depending on the browser version.

Does SRI work for resources fetched with JavaScript?

No. SRI only applies to static HTML tags: <script src> and <link rel="stylesheet">. It does not apply to fetch(), XMLHttpRequest, import(), or scripts that dynamically create new <script> elements at runtime. For those, a tight script-src Content-Security-Policy that allowlists only specific CDN origins is the complementary control.

What happens if the SRI hash doesn’t match?

The browser blocks the resource. For a script, the code is never executed. For a stylesheet, the styles are not applied. The block happens before the content touches the rendering engine. The browser logs a console error identifying the hash mismatch and the blocked URL. The page continues to load but the feature depending on that resource will be broken — which is the intended outcome: a broken widget is recoverable; silently executed attacker code is not.

Does HardenCheck check for SRI on CDN resources?

HardenCheck grades HTTP response headers including your CSP — it does not parse your HTML for individual script tag attributes. To audit SRI coverage, inspect your page HTML (View Source or DevTools → Sources) and check that every external <script src> and <link href> pointing to a CDN has an integrity attribute. HardenCheck does grade your CSP strength, including whether it has a restrictive script-src that limits which CDN domains can serve scripts to your page.

Also in the Copper Bay Labs ship-safety suite

SRI protects specific CDN script tags — here are guides for the other layers of browser security HardenCheck covers: