Security Headers
Learn how to configure security headers to protect your application from common web vulnerabilities.
Overview
Security headers are HTTP response headers that help protect your application from various attacks. Next.js makes it easy to configure these headers using the next.config.js file.
Configuration
Configure security headers in your Next.js application:
// next.config.jsconst { headers } = require("next/headers");/** @type {import('next').NextConfig} */const nextConfig = {async headers() {return [{source: "/:path*",headers: [{key: "X-DNS-Prefetch-Control",value: "on",},{key: "Strict-Transport-Security",value: "max-age=31536000; includeSubDomains",},{key: "X-XSS-Protection",value: "1; mode=block",},{key: "X-Frame-Options",value: "SAMEORIGIN",},{key: "X-Content-Type-Options",value: "nosniff",},{key: "Referrer-Policy",value: "strict-origin-when-cross-origin",},{key: "Permissions-Policy",value: "camera=(), microphone=(), geolocation=()",},],},];},};module.exports = nextConfig;
Content Security Policy
Configure CSP to prevent XSS attacks and other injections:
// next.config.jsconst ContentSecurityPolicy = `default-src 'self';script-src 'self' 'unsafe-eval' 'unsafe-inline' *.stripe.com;child-src *.stripe.com;style-src 'self' 'unsafe-inline' *.googleapis.com;img-src * blob: data:;font-src 'self' *.gstatic.com;frame-src *.stripe.com;connect-src *;`.replace(/\n/g, '');const securityHeaders = [// ... other headers{key: 'Content-Security-Policy',value: ContentSecurityPolicy,},];
Important Headers Explained
Strict-Transport-Security (HSTS)
Forces browsers to use HTTPS for the specified duration. Includes subdomains for complete protection.
X-Frame-Options
Prevents clickjacking attacks by controlling how your site can be embedded in iframes.
X-Content-Type-Options
Prevents MIME type sniffing and forces browsers to use the declared content type.
Permissions-Policy
Controls which browser features and APIs can be used in your application.
Testing Headers
Verify your security headers are working correctly:
- Use SecurityHeaders.com to scan your site
- Check browser developer tools Network tab
- Use curl to inspect response headers
- Run automated security scans
Best Practices
- Regularly review and update security headers
- Test headers in development before deploying
- Monitor for any CSP violations
- Keep CSP as strict as possible
- Use report-only mode when testing new policies