What is CSP (Content Security Policy)? XSS Protection

Share

TL;DR

Content Security Policy (CSP) is a security header that tells browsers what content can load on your page. It specifies allowed sources for scripts, styles, images, and more. If an attacker injects malicious code, CSP can block it from running. It's your second line of defense against XSS attacks after input sanitization.

The Simple Explanation

CSP is like a bouncer for your webpage. You give the browser a list of approved sources. If something tries to load from an unapproved source, the browser blocks it. This stops attackers from injecting malicious scripts even if they find a vulnerability in your app.

Basic CSP Header

Example CSP header

Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;

Common Directives

  • default-src: Fallback for other directives
  • script-src: Where scripts can load from
  • style-src: Where stylesheets can load from
  • img-src: Where images can load from
  • connect-src: Where fetch/XHR can connect to
  • frame-ancestors: Who can embed your page (prevents clickjacking)

Source Values

  • 'self': Same origin as the page
  • 'none': Block everything
  • 'unsafe-inline': Allow inline scripts/styles (weakens CSP)
  • 'nonce-abc123': Allow specific inline scripts with matching nonce
  • https: Any HTTPS URL
  • specific domains: https://example.com

Avoid 'unsafe-inline' for scripts. It defeats most XSS protection CSP provides. Use nonces or hashes instead for inline scripts you control.

Setting CSP in Next.js

next.config.js

const securityHeaders = { key: 'Content-Security-Policy', value: "default-src 'self'; script-src 'self'" }

module.exports = { async headers() { return { source: '/:path*', headers: securityHeaders } } }

What does CSP protect against?

CSP primarily protects against XSS (Cross-Site Scripting) attacks by controlling which scripts can run on your page. It also prevents clickjacking, data injection, and loading content from untrusted sources. CSP acts as a second line of defense if malicious code gets into your page.

Why does CSP break my inline scripts?

By default, CSP blocks inline scripts because attackers often inject malicious inline code. To allow your inline scripts, you can use nonces (random tokens) or hashes. Using unsafe-inline defeats the purpose of CSP for XSS protection and should be avoided.

How do I start with CSP without breaking my site?

Start with Content-Security-Policy-Report-Only header instead of Content-Security-Policy. This reports violations without blocking content. Monitor the reports to see what would break, then adjust your policy before enforcing it.

Check Your Security Headers

Scan your site for missing or misconfigured security headers.

Start Free Scan
Security Glossary

What is CSP (Content Security Policy)? XSS Protection