Stopping XSS Cold
Even if you sanitize inputs and escape outputs, XSS can still slip through (e.g., via a compromised third-party NPM package or a rogue browser extension). A Content Security Policy (CSP) is an HTTP header that tells the browser exactly which resources are allowed to load.
The White-Listing Approach
A basic CSP looks like this: default-src 'self'; script-src 'self' https://trusted-cdn.com;. This prevents the browser from executing any script that isn't from your domain or the trusted CDN. If an attacker injects <script src='evil.com/miner.js'>, the browser simply refuses to load it.
Strict-Dynamic and Nonces
Maintaining a whitelist is hard in modern apps with hundreds of dependencies. Google advocates for a 'Strict CSP' approach using cryptographic nonces. You generate a random nonce for every request (e.g., nonce-RandomString123) and add it to your valid script tags. The CSP then only allows scripts with a matching nonce to run.
Reporting Violations
You can set up a report-uri directive to receive a JSON packet whenever a policy is violated. This acts as a canary in the coal mine, alerting you to XSS attempts in real-time before they affect your users.