Capítulo 216 de 456

headers (next.config.js)

Core Idea

The headers key in next.config.js lets you set custom HTTP response headers per path pattern, with support for regex/wildcard matching and conditional application based on request headers, cookies, query, or host.

Key Concepts

  • headers(): sync or async function returning an array of { source, headers, basePath?, locale?, has?, missing? } objects.
  • source: incoming request path pattern (path-to-regexp syntax: :param, *, +, ? modifiers, (regex) groups).
  • headers array: list of { key, value } response header pairs; matched params usable in both.
  • has / missing: arrays of { type: 'header'|'cookie'|'host'|'query', key, value? } conditions; both source and all has must match, and all missing must not match.
  • basePath: false: opts a header rule out of automatic basePath prefixing (for external rewrites only).
  • locale: false: opts out of automatic i18n locale prefixing; source must include a locale manually if used.
  • Header order: checked before the filesystem (pages, /public); last matching header key wins on conflicts.
  • Cache-Control immutability: truly immutable assets (e.g. static image imports with SHA hash) get public, max-age=31536000, immutable and cannot be overridden via this config.

Code Examples

module.exports = {
  headers() {
    return [
      {
        source: '/blog/:slug*',
        headers: [
          { key: 'x-slug', value: ':slug*' },
        ],
      },
    ]
  },
}
  • O que demonstra: wildcard path matching (:slug*) reutilizando o parâmetro capturado no valor do header.
module.exports = {
  headers() {
    return [
      {
        source: '/:path*',
        has: [{ type: 'header', key: 'x-add-header' }],
        headers: [{ key: 'x-another-header', value: 'hello' }],
      },
    ]
  },
}
  • O que demonstra: aplicar um header condicionalmente com has.

Reference Tables

Header comumEfeito
Access-Control-Allow-OriginCORS: origem permitida a acessar route handlers
X-DNS-Prefetch-Controlliga prefetch de DNS pra links/recursos externos
Strict-Transport-Securityforça HTTPS por max-age; includeSubDomains; preload
X-Frame-Optionsprevine clickjacking (superado por CSP frame-ancestors)
Permissions-Policycontrola quais APIs do browser podem ser usadas
X-Content-Type-Optionsnosniff, previne MIME-sniffing/XSS
Referrer-Policycontrola quanta info de referrer é enviada entre origens
VersionChanges
v13.3.0missing adicionado.
v10.2.0has adicionado.
v9.5.0Headers adicionado.

Anti-patterns

  • Não escapar caracteres especiais em source: (, ), {, }, :, *, +, ? usados como valores literais precisam de \\ antes.
  • Tentar sobrescrever Cache-Control de assets imutáveis: não é possível via config, esses assets já têm SHA no filename.
  • Confundir X-Frame-Options com CSP: prefira frame-ancestors do CSP, que tem melhor suporte moderno.

Key Takeaways

  1. /blog/:slug casa só um nível (/blog/first-post), não caminhos aninhados; use :slug* pra wildcard.
  2. Regras conflitantes na mesma rota: a última regra que define a mesma chave de header vence.
  3. Com basePath ou i18n configurados, source é prefixado automaticamente a menos que basePath: false/locale: false seja setado.
  4. has/missing com grupo de captura nomeado ((?<paramName>...)) tornam o valor capturado disponível no destino via :paramName.

Connects To

  • Content Security Policy guide: referência detalhada pra configurar CSP corretamente.
  • basePath: afeta como source é prefixado nas regras de header.
  • redirects/rewrites (next.config.js): configs irmãs que usam a mesma sintaxe de path matching.