A Content Security Policy (CSP) is an HTTP header that tells the browser which sources of scripts, styles, images, and other resources it is allowed to load and run. By allowing only trusted origins and blocking inline script by default, a good CSP sharply reduces the damage a cross-site scripting bug can do, because injected script simply will not execute.
What it controls
A CSP is a set of directives, for example script-src to say where scripts may come from, and frame-ancestors to say who may frame your page. The browser enforces them, refusing to load or run anything outside the allowed sources, which turns a class of injection attacks into a non-event.
Why it is hard to add later
A strict CSP can break existing inline scripts and third-party widgets, so it is far easier to design in from the start than to retrofit. Many teams start in report-only mode, which logs violations without blocking, then tighten the policy once they see what breaks.
What this means for AI-generated code
AI-generated apps almost always ship with no CSP, since the app runs fine without one. That means an XSS bug, which these tools also introduce, has nothing standing in its way once it lands.
Common questions
What does a basic Next.js CSP look like?
A starting point for Next.js: Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{NONCE}'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com. Next.js 14+ has built-in nonce support for server components. The nonce approach avoids unsafe-inline for scripts while still allowing Next.js's own script injection.
What is the difference between CSP and the X-Content-Type-Options header?
CSP controls where resources can come from and which scripts can run — a broad defense against XSS and data injection. X-Content-Type-Options: nosniff tells the browser not to guess the content type of a response, preventing MIME-type confusion attacks where a browser might execute an uploaded image file as JavaScript. They solve different problems and you should set both.
Does a CSP prevent all XSS?
A strict CSP makes XSS very hard to exploit but does not prevent the underlying bug. If your CSP allows unsafe-inline (often required to get things working quickly) or if the attacker can find a trusted script source to abuse, a CSP can be bypassed. A strong CSP is a second layer that limits damage; fixing the XSS vulnerability itself is still required.