Subresource Integrity for scripts served from a CDN

Generate a digest from exact asset bytes and plan for CORS, version changes and failed loads during deployment.

Subresource Integrity lets a browser check that a fetched script or stylesheet matches an expected cryptographic digest before using it. The expected value belongs in the page's integrity attribute. If the downloaded bytes differ, a supporting browser rejects the resource under the applicable rules.

The operational challenge is keeping the page, digest and deployed asset in agreement. A correct hash of a local file is useless if a CDN serves a different build. Treat integrity metadata as part of the asset release, with versioned URLs and a tested failure path.

Hash the exact resource bytes

The SRI generator reads the selected file locally and computes a supported digest. It returns an integrity token containing the algorithm name and Base64-encoded digest. The input file must match the content the browser will evaluate.

Minification, newline conversion, banners and build-time replacements can change the bytes. Generate SRI after the final asset transformation, not from an earlier source file. A filename match is not evidence of content equality.

Ordinary HTTP content encoding, such as transport compression, is handled by the browser as part of fetching. The important comparison is the resource content used for integrity processing, not a separately captured compressed transport file. Verify the actual deployed asset through the browser when in doubt.

<script src="https://cdn.example/app.v3.js"
  integrity="sha384-BASE64_DIGEST_OF_FINAL_ASSET"
  crossorigin="anonymous"></script>

The placeholder is not a valid deployment digest. Replace it with the generator's output for the exact final file. Keep the algorithm prefix attached; a bare hexadecimal file checksum is not the same syntax as an SRI integrity token.

Understand what the digest protects

SRI can detect an unexpected change to a resource when the page still contains the trusted expected digest. If an attacker can modify both the page markup and the asset, they can replace the integrity value too. The page's own delivery and build pipeline remain part of the trust boundary.

A matching digest does not establish that the approved script is harmless. It establishes consistency with the bytes you chose to trust. Review dependencies and updates before pinning them, and keep normal application security controls in place.

Version pinning and SRI complement each other. A versioned URL helps identify the intended release and avoid mutable latest aliases. The digest provides a content check for that release. Neither excuses an unreviewed dependency update.

SRI deployment checks
CheckWhy it mattersEvidence
Final asset bytesBuild transforms can change the digestHash after the last transformation
Versioned URLMutable paths can serve unexpected contentRelease-specific asset name or path
Cross-origin CORS responseIntegrity use has origin requirementsBrowser load through the real CDN
Matching markupOld HTML can reference the wrong digestPage and asset release tested together
Failure behaviourRejected scripts can disable key featuresControlled mismatch test and clear recovery

Configure the cross-origin resource correctly

For cross-origin SRI use, the resource must satisfy the relevant CORS requirements. The common script pattern uses crossorigin=anonymous and a suitable Access-Control-Allow-Origin response from the CDN. An integrity attribute alone does not grant cross-origin access.

Inspect the actual response after redirects. A CDN configuration may supply CORS headers on one path but not an error page or alternate host. A script rejected for CORS can look like an integrity failure in a superficial report, so preserve the browser's exact console message.

If the resource genuinely requires credentials, review that architecture and the corresponding CORS rules carefully. Public static dependencies normally should not depend on a user's session cookie. Keep the loading model simple and test the same markup in the production origin context.

Deploy a changed asset without breaking cached pages

Suppose app.v3.js is replaced in place while cached HTML still contains the old digest. Browsers fetching the new bytes with the old integrity value reject the script. Some users may continue working with a cached old script, creating inconsistent failures across clients.

Publish the new asset under a new versioned URL, compute its digest and update the page reference together. Keep the old asset available for pages still using the old reference during the cache window. This makes both old and new page versions internally consistent.

Deploy assets before pages that reference them. Then test the public page, the fetched asset and its CORS response through the actual CDN. A local build passing does not show that the edge has the new file or that a deployment rewrite preserved its bytes.

For rollback, restore a page reference to an asset that still exists with its matching digest. Do not strip integrity attributes as the default recovery action. Preserve the relationship between trusted markup and exact resource content throughout the rollback.

Keep the digest format and algorithm explicit

SRI metadata uses an algorithm label followed by a hyphen and an encoded digest. Common supported choices include SHA-256, SHA-384 and SHA-512. The generator provides the full token so you do not have to convert a hexadecimal checksum manually.

Multiple integrity tokens have defined processing rules, including algorithm-strength considerations. Do not assume that adding many unrelated hashes means any arbitrary file will be accepted in the way you intend. Follow the current specification and test the exact metadata you deploy.

When comparing a build artifact with a published digest, confirm both algorithm and representation. A 64-character hexadecimal SHA-256 checksum and a Base64 SHA-256 SRI token can describe the same digest bytes while looking entirely different. Compare decoded values only with a clear format contract.

Generate metadata in the build pipeline

Make the build output a manifest mapping each final asset URL to its integrity value. Use that manifest when rendering HTML. This reduces the chance that a developer updates the script path but leaves an old digest copied in a template.

Keep the manifest tied to the release artifact. Recomputing it later from a different workspace can produce a valid digest for the wrong file. If the CDN performs content transformations, either disable those transformations for pinned assets or incorporate the final served form into a controlled process.

Add a meaningful deployment check that loads the actual page and confirms required resources execute or apply. A text test asserting that integrity exists cannot detect a mismatched file. Include one controlled mismatch in a test environment to verify the browser rejects it and the application handles the missing dependency.

Know which resources the markup actually pins

An integrity attribute on one script does not automatically pin every resource that script later loads. Dynamic imports, workers and additional requests have their own loading paths and controls. Inventory the dependency graph instead of assuming a single attribute covers the entire application.

CSP can complement SRI by constraining execution and resource destinations, but the mechanisms have different roles. Review trusted loaders and external dependencies together. A loader authorised by CSP can still introduce new resources unless the architecture controls that behaviour.

For third-party widgets that change without stable versioned assets, determine whether the provider supports a pinning workflow. If it does not, document the limitation and evaluate whether the integration's update model fits your security and availability needs.

Keep error pages out of asset paths

A missing script may receive the site’s HTML fallback with a successful status. The browser then rejects it through integrity or parsing checks, while a basic uptime probe sees 200. Test a missing versioned asset and ensure the server returns an appropriate failure rather than application HTML. Monitoring should distinguish asset availability from homepage availability, particularly during releases that publish many files in sequence.

Frequently asked questions

Does SRI prove a library has no vulnerabilities?

No. It verifies consistency with expected bytes. A vulnerable library can match its digest perfectly. Review versions and dependencies separately, then use SRI to detect unexpected content changes during delivery.

Why does the generated value contain Base64?

The integrity token encodes the digest bytes in the format SRI expects, with an algorithm prefix. It is not an encrypted file or a signature. Use the complete token instead of substituting a visually similar hexadecimal checksum.

Will a newline change break the hash?

It can, because the resource bytes changed. Generate the digest after final minification and text transformations. Keep the deployed file identical to the build artifact whose digest appears in the page.

Why is crossorigin needed in common CDN examples?

Cross-origin integrity use must satisfy the relevant CORS conditions. The attribute selects the request mode and credential behaviour for the resource. The CDN still needs a compatible response; adding the attribute alone cannot authorise a server that does not provide it.

Should I remove integrity when an update fails?

First compare the asset, digest, URL and CORS response. Restore a consistent release or deploy the correct matching metadata. Removing the check conceals the mismatch and changes the trust model instead of repairing the release.

Does one pinned script cover its dynamic dependencies?

Not automatically. Later loads follow their own mechanisms and policies. Review the complete loading graph and use supported controls for those resources. Do not describe a partially pinned application as if every dependency were checked by the initial attribute.

What is the best final verification?

Load the production-like page through its real asset host, confirm required resources work, inspect browser errors and compare the served content with the release manifest. Keep old versioned assets available for cached pages and test rollback with matching URLs and digests.

Sources and further reading

50 useful tools · ↑ ↓ to navigate · Enter to open · Esc to close