ミドルウェア
ミドルウェアを使用すると、リクエストが完了する前にコードを実行できます。次に、受信リクエストに基づいて、リライト、リダイレクト、リクエストまたはレスポンスヘッダーの変更、または直接レスポンスすることで、レスポンスを変更できます。
ミドルウェアは、キャッシュされたコンテンツとルートが一致する前に実行されます。詳細については、「パスのマッチング」を参照してください。
ユースケース
ミドルウェアをアプリケーションに統合すると、パフォーマンス、セキュリティ、およびユーザーエクスペリエンスが大幅に向上する可能性があります。ミドルウェアが特に効果的な一般的なシナリオを以下に示します。
- 認証と承認:特定のページまたは API ルートへのアクセスを許可する前に、ユーザーIDを確認し、セッションクッキーを確認します。
- サーバーサイドリダイレクト:特定の条件(ロケール、ユーザーロールなど)に基づいてサーバーレベルでユーザーをリダイレクトします。
- パスのリライト:リクエストプロパティに基づいて、パスを API ルートまたはページに動的にリライトすることにより、A/Bテスト、機能ロールアウト、またはレガシーパスをサポートします。
- ボット検出:ボットトラフィックを検出してブロックすることで、リソースを保護します。
- ロギングと分析:ページまたは API による処理の前に、インサイトを得るためにリクエストデータをキャプチャして分析します。
- フィーチャーフラグ:シームレスな機能ロールアウトまたはテストのために、機能を動的に有効または無効にします。
ミドルウェアが最適ではない可能性のある状況を認識することも同様に重要です。注意すべきいくつかのシナリオを次に示します。
- 複雑なデータフェッチと操作:ミドルウェアは、直接的なデータフェッチや操作のために設計されていません。これは、代わりにルートハンドラーまたはサーバーサイドユーティリティ内で行う必要があります。
- 負荷の高い計算タスク:ミドルウェアは軽量で、迅速に応答する必要があります。そうしないと、ページ読み込みの遅延が発生する可能性があります。負荷の高い計算タスクまたは長時間実行されるプロセスは、専用のルートハンドラー内で行う必要があります。
- 広範なセッション管理:ミドルウェアは基本的なセッションタスクを管理できますが、広範なセッション管理は、専用の認証サービスまたはルートハンドラー内で管理する必要があります。
- 直接データベース操作:ミドルウェア内で直接データベース操作を実行することはお勧めしません。データベースインタラクションは、ルートハンドラーまたはサーバーサイドユーティリティ内で行う必要があります。
規則
プロジェクトのルートにあるmiddleware.ts
(または .js
) ファイルを使用してミドルウェアを定義します。たとえば、pages
または app
と同じレベル、または該当する場合は src
の内側に定義します。
注:プロジェクトごとにサポートされる
middleware.ts
ファイルは1つだけですが、ミドルウェアロジックをモジュール化して構成することはできます。ミドルウェア機能を別々の.ts
または.js
ファイルに分割し、それらをメインのmiddleware.ts
ファイルにインポートします。これにより、ルート固有のミドルウェアのよりクリーンな管理が可能になり、集中管理のためにmiddleware.ts
に集約されます。単一のミドルウェアファイルを適用することにより、構成が簡素化され、潜在的な競合が防止され、複数のミドルウェアレイヤーを回避することでパフォーマンスが最適化されます。
例
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
パスのマッチング
ミドルウェアは、プロジェクト内のすべてのルートに対して呼び出されます。これを考慮すると、マッチャーを使用して特定のルートを正確にターゲットまたは除外することが重要です。以下は実行順序です。
next.config.js
からのheaders
next.config.js
からのredirects
- ミドルウェア (
rewrites
、redirects
など) next.config.js
からのbeforeFiles
(rewrites
)- ファイルシステムルート (
public/
、_next/static/
、pages/
、app/
など) next.config.js
からのafterFiles
(rewrites
)- 動的ルート (
/blog/[slug]
) fallback
(rewrites
) はnext.config.js
で設定します。
Middlewareがどのパスで実行されるかを定義する方法は2つあります。
マッチャー
matcher
を使用すると、Middlewareを特定のパスで実行するようにフィルタリングできます。
export const config = {
matcher: '/about/:path*',
}
単一のパス、または配列構文を使用して複数のパスをマッチさせることができます。
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
}
matcher
設定では、完全な正規表現が使用できるため、否定先読みや文字マッチングなどのマッチングがサポートされています。特定のパスを除くすべてにマッチする否定先読みの例は、こちらを参照してください。
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
}
また、missing
またはhas
配列、あるいはその両方を組み合わせることで、特定のリクエストに対してMiddlewareをバイパスすることもできます。
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
{
source:
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
{
source:
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
has: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
{
source:
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
has: [{ type: 'header', key: 'x-present' }],
missing: [{ type: 'header', key: 'x-missing', value: 'prefetch' }],
},
],
}
知っておくと良いこと:
matcher
の値は、ビルド時に静的に分析できるように定数である必要があります。変数などの動的な値は無視されます。
設定済みのマッチャー
- 必ず
/
で始める必要があります。 - 名前付きパラメーターを含めることができます:
/about/:path
は/about/a
と/about/b
にマッチしますが、/about/a/c
にはマッチしません。 - 名前付きパラメーター(
:
で始まる)に修飾子を指定できます:/about/:path*
は*
が「0個以上の」を意味するため、/about/a/b/c
にマッチします。?
は「0個または1個」、+
は「1個以上」です。 - 括弧で囲まれた正規表現を使用できます:
/about/(.*)
は/about/:path*
と同じです。
path-to-regexp のドキュメントで詳細を確認してください。
知っておくと良いこと:後方互換性のため、Next.jsは常に
/public
を/public/index
とみなします。したがって、/public/:path
のマッチャーがマッチします。
条件文
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/about')) {
return NextResponse.rewrite(new URL('/about-2', request.url))
}
if (request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.rewrite(new URL('/dashboard/user', request.url))
}
}
NextResponse
NextResponse
APIを使用すると、次のことができます。
- 受信リクエストを別のURLに
redirect
する - 特定のURLを表示してレスポンスを
rewrite
する - APIルート、
getServerSideProps
、およびrewrite
先のヘッダーを設定する - レスポンスのクッキーを設定する
- レスポンスヘッダーを設定する
Middlewareからレスポンスを生成するには、次のいずれかを実行できます。
- レスポンスを生成するルート(ページまたはEdge APIルート)に
rewrite
する NextResponse
を直接返す。レスポンスの生成を参照してください。
クッキーの使用
クッキーは通常のヘッダーです。Request
では、Cookie
ヘッダーに格納されます。Response
では、Set-Cookie
ヘッダーにあります。Next.jsは、NextRequest
とNextResponse
のcookies
拡張機能を介して、これらのクッキーにアクセスし操作するための便利な方法を提供します。
- 受信リクエストの場合、
cookies
には、クッキーをget
、getAll
、set
、およびdelete
するためのメソッドが付属しています。has
を使用してクッキーの存在を確認したり、clear
を使用してすべてのクッキーを削除したりできます。 - 送信レスポンスの場合、
cookies
には、get
、getAll
、set
、およびdelete
のメソッドがあります。
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Assume a "Cookie:nextjs=fast" header to be present on the incoming request
// Getting cookies from the request using the `RequestCookies` API
let cookie = request.cookies.get('nextjs')
console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }
const allCookies = request.cookies.getAll()
console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
request.cookies.has('nextjs') // => true
request.cookies.delete('nextjs')
request.cookies.has('nextjs') // => false
// Setting cookies on the response using the `ResponseCookies` API
const response = NextResponse.next()
response.cookies.set('vercel', 'fast')
response.cookies.set({
name: 'vercel',
value: 'fast',
path: '/',
})
cookie = response.cookies.get('vercel')
console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }
// The outgoing response will have a `Set-Cookie:vercel=fast;path=/` header.
return response
}
ヘッダーの設定
NextResponse
APIを使用して、リクエストヘッダーとレスポンスヘッダーを設定できます(リクエストヘッダーの設定は、Next.js v13.0.0以降で利用可能です)。
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-hello-from-middleware1', 'hello')
// You can also set request headers in NextResponse.next
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello')
return response
}
知っておくと良いこと:バックエンドのWebサーバー構成によっては、431 Request Header Fields Too Largeエラーが発生する可能性があるため、大きなヘッダーを設定することは避けてください。
CORS
MiddlewareでCORSヘッダーを設定して、単純なおよびプリフライトリクエストを含む、クロスオリジンリクエストを許可できます。
import { NextRequest, NextResponse } from 'next/server'
const allowedOrigins = ['https://acme.com', 'https://my-app.org']
const corsOptions = {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
export function middleware(request: NextRequest) {
// Check the origin from the request
const origin = request.headers.get('origin') ?? ''
const isAllowedOrigin = allowedOrigins.includes(origin)
// Handle preflighted requests
const isPreflight = request.method === 'OPTIONS'
if (isPreflight) {
const preflightHeaders = {
...(isAllowedOrigin && { 'Access-Control-Allow-Origin': origin }),
...corsOptions,
}
return NextResponse.json({}, { headers: preflightHeaders })
}
// Handle simple requests
const response = NextResponse.next()
if (isAllowedOrigin) {
response.headers.set('Access-Control-Allow-Origin', origin)
}
Object.entries(corsOptions).forEach(([key, value]) => {
response.headers.set(key, value)
})
return response
}
export const config = {
matcher: '/api/:path*',
}
レスポンスの生成
Response
またはNextResponse
インスタンスを返すことで、Middlewareから直接応答できます。(これはNext.js v13.1.0以降で利用可能です)
import type { NextRequest } from 'next/server'
import { isAuthenticated } from '@lib/auth'
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/:function*',
}
export function middleware(request: NextRequest) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond with JSON indicating an error message
return Response.json(
{ success: false, message: 'authentication failed' },
{ status: 401 }
)
}
}
waitUntil
と NextFetchEvent
NextFetchEvent
オブジェクトは、ネイティブのFetchEvent
オブジェクトを拡張し、waitUntil()
メソッドを含みます。
waitUntil()
メソッドは、引数としてPromiseを取り、Promiseが確定するまでMiddlewareの寿命を延長します。これはバックグラウンドで作業を実行するのに役立ちます。
import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest } from 'next/server'
export function middleware(req: NextRequest, event: NextFetchEvent) {
event.waitUntil(
fetch('https://my-analytics-platform.com', {
method: 'POST',
body: JSON.stringify({ pathname: req.nextUrl.pathname }),
})
)
return NextResponse.next()
}
高度なMiddlewareフラグ
Next.jsのv13.1
では、高度なユースケースを処理するために、skipMiddlewareUrlNormalize
とskipTrailingSlashRedirect
の2つの追加フラグがmiddlewareに導入されました。
skipTrailingSlashRedirect
は、末尾のスラッシュを追加または削除するためのNext.jsのリダイレクトを無効にします。これにより、middleware内でカスタム処理を行い、一部のパスでは末尾のスラッシュを維持し、他のパスでは維持しないことができ、段階的な移行を容易にすることができます。
module.exports = {
skipTrailingSlashRedirect: true,
}
const legacyPrefixes = ['/docs', '/blog']
export default async function middleware(req) {
const { pathname } = req.nextUrl
if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
return NextResponse.next()
}
// apply trailing slash handling
if (
!pathname.endsWith('/') &&
!pathname.match(/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/)
) {
return NextResponse.redirect(
new URL(`${req.nextUrl.pathname}/`, req.nextUrl)
)
}
}
skipMiddlewareUrlNormalize
を使用すると、Next.jsでのURLの正規化を無効にして、直接アクセスとクライアントトランジションの処理を同じにすることができます。一部の高度なケースでは、このオプションは元のURLを使用することで完全な制御を提供します。
module.exports = {
skipMiddlewareUrlNormalize: true,
}
export default async function middleware(req) {
const { pathname } = req.nextUrl
// GET /_next/data/build-id/hello.json
console.log(pathname)
// with the flag this now /_next/data/build-id/hello.json
// without the flag this would be normalized to /hello
}
ランタイム
Middlewareは現在、Edgeランタイムと互換性のあるAPIのみをサポートしています。Node.js専用のAPIはサポートされていません。
バージョン履歴
バージョン | 変更点 |
---|---|
v13.1.0 | 高度なMiddlewareフラグが追加されました |
v13.0.0 | Middlewareはリクエストヘッダー、レスポンスヘッダーを変更し、レスポンスを送信できます |
v12.2.0 | ミドルウェアは安定しています。 アップグレードガイドをご覧ください。 |
v12.0.9 | Edge Runtime で絶対 URL を強制 (PR) |
v12.0.0 | ミドルウェア (ベータ版) が追加されました |
お役に立ちましたか?