headers
Headersは、指定されたパスへの受信リクエストに対するレスポンスにカスタムHTTPヘッダーを設定することを可能にします。
カスタムHTTPヘッダーを設定するには、next.config.jsでheadersキーを使用します。
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の場合、matching時にbasePathは含まれません。外部リライトにのみ使用できます。
- locale:- falseまたは- undefined- matching時にlocaleを含めるべきかどうか。
- hasは、- type、- key、- valueプロパティを持つhasオブジェクトの配列です。
- missingは、- type、- key、- valueプロパティを持つmissingオブジェクトの配列です。
ヘッダーは、ファイルシステム(pagesや/publicファイルを含む)よりも前にチェックされます。
Headerのオーバーライド動作
同じパスに一致する2つのヘッダーが同じヘッダーキーを設定する場合、後から設定されたヘッダーキーが最初それを上書きします。以下のヘッダーを使用すると、パス/helloは、最後に設定された値がworldであるため、ヘッダーx-helloがworldになります。
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に一致しますが、(ネストされたパスは一致しません)
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に一致します。
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には一致しません。
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:post(\\d{1,})',
        headers: [
          {
            key: 'x-post',
            value: ':post',
          },
        ],
      },
    ]
  },
}特殊文字(、)、{、}、:、*、+、?は正規表現パスマッチングに使用されるため、sourceで特殊でない値として使用する場合は、前に\\を追加してエスケープする必要があります。
module.exports = {
  async headers() {
    return [
      {
        // this will match `/english(default)/something` being requested
        source: '/english\\(default\\)/:slug',
        headers: [
          {
            key: 'x-header',
            value: 'value',
          },
        ],
      },
    ]
  },
}ヘッダー、Cookie、クエリのマッチング
ヘッダー、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で宛先で使用できます。
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サポート付きのHeader
basePathサポートを利用する場合、各sourceは自動的にbasePathでプレフィックスされます。ただし、ヘッダーにbasePath: falseを追加しない限り、これは適用されます。
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サポート付きのHeader
i18nサポートを利用する場合、各sourceは自動的に設定されたlocalesを処理するようにプレフィックスされます。ただし、ヘッダーにlocale: falseを追加しない限り、これは適用されます。locale: falseを使用する場合、正しく一致させるにはsourceにロケールをプレフィックスする必要があります。
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ハッシュが含まれているため、無期限に安全にキャッシュできます。例: Static Image Imports。これらのアセットに対してnext.config.jsでCache-Controlヘッダーを設定することはできません。
ただし、他のレスポンスやデータに対してCache-Controlヘッダーを設定することは可能です。
静的生成されたページのキャッシュを再検証する必要がある場合は、そのページのgetStaticProps関数でrevalidateプロップを設定することで行うことができます。
API Routeからのレスポンスをキャッシュするには、res.setHeaderを使用します。
import type { NextApiRequest, NextApiResponse } from 'next'
 
type ResponseData = {
  message: string
}
 
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.setHeader('Cache-Control', 's-maxage=86400')
  res.status(200).json({ message: 'Hello from Next.js!' })
}getServerSideProps内でキャッシュヘッダー(Cache-Control)を使用して動的なレスポンスをキャッシュすることもできます。例: stale-while-revalidateを使用します。
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
 
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export const getServerSideProps = (async (context) => {
  context.res.setHeader(
    'Cache-Control',
    'public, s-maxage=10, stale-while-revalidate=59'
  )
 
  return {
    props: {},
  }
}) satisfies GetServerSidePropsオプション
CORS
Cross-Origin Resource Sharing (CORS)は、どのサイトがリソースにアクセスできるかを制御するセキュリティ機能です。特定のオリジンからのアクセスを許可するには、Access-Control-Allow-Originヘッダーを設定します。API Endpoints.
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を使用します。これにより、HTTPSでしか提供できないページやサブドメインへのアクセスがブロックされます。
{
  key: 'Strict-Transport-Security',
  value: 'max-age=63072000; includeSubDomains; preload'
}X-Frame-Options
このヘッダーは、サイトがiframe内で表示されることを許可するかどうかを示します。これにより、クリックジャッキング攻撃を防ぐことができます。
このヘッダーはCSPのframe-ancestorsオプションに置き換えられました。このオプションは、最新のブラウザでより良いサポートを提供します(設定に関する詳細はContent Security Policyを参照してください)。
{
  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
アプリケーションにContent Security Policyを追加する方法については、こちらを参照してください。
バージョン履歴
| バージョン | 変更履歴 | 
|---|---|
| v13.3.0 | missingが追加されました。 | 
| v10.2.0 | hasが追加されました。 | 
| v9.5.0 | ヘッダーが追加されました。 | 
役に立ちましたか?