Join our Newsletter — 33% off our NHI Course
Home› Guides› Subresource Integrity (SRI) Guide: Hashing Third-Party Scripts and…
Guide Web & API Security

Subresource Integrity (SRI) Guide: Hashing Third-Party Scripts and Styles

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 16 min read
On this page

Every script or stylesheet your page loads from a CDN or another origin runs with the full authority of your page, and if that host is compromised the browser will execute whatever it now serves. Subresource Integrity (SRI) is the browser feature that closes that gap for static files: you publish a cryptographic hash of the exact file you expect, and the browser refuses to use anything that does not match. This guide covers how SRI works at the specification level, the CORS rules that trip most teams up, which resources SRI can and cannot protect, how to generate and maintain hashes in a build pipeline, how to enforce coverage with the newer Integrity-Policy header, and how SRI evidence supports PCI DSS v4.0.1 requirements 6.4.3 and 11.6.1. It is written for front-end engineers, application security teams and assessors who need more than a one-line "add SRI" recommendation.

Key takeaways

  • SRI pins content, not a location. The integrity attribute carries one or more base64 hashes (sha256, sha384 or sha512); if the fetched bytes do not match, the browser returns a network error and the script never runs.
  • Cross-origin SRI needs CORS. Without crossorigin="anonymous" and an Access-Control-Allow-Origin header from the host, an integrity-protected request fails by design.
  • SRI only fits static, versioned files. "Latest" URLs, per-browser bundles, tag manager loaders and vendor scripts that change without notice cannot be hashed in advance; those need self-hosting, isolation or monitoring instead.
  • Coverage can now be enforced. Integrity-Policy-Report-Only and then Integrity-Policy let a page report, then block, any script or stylesheet that loads without integrity metadata.
  • SRI is evidence, not a full answer, for PCI DSS 6.4.3. It is a strong method to assure integrity of each payment page script, but you still need the authorisation and inventory elements, plus change and tamper detection under 11.6.1.

How SRI works

The W3C Subresource Integrity specification (currently a Level 2 Editor's Draft maintained by the Web Application Security Working Group) defines a single mechanism: integrity metadata attached to a request, checked by the browser against the response body before the resource is executed or applied.

  • Supported elements: <script>, and <link> where rel is stylesheet, preload or modulepreload. The specification notes that support for other elements (images, iframes, media) may come in a future revision; today they are not covered.
  • Syntax: the value is a whitespace-separated list of <algorithm>-<base64 digest> expressions, for example integrity="sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO". A ?option suffix is reserved in the grammar, but no options are defined and browsers must ignore unknown ones.
  • Algorithms: only sha256, sha384 and sha512 are valid. The specification orders them from weakest to strongest and states that SHA-384 is a good baseline; MD5 and SHA-1 are explicitly not recommended and are not accepted.
  • Strongest wins: if you list hashes from more than one algorithm, the browser discards all but the strongest algorithm present and checks only those. If you list several hashes of the same algorithm, a match on any one passes, which is how you allow two known-good versions during a transition.
  • Failure behaviour: a mismatch produces a network error and fires an error event on the element. You can catch that event to load a fallback copy from your own origin, but a fallback that silently loads an unhashed copy defeats the control.
  • Preload headers: integrity can also be expressed on an HTTP Link header, for example Link: </style.css>; rel=preload; as=style; crossorigin="anonymous"; integrity="sha256-...".
  • ES modules: import maps accept an integrity key that maps module URLs to integrity metadata, so dynamically and statically imported modules can be checked even when no <script> tag carries the attribute.

SRI and CORS: the rule that breaks most rollouts

The specification states plainly that SRI requires CORS and that using it without CORS is a logical error. The reason is privacy: if a page could attach a guessed hash to any cross-origin URL and watch for load failures, it could learn the contents of resources it is not allowed to read, such as whether a user is logged in to another site. Browsers therefore refuse to apply integrity checks to no-cors requests, and a request with an integrity attribute but no crossorigin attribute always fails.

Markup and server responseResultNotes
integrity set, no crossorigin, cross-origin hostBlockedRequest goes in no-cors mode; integrity cannot be applied, so the load fails.
crossorigin="anonymous", host sends Access-Control-Allow-Origin: *Loads if hash matchesThe normal public CDN case; no cookies are sent.
crossorigin="anonymous", host sends no CORS headerBlockedCommon with self-managed buckets and older vendor hosts. Fix the host, or self-host the file.
crossorigin="use-credentials"Loads only if host allows your exact origin with credentialsRarely needed for scripts; a wildcard origin is not accepted with credentials.
Same-origin file with integrityLoads if hash matchesNo CORS headers needed; still useful when files come from a separate deployment or storage layer.

Two further rules from the specification matter in production. Intermediaries that rewrite responses (minifying proxies, some CDN optimisation features, injected analytics) will break the hash, so the host should send Cache-Control: no-transform and you should disable automatic optimisation for hashed paths. And integrity metadata served on a plain HTTP page protects nothing against a network attacker, who can simply strip the attribute; SRI belongs only on HTTPS pages. See the CORS Misconfiguration Guide for setting CORS headers safely on your own hosts.

What SRI can and cannot protect

SRI works by pinning exact bytes, so it suits resources whose content you decide, and fails for resources whose content the vendor decides. Classify every external resource before you start hashing.

Resource typeSRI fitBetter control if SRI does not fit
Versioned open source library on a public CDN (for example [email protected]/dist/x.min.js)StrongSRI plus exact version pin; or self-host from your build.
Same library loaded as @latest or an unversioned pathNone (hash breaks on every release)Pin the version first, then hash.
Web fonts and CSS frameworks from a CDNStrong for <link rel="stylesheet">; font files fetched by CSS are not coveredSelf-host fonts if their integrity matters.
Vendor SDK that the vendor updates in place (analytics, chat, A/B testing)Poor: breaks without warningAsk for versioned URLs with published hashes; otherwise isolate, restrict with CSP and monitor.
Bundles generated per browser or per requestNoneSelf-host a fixed build or drop the dependency.
Tag manager container and the scripts it injectsLoader only, at best; injected tags are uncontrolledTag governance and script monitoring. See the Third-Party JavaScript Management Guide.
Payment fields from a payment service providerUsually not applicablePSP-hosted iframe or redirect, which moves the field out of your page.
Scripts created at runtime by your own codePossible: set script.integrity and script.crossOrigin before insertingGenerate the hash at build time and ship it with the loader.

The polyfill.io case in June 2024 shows the limit clearly. According to Sansec, after the domain changed owner, malicious code was served to more than 100,000 sites. That service generated a different bundle depending on the visiting browser, so there was no single file to hash: the only effective defences were removing the dependency or self-hosting a fixed build.

Generating and maintaining hashes in the build

Hand-pasting hashes from a website works for a demo and fails at scale. Treat integrity values as build artefacts derived from the same lockfile that pins your dependency versions.

  • Compute from the file you will serve: openssl dgst -sha384 -binary file.js | openssl base64 -A gives the digest; prefix it with sha384-. Hash the minified, compressed-as-served bytes after decompression, which is what the browser checks.
  • Bundlers: build plugins such as webpack-subresource-integrity add integrity to the chunks and tags they emit, including lazily loaded chunks. Most frameworks have an equivalent option; turn it on rather than writing your own.
  • External CDN files: download the pinned version once in CI, hash it, and fail the build if the CDN copy ever differs from the hash recorded in the repository. That check also detects a CDN serving tampered content between releases.
  • Algorithm choice: use sha384 by default; sha512 is fine. Do not mix in sha256 for the same file thinking it adds safety: the browser will ignore it in favour of the stronger set.
  • Updates: when a dependency update bot raises a version bump, the same pull request must regenerate the hash. A bump that changes the URL but not the hash breaks the page; a hash regenerated from an unreviewed file simply launders the change. See the Dependency Update Automation Guide.
  • Two-version transition: list two hashes of the same algorithm when you need a staged rollout across caches, then remove the old one.

Enforcing coverage: Integrity-Policy and CSP

SRI on its own is opt-in per tag, so one new tag without an attribute silently reopens the risk. Two browser mechanisms turn it into a policy.

Integrity-Policy headers

The SRI specification now defines Integrity-Policy and Integrity-Policy-Report-Only response headers. Their value is a structured field dictionary with blocked-destinations (allowed values script and style), optional sources (only inline, the default) and optional endpoints naming reporting endpoints declared in Reporting-Endpoints. With the enforcing header, the browser blocks any listed destination requested without integrity metadata, and blocks no-cors requests outright. Violations generate reports of type integrity-violation containing the document URL, blocked URL, destination and whether the policy was report-only, which you can also observe in page with a ReportingObserver.

A practical pair of headers for a payment page:

  • Reporting-Endpoints: integrity="https://reports.example.com/integrity"
  • Integrity-Policy-Report-Only: blocked-destinations=(script style), endpoints=(integrity)

Browser support for these headers is newer and uneven; check current compatibility data before relying on blocking, and keep CSP as the baseline control.

Content Security Policy

CSP Level 3 lets a script-src hash source match a request's integrity metadata, so an external script whose integrity hash appears in the policy can be allowed without allowlisting its host. In practice most teams combine a nonce or hash based script-src for first-party code with SRI on the remaining static third-party files. OWASP ASVS 5.0 requirement V3.4.3 sets the CSP baseline (object-src 'none', base-uri 'none', and an allowlist, nonces or hashes). See the Content Security Policy Guide.

Choosing between SRI, self-hosting and isolation

OptionProtects againstCost and trade-offsChoose when
SRI on CDN-hosted fileTampering at the CDN or origin hostHash maintenance; CORS dependency; breaks if host changes the fileStatic, versioned public libraries where CDN delivery matters
Self-host from your buildThird-party host compromise entirelyYou own patching and caching; your own pipeline becomes the trust pointMost libraries; any file you would otherwise hash
Self-host plus SRITampering in your own storage or CDN layerLow extra cost once the build emits hashesPayment pages and high-value pages served from separate asset storage
Sandboxed iframe on another originThird-party code reading or changing your pageLayout and messaging work (postMessage)Widgets and vendor code that must stay dynamic
Script monitoring or tamper detectionDetects changes after they happenDoes not prevent the first executionDynamic vendor scripts that cannot be hashed; PCI DSS 11.6.1

Small versus large organisations: a small site gets most of the benefit by self-hosting libraries, turning on the bundler SRI option and adding a report-only integrity policy. A large estate with many teams and vendors needs a central script inventory, CI checks that fail builds missing integrity, collected integrity and CSP reports, and an exception register for every unhashed script with an owner and justification.

Implementation plan

  1. Inventory: crawl the pages in scope (start with login, checkout and account pages) and list every external script and stylesheet with host, URL, version and owner. Browser developer tools and CSP report-only data both help.
  2. Classify: sort each item into the categories in the table above: hashable, needs pinning first, self-host, isolate, or monitor only.
  3. Pin and fix CORS: replace floating URLs with exact versions and confirm each host returns Access-Control-Allow-Origin. Move files from hosts that cannot do CORS to your own origin.
  4. Add hashes in the build: enable the bundler integrity option, add a CI step that recomputes external hashes and fails on drift, and add crossorigin="anonymous" to every hashed cross-origin tag.
  5. Test in a pilot: deploy to a staging environment and one low-risk page first; watch the browser console and error tracking for integrity failures. Test a deliberately wrong hash to confirm the page fails safely.
  6. Report-only policy: ship Integrity-Policy-Report-Only for scripts and styles and collect reports until unexpected entries stop.
  7. Enforce: switch to Integrity-Policy on pages where every remaining script is hashed or isolated. Rollback is a header change: revert to report-only if a release breaks a page, rather than removing hashes.
  8. Maintain: require hash regeneration in dependency update pull requests and review the exception register quarterly.

Detection and measurement

  • Integrity violation reports: collect integrity-violation reports and CSP violation reports centrally; a new blocked URL on a payment page is a security event until proven otherwise.
  • Client-side load errors: forward script error events with the failing URL to your error tracking so a real integrity failure is not dismissed as a flaky CDN.
  • CI drift checks: alert when a pinned CDN file no longer matches its recorded hash; that indicates either an upstream change or tampering.
  • Change review: log every change to integrity values in source control with the reviewer, so an assessor can see who approved each script version.

Metrics that show SRI is working:

  • Percentage of external scripts and stylesheets on in-scope pages that are hashed, self-hosted or isolated (target 100 percent on payment pages).
  • Number of open exceptions (unhashed scripts) with an owner and justification, and their age.
  • Integrity violations per week after tuning, and median time to triage each one.
  • Percentage of dependency update pull requests that regenerated hashes in the same change.
  • Pages with an enforcing Integrity-Policy or nonce-based CSP, out of pages in scope.

PCI DSS and framework mapping

PCI DSS v4.0.1 requirement 6.4.3 requires that every payment page script executed in the consumer's browser is authorised, has its integrity assured and is listed in an inventory with a written justification; requirement 11.6.1 requires a change and tamper detection mechanism for security-impacting HTTP headers and script contents of payment pages as received by the browser. Both became mandatory on 31 March 2025. In January 2025 the PCI Security Standards Council removed 6.4.3 and 11.6.1 from SAQ A, replacing them with an eligibility criterion that the merchant confirms its site is not susceptible to attacks from scripts that could affect its e-commerce systems; the Council stressed this does not weaken the underlying requirements. See the PCI DSS for E-commerce Payment Page Scripts Guide.

FrameworkReferenceHow SRI contributes
PCI DSS v4.0.16.4.3Integrity element for static scripts; hash list in source control supports authorisation evidence
PCI DSS v4.0.111.6.1Integrity policy reports and CI drift checks feed tamper detection; not sufficient alone for dynamic scripts or headers
OWASP ASVS 5.0V3.6.1 (Level 3)External assets only if static, versioned and protected by SRI, otherwise a documented decision per resource
NIST SP 800-53 Rev. 5SI-7, SI-7(15), SR-11, SA-9Integrity verification and code authentication of externally provided components
NIST CSF 2.0ID.AM-02, PR.PS-01, GV.SC-07Script inventory, configuration management of page content, supplier risk
MITRE ATT&CKT1195.002 Compromise Software Supply Chain; T1189 Drive-by CompromiseBlocks tampered third-party code from executing in visitors' browsers

Common failure patterns

  • Missing crossorigin: teams add the hash, the script fails in every browser, and the attribute is removed under pressure. Add both together and test before release.
  • Hashing a floating URL: a hash on @latest breaks at the next upstream release, which teaches developers to distrust SRI. The Lottie Player npm compromise reached websites precisely because many loaded the player from public CDNs using the latest tag, so malicious versions published with a stolen npm token were served without any change on those sites.
  • Trusting your own asset storage: SRI is often applied only to public CDNs. In the Twilio TaskRouter SDK compromise, a vendor SDK served from a world-writable S3 bucket was modified for about nine hours; customers loading a pinned, hashed copy would have blocked it.
  • Fallback that bypasses the check: an onerror handler that loads the same file from another host without integrity converts a blocked attack into a successful one.
  • CDN optimisation rewriting files: automatic minification or script injection features change the bytes and break hashes; disable them for hashed paths and send no-transform.
  • Assuming SRI covers tag managers: hashing the container loader does nothing for the tags it injects later.

Where identity fits

The files SRI protects are published by someone holding a credential: an npm publishing token, a CDN or bucket write key, a CI deploy role. SRI limits the blast radius when those credentials are stolen, but the root fix is scoping and shortening them. Treat CDN and package publishing credentials as privileged non-human identities. See the npm Tokens Security Guide and the CDN Security Guide.

Practitioner checklist

  • Inventory every external script and stylesheet on login, checkout and account pages, with owner and justification.
  • Pin every third-party file to an exact version before hashing it; remove @latest and unversioned URLs.
  • Use sha384 integrity values with crossorigin="anonymous" and confirm each host returns CORS headers.
  • Generate hashes in the build and fail CI when an external file drifts from its recorded hash.
  • Self-host files where you can; isolate dynamic vendor code in sandboxed iframes.
  • Deploy Integrity-Policy-Report-Only with a reporting endpoint, then enforce on pages with full coverage.
  • Never write error fallbacks that load unhashed copies.
  • Require hash regeneration and review in every dependency update pull request.
  • Keep SRI evidence (hash history, reports, exceptions) for PCI DSS 6.4.3 and 11.6.1 assessments.

Standards and references

Related NHI Mgmt Group resources: Client-Side Security Guide · OWASP Top 10 A08 Guide · Content Security Policy Guide · PCI DSS for E-commerce Payment Page Scripts Guide · Software Supply Chain Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.