typescriptadvanced
Content Security Policy Headers
Configure strict CSP and security headers in Next.js for production-grade security.
typescriptPress ⌘/Ctrl + Shift + C to copy
// next.config.ts
import type { NextConfig } from 'next';
const cspHeader = `
default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com https://pagead2.googlesyndication.com;
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data: https:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://www.google-analytics.com https://vitals.vercel-insights.com;
frame-src 'self' https://googleads.g.doubleclick.net;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`.replace(/\n/g, '');
const nextConfig: NextConfig = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Content-Security-Policy',
value: cspHeader,
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'X-Frame-Options',
value: 'DENY',
},
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin',
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()',
},
],
},
];
},
};
export default nextConfig;Use Cases
- production security
- XSS prevention
- compliance
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Next.js Middleware for Authentication
Protect routes with Next.js middleware using token verification and role-based redirects.
Best for: Protecting authenticated routes at the edge
#nextjs#middleware
typescriptintermediate
API Route Rate Limiting
Add rate limiting to Next.js API routes with sliding window, IP-based limits, and custom responses.
Best for: API abuse prevention
#nextjs#api
typescriptbeginner
Server-Only Utility Functions
Ensure utility functions only run on the server using the server-only package to prevent client leakage.
Best for: protecting secrets
#nextjs#server-only
typescriptintermediate
Cookies and Headers in Server Components
Read and set cookies and headers in Next.js server components and route handlers.
Best for: theme preferences
#nextjs#cookies