Why It Matters for AI-Coded Apps
CSP is the strongest browser-side defense against XSS. Yet 89% of AI-generated applications in our research shipped without any CSP header. When an XSS vulnerability exists, CSP can prevent the injected script from executing, turning a critical vulnerability into a blocked attempt.
Real-World Example
Adding the header Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; tells the browser to only execute scripts from your own domain, blocking any injected script tags from third-party sources or inline code.
How to Detect and Prevent It
Start with a strict CSP: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'self'; form-action 'self'. Use nonces for inline scripts that must exist. Deploy in report-only mode first to identify breakage before enforcing.
Frequently Asked Questions
What does 'unsafe-inline' mean in CSP?
script-src 'nonce-randomvalue') instead.How do I implement CSP with Next.js?
next.config.js using the headers() function, or in middleware. Use next/script with a nonce for inline scripts. Generate a fresh nonce per request in middleware and pass it via headers.What is CSP report-only mode?
Content-Security-Policy-Report-Only header applies the same rules but only reports violations without blocking them. Use this to test your CSP policy in production before enforcing it. Set a report-uri or report-to directive to collect violation reports.