コンテンツへスキップ

headers

ヘッダーを使用すると、指定されたパスへの受信リクエストに対するレスポンスにカスタムHTTPヘッダーを設定できます。

カスタムHTTPヘッダーを設定するには、`next.config.js`の`headers`キーを使用します。

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`は、`source`と`headers`プロパティを持つオブジェクトの配列が返されることを期待する非同期関数です。

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

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

ヘッダーのオーバーライド動作

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

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',
          },
        ],
      },
    ]
  },
}

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

`has`および`missing`項目には、以下のフィールドを含めることができます。

  • `type`: `String` - `header`、`cookie`、`host`、または`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は、真に不変なアセットに対して`public, max-age=31536000, immutable`の`Cache-Control`ヘッダーを設定します。これは上書きできません。これらの不変なファイルはファイル名にSHAハッシュを含んでいるため、安全に無期限にキャッシュできます。例えば、静的画像のインポートなどです。これらのアセットに対して`next.config.js`で`Cache-Control`ヘッダーを設定することはできません。

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

App Routerでのキャッシングについて詳しく学ぶ。

オプション

CORS

Cross-Origin Resource Sharing (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を使用してのみアクセスされるべきであることを通知します。以下の設定を使用すると、現在および将来のすべてのサブドメインは、`max-age`2年間HTTPSを使用するようになります。これにより、HTTP経由でしか提供できないページやサブドメインへのアクセスがブロックされます。

Vercelにデプロイする場合、`next.config.js`で`headers`を宣言しない限り、このヘッダーはすべてのデプロイメントに自動的に追加されるため、不要です。

{
  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`ヘッダーが明示的に設定されていない場合に、ブラウザがコンテンツのタイプを推測しようとするのを防ぎます。これにより、ユーザーがファイルをアップロードおよび共有できるウェブサイトでのXSS攻撃を防ぐことができます。

例えば、ユーザーが画像をダウンロードしようとしているのに、それが悪意のある実行ファイルのような別の`Content-Type`として扱われるのを防ぎます。このヘッダーはブラウザ拡張機能のダウンロードにも適用されます。このヘッダーの唯一の有効な値は`nosniff`です。

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

Referrer-Policy

このヘッダーは、ブラウザが現在のウェブサイト(オリジン)から別のウェブサイトへナビゲートする際に、どれだけの情報を含めるかを制御します。

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

Content-Security-Policy

アプリケーションにコンテンツセキュリティポリシーを追加する方法について詳しく学ぶ。

バージョン履歴

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