Security Recommended
Lock scripts to a known hash
Put an integrity hash, a fingerprint of the file, on every script and stylesheet. Let the browser refuse any script without one.
How to do it
Add integrity="sha384-…" to script and stylesheet tags at build time, from the final bytes. Files from another origin also need crossorigin="anonymous" and a CORS header. Send Integrity-Policy: blocked-destinations=(script), which current browsers enforce. Try Integrity-Policy-Report-Only first.
Example
<script type="module" src="/app.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>
# Make the hash at build time
openssl dgst -sha384 -binary app.js | openssl base64 -A
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
const integrity = 'sha384-' + createHash('sha384').update(readFileSync('dist/app.js')).digest('base64');
import base64, hashlib, pathlib
integrity = "sha384-" + base64.b64encode(hashlib.sha384(pathlib.Path("dist/app.js").read_bytes()).digest()).decode()
How to check
A build test finds integrity on every <script src> and <link rel="stylesheet">. Change one byte of the bundle on a test server, and the browser refuses it.
For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers website playbook: https://agentwranglers.se/playbook/website/security/subresource-integrity.