Using Nonces to Prevent XSS with CSP
Content Security Policy nonces are one of the cleanest ways to shut down a huge class of XSS bugs without rewriting every frontend template you own. If you’ve ever inherited a server-rendered app with inline scripts sprinkled everywhere, nonces are usually the fastest path to meaningful protection. They let you keep specific inline <script> and <style> blocks while blocking attacker-injected ones. The short version: The server generates a fresh random nonce for every HTTP response That nonce goes into the CSP header The same nonce is added to trusted inline <script> or <style> tags The browser executes only the tags with the matching nonce If an attacker injects <script>alert(1)</script>, it won’t have the right nonce, so the browser refuses to run it. ...