A Developer's Guide to Secure Headers in Next.js
Learn how to properly configure HTTP security headers in a Next.js application to protect against XSS, clickjacking, and more.
Why Security Headers Matter
HTTP security headers are a fundamental layer of defense. They instruct the browser on how to behave securely, effectively neutralizing entire classes of attacks like Cross-Site Scripting (XSS) and Clickjacking.
Configuring Headers in Next.js
Next.js makes it incredibly easy to configure security headers globally using the next.config.js file.
Here is a secure baseline configuration:
// next.config.js const securityHeaders = [ { key: 'X-DNS-Prefetch-Control', value: 'on' }, { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' }, { key: 'X-Frame-Options', value: 'SAMEORIGIN' }, { key: 'X-Content-Type-Options', value: 'nosniff' }, { key: 'Referrer-Policy', value: 'origin-when-cross-origin' } ] module.exports = { async headers() { return [ { source: '/(.*)', headers: securityHeaders, }, ] }, }
The Hardest Header: Content Security Policy (CSP)
CSP is the most powerful header, but also the hardest to implement without breaking your site. It restricts where scripts, styles, and images can be loaded from.
For Next.js, implementing a strict CSP requires using nonces for inline scripts (which Next.js generates).
Start by deploying CSP in "Report-Only" mode. This allows you to see what would break without actually blocking anything, allowing you to refine your policy safely.
Find your vulnerabilities before attackers do.
Our automated $149 security audit maps your public attack surface and checks for misconfigurations, outdated components, and missing security headers.
Get Your Security Audit