# SRI

> The SRI (Subresource Integrity) is a security feature that verifies fetched resources have not been modified.

## What is Subresource Integrity and how do I add an integrity hash?

The feature that checks scripts and styles against a cryptographic hash in the `integrity` attribute, usually for files from a CDN. If the content does not match, the browser refuses to use it.

- Topic: Security
- Type: technique

## Example

Wrong:

```html
<script
  src="https://cdn.example.com/lib@1.2.0/lib.min.js"
></script>
```

Right:

```html
<script
  src="https://cdn.example.com/lib@1.2.0/lib.min.js"
  integrity="sha384-BASE64_HASH_OF_FILE"
  crossorigin="anonymous"
></script>
```

The browser hashes the file and refuses to run it if it differs, so a compromised CDN cannot inject code.

## Common mistakes

- Using SRI on a URL whose content changes, so the resource suddenly stops loading.

## Key points

- Scripts and styles from a CDN have an `integrity` attribute with a 'sha384' or stronger hash.
- Cross-origin resources with `integrity` also have `crossorigin='anonymous'`.
- The hash is generated from the exact file and updated when the version changes.

## Interview questions

### How do I generate an SRI hash?

Run `openssl dgst -sha384 -binary lib.js | openssl base64 -A` and prefix the result with 'sha384-'.

### Can I use SRI with `fetch()`?

Yes. Pass an `integrity` option to `fetch()`, and the promise rejects if the response does not match the hash.

### Why does SRI fail with a CORS error?

Cross-origin files must be fetched with CORS for the browser to check them, so add `crossorigin='anonymous'` and make sure the CDN sends `Access-Control-Allow-Origin`.

## Related cards

- [CSP](https://wonderium.dev/web/csp.md)
- [CDN](https://wonderium.dev/web/cdn.md)
- [`<script>`](https://wonderium.dev/html/script.md)
- [`<link>`](https://wonderium.dev/html/link.md)
- [Hashing](https://wonderium.dev/engineering/hashing.md)

---

- Level: [Web Platform](https://wonderium.dev/web.md)
- HTML version: https://wonderium.dev/web/sri
- Last updated: 2026-11-25
