Capítulo 403 de 456

headers

Core Idea

Sets custom HTTP response headers on incoming requests for given path patterns, via the headers key in next.config.js (Pages Router). Checked before the filesystem (pages and /public).

Key Concepts

  • source: incoming request path pattern (path-to-regexp syntax) that must match.
  • headers: array of { key, value } response header objects to apply.
  • basePath: false to exclude basePath prefixing from matching (external rewrites only).
  • locale: false to exclude automatic locale prefixing.
  • has / missing: arrays of { type, key, value } conditions (header, cookie, host, query) that must (has) or must not (missing) match for the header to apply.
  • Header overriding: if two entries match the same path and set the same key, the later one wins.
  • Path matching: :slug matches one segment; * (zero+), + (one+), ? (zero/one) modifiers; :slug* matches nested paths; regex via :slug(\d{1,}); special chars (){}:*+? must be escaped with \\ when literal.
  • Cache-Control: immutable hashed assets (e.g. static image imports) get public, max-age=31536000, immutable automatically and cannot be overridden; other responses can set Cache-Control via res.setHeader in API Routes or inside getServerSideProps.

Code Examples

module.exports = {
  headers() {
    return [
      {
        source: '/blog/:slug',
        has: [{ type: 'query', key: 'page', value: 'home' }],
        headers: [{ key: 'x-slug', value: ':slug' }],
      },
    ]
  },
}
  • O que demonstra: matching de path parametrizado combinado com condição has de query string, reutilizando o parâmetro capturado no valor do header.
res.setHeader('Cache-Control', 's-maxage=86400')
  • O que demonstra: setar Cache-Control manualmente numa API Route.

Reference Tables

Header comumUso
X-DNS-Prefetch-Controlliga prefetch de DNS
Strict-Transport-Securityforça HTTPS (max-age=63072000; includeSubDomains; preload)
X-Frame-Optionsprevine clickjacking (superado por CSP frame-ancestors)
Permissions-Policycontrola APIs/features do browser
X-Content-Type-Optionsnosniff, evita MIME sniffing
Referrer-Policycontrola info de referrer enviada
VersionChanges
v13.3.0missing added
v10.2.0has added
v9.5.0Headers added

Anti-patterns

  • Tentar sobrescrever Cache-Control de assets imutáveis: não é possível, hash no filename já garante cache seguro.

Key Takeaways

  1. headers roda antes do filesystem, então pode sobrepor arquivos estáticos.
  2. Path matching não cobre nested paths por padrão, use * para isso.
  3. has/missing permitem headers condicionais por header/cookie/query/host recebido.
  4. Com basePath ou i18n configurados, source é prefixado automaticamente a menos que basePath: false ou locale: false.

Connects To

  • redirects / rewrites: mesma sintaxe de source, has/missing, path matching.
  • Content Security Policy guide: para configurar CSP corretamente em vez de X-Frame-Options.