Set a Content Security Policy with nonces
Generate a fresh random nonce per response and put it in the Content-Security-Policy header and on each script tag, so only your scripts run.
A CSP that allows 'unsafe-inline' does nothing against injected scripts. A nonce lets you keep inline scripts and still block the ones an attacker adds, as long as the value changes on every response.
import { randomBytes } from 'node:crypto';
function cspFor() {
const nonce = randomBytes(16).toString('base64');
const header = `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`;
return { nonce, header };
}
const { nonce, header } = cspFor();
console.log(header.length > 60);
console.log(`<script nonce="${nonce}">init()</script>`.startsWith('<script nonce="'));true
trueSend header as the Content-Security-Policy response header and print the same nonce in each trusted <script nonce="..."> tag. The browser runs a script only when its nonce matches the header, and an injected <script> has no way to know a value that did not exist until this response. randomBytes comes from the operating system's CSPRNG, which is what the MDN CSP guide asks for.
A cached page keeps its old nonce, so a nonce cannot be used on pages served from a CDN cache or static files. Use hashes there instead.