コンテンツにスキップ

headers

ヘッダーを使用すると、特定のパスへの着信リクエストに対する応答にカスタム HTTP ヘッダーを設定できます。

カスタム HTTP ヘッダーを設定するには、next.config.jsheaders キーを使用できます。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/about',
        headers: [
          {
            key: 'x-custom-header',
            value: 'my custom header value',
          },
          {
            key: 'x-another-custom-header',
            value: 'my other custom header value',
          },
        ],
      },
    ]
  },
}

headers は、sourceheaders プロパティを持つオブジェクトを保持する配列が返されることを期待する非同期関数です。

  • source は着信リクエストのパスパターンです。
  • headers は、keyvalue プロパティを持つ応答ヘッダーオブジェクトの配列です。
  • basePath: false または undefined - false の場合、マッチング時に basePath は含まれません。外部リライトでのみ使用できます。
  • locale: false または undefined - マッチング時にロケールを含めるべきではないかどうか。
  • has は、typekeyvalue プロパティを持つ has オブジェクト の配列です。
  • missing は、typekeyvalue プロパティを持つ missing オブジェクト の配列です。

ヘッダーは、ページと /public ファイルを含むファイルシステムの前にチェックされます。

ヘッダーの上書き動作

2つのヘッダーが同じパスに一致し、同じヘッダーキーを設定する場合、最後のヘッダーキーが最初のヘッダーキーを上書きします。以下のヘッダーを使用すると、パス /hello は、最後に設定されたヘッダー値が world であるため、ヘッダー x-helloworld になります。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'x-hello',
            value: 'there',
          },
        ],
      },
      {
        source: '/hello',
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
    ]
  },
}

パスのマッチング

パスのマッチが許可されています。たとえば、/blog/:slug/blog/hello-world に一致します (ネストされたパスはありません)。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:slug',
        headers: [
          {
            key: 'x-slug',
            value: ':slug', // Matched parameters can be used in the value
          },
          {
            key: 'x-slug-:slug', // Matched parameters can be used in the key
            value: 'my other custom header value',
          },
        ],
      },
    ]
  },
}

ワイルドカードパスのマッチング

ワイルドカードパスをマッチングするには、パラメーターの後に * を使用できます。たとえば、/blog/:slug*/blog/a/b/c/d/hello-world に一致します。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:slug*',
        headers: [
          {
            key: 'x-slug',
            value: ':slug*', // Matched parameters can be used in the value
          },
          {
            key: 'x-slug-:slug*', // Matched parameters can be used in the key
            value: 'my other custom header value',
          },
        ],
      },
    ]
  },
}

正規表現パスのマッチング

正規表現パスをマッチさせるには、パラメータの後に括弧で正規表現を囲みます。例えば、/blog/:slug(\\d{1,})/blog/123 にはマッチしますが、/blog/abc にはマッチしません。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:post(\\d{1,})',
        headers: [
          {
            key: 'x-post',
            value: ':post',
          },
        ],
      },
    ]
  },
}

以下の文字 (, ), {, }, :, *, +, ? は正規表現パスのマッチングに使用されるため、source 内で特殊な値としてではなく使用する場合は、前に \\ を追加してエスケープする必要があります。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        // this will match `/english(default)/something` being requested
        source: '/english\\(default\\)/:slug',
        headers: [
          {
            key: 'x-header',
            value: 'value',
          },
        ],
      },
    ]
  },
}

ヘッダー、クッキー、またはクエリの値も has フィールドに一致する場合、または missing フィールドに一致しない場合にのみヘッダーを適用するには、has フィールドまたは missing フィールドを使用できます。ヘッダーを適用するには、source とすべての has 項目が一致し、すべての missing 項目が一致しない必要があります。

has および missing 項目には、以下のフィールドがあります。

  • type: String - headercookiehost、または query のいずれかである必要があります。
  • key: String - 照合する選択されたタイプのキー。
  • value: String または undefined - チェックする値。undefined の場合は、任意の値が一致します。正規表現のような文字列を使用して、値の特定の部分をキャプチャできます。例:値 first-(?<paramName>.*)first-second に使用されている場合、second は宛先で :paramName を使用して利用できます。
next.config.js
module.exports = {
  async headers() {
    return [
      // if the header `x-add-header` is present,
      // the `x-another-header` header will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-add-header',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: 'hello',
          },
        ],
      },
      // if the header `x-no-header` is not present,
      // the `x-another-header` header will be applied
      {
        source: '/:path*',
        missing: [
          {
            type: 'header',
            key: 'x-no-header',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: 'hello',
          },
        ],
      },
      // if the source, query, and cookie are matched,
      // the `x-authorized` header will be applied
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // the page value will not be available in the
            // header key/values since value is provided and
            // doesn't use a named capture group e.g. (?<page>home)
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        headers: [
          {
            key: 'x-authorized',
            value: ':authorized',
          },
        ],
      },
      // if the header `x-authorized` is present and
      // contains a matching value, the `x-another-header` will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: ':authorized',
          },
        ],
      },
      // if the host is `example.com`,
      // this header will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: ':authorized',
          },
        ],
      },
    ]
  },
}

basePathをサポートするヘッダー

basePath のサポートをヘッダーで利用する場合、ヘッダーに basePath: false を追加しない限り、各 source は自動的に basePath でプレフィックスされます。

next.config.js
module.exports = {
  basePath: '/docs',
 
  async headers() {
    return [
      {
        source: '/with-basePath', // becomes /docs/with-basePath
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        source: '/without-basePath', // is not modified since basePath: false is set
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
        basePath: false,
      },
    ]
  },
}

i18nをサポートするヘッダー

i18n のサポートをヘッダーで利用する場合、ヘッダーに locale: false を追加しない限り、各 source は構成された locales を処理するために自動的にプレフィックスされます。locale: false が使用されている場合は、正しくマッチさせるために source にロケールをプレフィックスする必要があります。

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },
 
  async headers() {
    return [
      {
        source: '/with-locale', // automatically handles all locales
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // does not handle locales automatically since locale: false is set
        source: '/nl/with-locale-manual',
        locale: false,
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // this matches '/' since `en` is the defaultLocale
        source: '/en',
        locale: false,
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // this gets converted to /(en|fr|de)/(.*) so will not match the top-level
        // `/` or `/fr` routes like /:path* would
        source: '/(.*)',
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
    ]
  },
}

Cache-Control

Next.js は、真に不変なアセットに対して Cache-Control ヘッダーを public, max-age=31536000, immutable に設定します。これは上書きできません。これらの不変ファイルにはファイル名に SHA ハッシュが含まれているため、無期限に安全にキャッシュできます。例:静的画像インポート。これらのアセットに対して next.config.jsCache-Control ヘッダーを設定することはできません。

ただし、他のレスポンスやデータに対して Cache-Control ヘッダーを設定できます。

App Router を使用した キャッシングの詳細をご覧ください。

オプション

CORS

クロスオリジンリソース共有 (CORS) は、リソースにアクセスできるサイトを制御できるセキュリティ機能です。特定のオリジンがリソースにアクセスできるようにするには、Access-Control-Allow-Origin ヘッダーを設定できます。ルートハンドラー.

async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          {
            key: "Access-Control-Allow-Origin",
            value: "*", // Set your origin
          },
          {
            key: "Access-Control-Allow-Methods",
            value: "GET, POST, PUT, DELETE, OPTIONS",
          },
          {
            key: "Access-Control-Allow-Headers",
            value: "Content-Type, Authorization",
          },
        ],
      },
    ];
  },

X-DNS-Prefetch-Control

このヘッダー は DNS プリフェッチを制御し、ブラウザが外部リンク、画像、CSS、JavaScript などに対してドメイン名解決をプロアクティブに実行できるようにします。このプリフェッチはバックグラウンドで実行されるため、参照されたアイテムが必要になるまでに DNS が解決されている可能性が高くなります。これにより、ユーザーがリンクをクリックしたときのレイテンシが削減されます。

{
  key: 'X-DNS-Prefetch-Control',
  value: 'on'
}

Strict-Transport-Security

このヘッダー は、HTTP の代わりに HTTPS を使用してのみアクセスする必要があることをブラウザに通知します。以下の構成を使用すると、現在および将来のすべてのサブドメインは、2 年間の max-age で HTTPS を使用します。これにより、HTTP でのみ提供できるページまたはサブドメインへのアクセスがブロックされます。

Vercel にデプロイする場合、next.config.jsheaders を宣言しない限り、このヘッダーはすべてのデプロイに自動的に追加されるため、必要ありません。

{
  key: 'Strict-Transport-Security',
  value: 'max-age=63072000; includeSubDomains; preload'
}

X-Frame-Options

このヘッダー は、サイトが iframe 内に表示されることを許可するかどうかを示します。これにより、クリックジャッキング攻撃を防ぐことができます。

このヘッダーは、CSP の frame-ancestors オプションに取って代わられました。これは、最新のブラウザでより優れたサポートを提供します (構成の詳細については、コンテンツセキュリティポリシー を参照してください)。

{
  key: 'X-Frame-Options',
  value: 'SAMEORIGIN'
}

Permissions-Policy

このヘッダーを使用すると、ブラウザで使用できる機能とAPIを制御できます。以前はFeature-Policyという名前でした。

{
  key: 'Permissions-Policy',
  value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()'
}

X-Content-Type-Options

このヘッダーは、Content-Typeヘッダーが明示的に設定されていない場合に、ブラウザがコンテンツの種類を推測しようとするのを防ぎます。これにより、ユーザーがファイルをアップロードおよび共有できるWebサイトでのXSS攻撃を防ぐことができます。

たとえば、ユーザーが画像をダウンロードしようとしたときに、実行可能ファイルのような異なるContent-Typeとして扱われる可能性があります。これは悪意のある可能性があります。このヘッダーは、ブラウザ拡張機能のダウンロードにも適用されます。このヘッダーの有効な値はnosniffのみです。

{
  key: 'X-Content-Type-Options',
  value: 'nosniff'
}

Referrer-Policy

このヘッダーは、現在のWebサイト(オリジン)から別のWebサイトに移動するときに、ブラウザが含める情報の量を制御します。

{
  key: 'Referrer-Policy',
  value: 'origin-when-cross-origin'
}

Content-Security-Policy

アプリケーションにコンテンツセキュリティポリシーを追加する方法について詳しくはこちらをご覧ください。

Version History

バージョン変更点
v13.3.0missingが追加されました。
v10.2.0hasが追加されました。
v9.5.0ヘッダーが追加されました。