XSS (Cross-Site Scripting)
XSS (Cross-Site Scripting) is an attack where malicious JavaScript is injected into a page and executed in other users' browsers. The primary header defense is Content Security Policy (CSP), which prevents unauthorized scripts from running even if injected.
How XSS works
An attacker finds a way to inject a script into your page — through a user comment, URL parameter, or compromised third-party dependency. When another user visits the page, the injected script runs in their browser with access to cookies, localStorage, and the ability to make authenticated requests.
The three types
| Type | How it works | Example |
|---|---|---|
| Reflected | Script in URL parameter reflected back in response | ?search=<script>alert(1)</script> |
| Stored (persistent) | Script saved to database, served to all visitors | Comment with embedded script tag |
| DOM-based | Script injected via client-side JavaScript | URL hash read into innerHTML |
Defense — Content Security Policy
CSP blocks unauthorized script execution even when injection succeeds. A strict CSP:
Content-Security-Policy: script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self';
With this policy, any injected <script> tag is blocked unless it has the correct nonce — which attackers cannot predict.
Other header defenses
- X-Content-Type-Options: nosniff — prevents MIME-type confusion that can enable XSS
- Referrer-Policy — limits what attackers can learn from referrer headers
- Cookie: HttpOnly — prevents injected scripts from stealing session cookies
What CSP does NOT protect against
CSP is not a substitute for output encoding. An attacker can still inject HTML attributes or URL-based attacks without <script> tags. Always encode output server-side in addition to setting CSP.