Strict CSP and Modern Best Practices
What you'll learn: How to build a Content Security Policy that uses strict-dynamic and nonces instead of host allowlists for stronger, more maintainable XSS protection.
Why Host-Based Allowlists Fail
Traditional CSP policies rely on host-based allowlists like script-src https://trusted.com. This approach has major weaknesses: attackers can exploit JSONP endpoints, CDN compromises, or open redirects on trusted domains. You're essentially trusting entire hosts, not individual scripts—and that's a huge attack surface.
Enter Strict CSP
Strict CSP flips the model. Instead of listing trusted hosts, you use:
- Nonces: Random tokens generated per page load, embedded in your CSP header and script tags
strict-dynamic: A directive that trusts scripts loaded by nonce-validated scripts, allowing your legitimate code to dynamically load dependencies
How It Works
Your CSP header looks like:
Content-Security-Policy: script-src 'nonce-r4nd0m123' 'strict-dynamic';
Every inline or external script you control gets the nonce:
<script nonce="r4nd0m123">/* your code */</script>
The magic: strict-dynamic tells the browser "any script loaded by a nonce-validated script is also trusted." This lets your legitimate code use document.createElement('script') while blocking attacker-injected scripts that lack the nonce.
Modern Best Practices
- Always generate fresh nonces per response (never reuse)
- Avoid
unsafe-inlineandunsafe-eval—strict CSP makes them unnecessary - Use CSP Level 3 features where supported
- Remove host allowlists entirely—they're legacy and weaker
Key Takeaway: Strict CSP with nonce-based validation and strict-dynamic replaces fragile host allowlists with cryptographic proof of script legitimacy, dramatically reducing XSS risk while simplifying policy maintenance.