Next.jsEasy
What are headers in next.config.js?
headers() in next.config.ts returns rules that add HTTP response headers to matching paths, such as security headers, caching rules or CORS for static paths. Each rule has a source pattern and a list of { key, value } headers, with optional has/missing conditions.
Common uses
- Security:
Strict-Transport-Security,X-Content-Type-Options: nosniff,Referrer-Policy,Permissions-Policy,X-Frame-Optionsor CSPframe-ancestors. - Caching: long-lived
Cache-Controlfor versioned files inpublic/(fonts, downloads). - CORS for static assets used on other origins.
- Custom headers for monitoring or
X-Robots-Tag: noindexon staging.
Matching rules
- Same patterns as redirects:
/:path*,/fonts/:file, regex,has/missingon headers, cookies, query and host. - If several rules match, all apply; for the same key, the last matching rule wins.
- Headers run first in the routing order, before redirects and Proxy.
Limits
- Values are static. For per-request values like a CSP nonce, set headers in
proxy.ts. - Do not set
Cache-Controlon pages or/_next/statichere; Next.js manages those. Overriding page caching can break revalidation. poweredByHeader: falseremovesX-Powered-By: Next.js.
Content Security Policy
A static CSP with 'unsafe-inline' can live here. A strict nonce-based CSP must be generated per request in Proxy, which also makes pages request-time.
Code example
tsx
1// next.config.ts2import type { NextConfig } from "next";34const securityHeaders = [5 { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },6 { key: "X-Content-Type-Options", value: "nosniff" },7 { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },8 { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },9 { key: "Content-Security-Policy", value: "frame-ancestors 'none'" },10];1112const nextConfig: NextConfig = {13 poweredByHeader: false,14 async headers() {15 return [16 { source: "/:path*", headers: securityHeaders },17 {18 source: "/fonts/:file*",19 headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }],20 },21 {22 source: "/:path*",23 has: [{ type: "host", value: "staging.acme.com" }],24 headers: [{ key: "X-Robots-Tag", value: "noindex" }],25 },26 ];27 },28};2930export default nextConfig;
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.