7 min read

Security headers for Next.js — CSP, HSTS, and the full list

A complete reference for the security headers your Next.js app should ship with. Configured via next.config.mjs in minutes.

Security headers are free, high-leverage, and mostly forgotten. This guide walks through the eight headers every Next.js app should set and why.

What it is

Security headers are HTTP response headers that instruct browsers to enforce specific security behaviors — block mixed content, refuse framing, enforce HTTPS, restrict script sources.

Vulnerable example

// Vulnerable: default Next.js config, no security headers.
const nextConfig = { reactStrictMode: true };
export default nextConfig;

Fixed example

// Fixed: eight hardening headers via next.config.mjs
const headers = [
  { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
  { key: "X-Content-Type-Options", value: "nosniff" },
  { key: "X-Frame-Options", value: "SAMEORIGIN" },
  { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
  { key: "Permissions-Policy", value: "accelerometer=(), camera=(), geolocation=(), microphone=()" },
  { key: "Cross-Origin-Opener-Policy", value: "same-origin" },
  { key: "X-DNS-Prefetch-Control", value: "on" },
  // CSP is best set via middleware with nonces — see /guides/content-security-policy
];

export default {
  async headers() {
    return [{ source: "/:path*", headers }];
  },
};

How Securie catches it

Securie scans your deployed app for each of the eight recommended headers and flags missing or weak values with the exact config line to paste into next.config.mjs.

Checklist

  • Strict-Transport-Security: long max-age with includeSubDomains + preload
  • Content-Security-Policy: set and tested (nonce-based preferred)
  • X-Frame-Options: SAMEORIGIN or DENY
  • X-Content-Type-Options: nosniff
  • Referrer-Policy: strict-origin-when-cross-origin
  • Permissions-Policy: deny everything you do not use
  • Cross-Origin-Opener-Policy: same-origin
  • HSTS preload-list submission (hstspreload.org) after verifying

FAQ

Does CSP break Next.js?

A strict CSP without 'unsafe-inline' requires nonces. Next.js supports nonce'd scripts via middleware — yes it takes some wiring but it works.