Capítulo 216 de 456
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.
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./public); last matching header key wins on conflicts.public, max-age=31536000, immutable and cannot be overridden via this config.module.exports = {
headers() {
return [
{
source: '/blog/:slug*',
headers: [
{ key: 'x-slug', value: ':slug*' },
],
},
]
},
}
: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' }],
},
]
},
}
has.| Header comum | Efeito |
|---|---|
Access-Control-Allow-Origin | CORS: origem permitida a acessar route handlers |
X-DNS-Prefetch-Control | liga prefetch de DNS pra links/recursos externos |
Strict-Transport-Security | força HTTPS por max-age; includeSubDomains; preload |
X-Frame-Options | previne clickjacking (superado por CSP frame-ancestors) |
Permissions-Policy | controla quais APIs do browser podem ser usadas |
X-Content-Type-Options | nosniff, previne MIME-sniffing/XSS |
Referrer-Policy | controla quanta info de referrer é enviada entre origens |
| Version | Changes |
|---|---|
| v13.3.0 | missing adicionado. |
| v10.2.0 | has adicionado. |
| v9.5.0 | Headers adicionado. |
source: (, ), {, }, :, *, +, ? usados como valores literais precisam de \\ antes.frame-ancestors do CSP, que tem melhor suporte moderno./blog/:slug casa só um nível (/blog/first-post), não caminhos aninhados; use :slug* pra wildcard.basePath ou i18n configurados, source é prefixado automaticamente a menos que basePath: false/locale: false seja setado.has/missing com grupo de captura nomeado ((?<paramName>...)) tornam o valor capturado disponível no destino via :paramName.source é prefixado nas regras de header.