Content Security Policy (CSP)
Define CSP headers to prevent XSS, data injection, and mixed content.
EdgeAdvanced
Why
CSP is the most effective defense against XSS — it restricts which resources can load and execute. Cloudflare's edge network spans 330+ cities with sub-50ms p95 latency globally.
Edge functions reduce TTFB by 60-80% compared to origin servers, and Akamai reports 40% of enterprises now use edge compute in 2024.
When
All production sites handling user input or displaying third-party content. Avoid edge functions for stateful logic requiring database writes — edge runtimes have no persistent connection pool.
Skip if you need long-running tasks (>30s) or heavy CPU computation.
How
# Next.js CSP via headers
async headers() {
return [{
source: '/(.*)',
headers: [{
key: 'Content-Security-Policy',
value: [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"img-src 'self' data: https: blob:",
"font-src 'self' https://fonts.gstatic.com",
"connect-src 'self' https://api.example.com wss://ws.example.com",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
"upgrade-insecure-requests",
].join('; ')
}]
}];
}
4. Verify deployment — curl -I https://your-app.example.com
5. Monitor logs — check for errors in first 5 minutes
6. Rollback if needed — revert to previous version
Example
# Nonce-based CSP (Next.js 14)
import { headers } from 'next/headers';
export default function Layout({ children }) {
const nonce = headers().get('x-nonce') || '';
const csp = [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}'`,
"style-src 'self' 'unsafe-inline'",
].join('; ');
return (
<html>
<head>
<meta httpEquiv="Content-Security-Policy" content={csp} />
</head>
<body>{children}</body>
</html>
);
}
Common Problems
- ⚠Inline scripts blocked — use nonces or hashes
- ⚠Third-party scripts failing — add specific domains to script-src
- ⚠Configuration drift between environments — use infrastructure-as-code (Terraform/Pulumi) to keep dev/staging/prod identical
Best Practices
- ✓Start with report-only — collect violations before enforcing
- ✓Use nonces for inline scripts — more secure than unsafe-inline
- ✓Set up health checks and graceful shutdown — handle SIGTERM to drain in-flight requests before exit