リダイレクト
Next.jsでは、リダイレクトを処理する方法はいくつかあります。 このページでは、利用可能な各オプション、ユースケース、および大量のリダイレクトの管理方法について説明します。
API | 目的 | 場所 | ステータスコード |
---|---|---|---|
useRouter | クライアントサイドナビゲーションを実行する | コンポーネント | 該当なし |
next.config.js のredirects | パスに基づいて着信リクエストをリダイレクトする | next.config.js ファイル | 307 (一時的) または 308 (恒久的) |
NextResponse.redirect | 条件に基づいて着信リクエストをリダイレクトする | ミドルウェア | いずれか |
useRouter()
フック
コンポーネント内でリダイレクトする必要がある場合は、useRouter
フックの push
メソッドを使用できます。 例:
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}
知っておくと良いこと:
- プログラムでユーザーをナビゲートする必要がない場合は、
<Link>
コンポーネントを使用する必要があります。
詳細については、useRouter
APIリファレンスを参照してください。
next.config.js
のredirects
next.config.js
ファイルのredirects
オプションを使用すると、着信リクエストパスを別の宛先パスにリダイレクトできます。 これは、ページのURL構造を変更する場合や、事前にわかっているリダイレクトのリストがある場合に役立ちます。
redirects
はパス、ヘッダー、Cookie、およびクエリマッチングをサポートしており、着信リクエストに基づいてユーザーをリダイレクトする柔軟性を提供します。
redirects
を使用するには、next.config.js
ファイルにオプションを追加します
module.exports = {
async redirects() {
return [
// Basic redirect
{
source: '/about',
destination: '/',
permanent: true,
},
// Wildcard path matching
{
source: '/blog/:slug',
destination: '/news/:slug',
permanent: true,
},
]
},
}
詳細については、redirects
APIリファレンスを参照してください。
知っておくと良いこと:
redirects
は、permanent
オプションを使用して、307 (一時リダイレクト) または 308 (恒久リダイレクト) ステータスコードを返すことができます。redirects
にはプラットフォームの制限がある場合があります。 たとえば、Vercelでは、1,024リダイレクトの制限があります。 大量のリダイレクト (1000+) を管理するには、ミドルウェアを使用してカスタムソリューションを作成することを検討してください。 詳細については、大規模なリダイレクトの管理を参照してください。redirects
はミドルウェアの**前**に実行されます。
ミドルウェアのNextResponse.redirect
ミドルウェアを使用すると、リクエストが完了する前にコードを実行できます。次に、受信リクエストに基づいて、NextResponse.redirect
を使用して別の URL にリダイレクトします。これは、条件(例:認証、セッション管理など)に基づいてユーザーをリダイレクトする場合、または多数のリダイレクトがある場合に便利です。
たとえば、認証されていない場合にユーザーを /login
ページにリダイレクトするには、次のようにします。
import { NextResponse, NextRequest } from 'next/server'
import { authenticate } from 'auth-provider'
export function middleware(request: NextRequest) {
const isAuthenticated = authenticate(request)
// If the user is authenticated, continue as normal
if (isAuthenticated) {
return NextResponse.next()
}
// Redirect to login page if not authenticated
return NextResponse.redirect(new URL('/login', request.url))
}
export const config = {
matcher: '/dashboard/:path*',
}
知っておくと良いこと:
- ミドルウェアは、
next.config.js
のredirects
の**後**、レンダリングの**前**に実行されます。
詳細については、ミドルウェアのドキュメントを参照してください。
大規模なリダイレクトの管理(上級)
多数のリダイレクト(1000+)を管理するには、ミドルウェアを使用してカスタムソリューションを作成することを検討してください。これにより、アプリケーションを再デプロイすることなく、プログラムでリダイレクトを処理できます。
これを行うには、以下の点を考慮する必要があります。
- リダイレクトマップの作成と保存。
- データ検索パフォーマンスの最適化。
**Next.js の例**: 以下の推奨事項の実装については、ブルームフィルターを使用したミドルウェアの例を参照してください。
1. リダイレクトマップの作成と保存
リダイレクトマップは、データベース(通常はキーバリューストア)または JSON ファイルに保存できるリダイレクトのリストです。
次のデータ構造を検討してください。
{
"/old": {
"destination": "/new",
"permanent": true
},
"/blog/post-old": {
"destination": "/blog/post-new",
"permanent": true
}
}
ミドルウェアでは、Vercel の Edge Config や Redis などのデータベースから読み取り、受信リクエストに基づいてユーザーをリダイレクトできます。
import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/edge-config'
type RedirectEntry = {
destination: string
permanent: boolean
}
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname
const redirectData = await get(pathname)
if (redirectData && typeof redirectData === 'string') {
const redirectEntry: RedirectEntry = JSON.parse(redirectData)
const statusCode = redirectEntry.permanent ? 308 : 307
return NextResponse.redirect(redirectEntry.destination, statusCode)
}
// No redirect found, continue without redirecting
return NextResponse.next()
}
2. データ検索パフォーマンスの最適化
受信リクエストごとに大規模なデータセットを読み取ると、速度が低下し、コストがかかる可能性があります。データ検索のパフォーマンスを最適化するには、2 つの方法があります。
- Vercel Edge Config や Redis など、高速読み取りに最適化されたデータベースを使用する。
- 大きなリダイレクトファイルまたはデータベースを読み取る**前**に、リダイレクトが存在するかどうかを効率的に確認するために、ブルームフィルターなどのデータ検索戦略を使用する。
前の例を考慮すると、生成されたブルームフィルターファイルをミドルウェアにインポートし、受信リクエストのパス名がブルームフィルターに存在するかどうかを確認できます。
存在する場合は、リクエストを 実際のファイルをチェックし、ユーザーを適切な URL にリダイレクトする API ルート に転送します。これにより、大きなリダイレクトファイルをミドルウェアにインポートすることを回避でき、受信リクエストごとに速度が低下するのを防ぐことができます。
import { NextResponse, NextRequest } from 'next/server'
import { ScalableBloomFilter } from 'bloom-filters'
import GeneratedBloomFilter from './redirects/bloom-filter.json'
type RedirectEntry = {
destination: string
permanent: boolean
}
// Initialize bloom filter from a generated JSON file
const bloomFilter = ScalableBloomFilter.fromJSON(GeneratedBloomFilter as any)
export async function middleware(request: NextRequest) {
// Get the path for the incoming request
const pathname = request.nextUrl.pathname
// Check if the path is in the bloom filter
if (bloomFilter.has(pathname)) {
// Forward the pathname to the Route Handler
const api = new URL(
`/api/redirects?pathname=${encodeURIComponent(request.nextUrl.pathname)}`,
request.nextUrl.origin
)
try {
// Fetch redirect data from the Route Handler
const redirectData = await fetch(api)
if (redirectData.ok) {
const redirectEntry: RedirectEntry | undefined =
await redirectData.json()
if (redirectEntry) {
// Determine the status code
const statusCode = redirectEntry.permanent ? 308 : 307
// Redirect to the destination
return NextResponse.redirect(redirectEntry.destination, statusCode)
}
}
} catch (error) {
console.error(error)
}
}
// No redirect found, continue the request without redirecting
return NextResponse.next()
}
次に、API ルートで
import type { NextApiRequest, NextApiResponse } from 'next'
import redirects from '@/app/redirects/redirects.json'
type RedirectEntry = {
destination: string
permanent: boolean
}
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const pathname = req.query.pathname
if (!pathname) {
return res.status(400).json({ message: 'Bad Request' })
}
// Get the redirect entry from the redirects.json file
const redirect = (redirects as Record<string, RedirectEntry>)[pathname]
// Account for bloom filter false positives
if (!redirect) {
return res.status(400).json({ message: 'No redirect' })
}
// Return the redirect entry
return res.json(redirect)
}
知っておくと良いこと
- ブルームフィルターを生成するには、
bloom-filters
などのライブラリを使用できます。- 悪意のあるリクエストを防ぐために、ルートハンドラーへのリクエストを検証する必要があります。
これは役に立ちましたか?