リダイレクト
Next.js でリダイレクトを処理する方法はいくつかあります。このページでは、利用可能な各オプション、ユースケース、および多数のリダイレクトを管理する方法について説明します。
API | 目的 | 場所 | ステータスコード |
---|---|---|---|
redirect | ミューテーションまたはイベント後のユーザーリダイレクト | サーバーコンポーネント、サーバーアクション、ルートハンドラー | 307 (一時的) または 303 (サーバーアクション) |
permanentRedirect | ミューテーションまたはイベント後のユーザーリダイレクト | サーバーコンポーネント、サーバーアクション、ルートハンドラー | 308 (永続的) |
useRouter | クライアントサイドナビゲーションの実行 | クライアントコンポーネントのイベントハンドラー | 該当なし |
next.config.js の redirects | パスに基づく受信リクエストのリダイレクト | next.config.js ファイル | 307 (一時的) または 308 (永続的) |
NextResponse.redirect | 条件に基づく受信リクエストのリダイレクト | ミドルウェア | どこでも |
redirect
関数
redirect
関数を使用すると、ユーザーを別の URL にリダイレクトできます。redirect
は、サーバーコンポーネント、ルートハンドラー、およびサーバーアクションで呼び出すことができます。
redirect
は、ミューテーションやイベントの後に使用されることがよくあります。たとえば、投稿の作成などです。
'use server'
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'
export async function createPost(id: string) {
try {
// Call database
} catch (error) {
// Handle errors
}
revalidatePath('/posts') // Update cached posts
redirect(`/post/${id}`) // Navigate to the new post page
}
知っておくと良いこと:
redirect
はデフォルトで 307 (一時的なリダイレクト) ステータスコードを返します。サーバーアクションで使用すると、303 (See Other) を返します。これは、POST リクエストの結果として成功ページにリダイレクトするためによく使用されます。redirect
は内部的にエラーをスローするため、try/catch
ブロックの外で呼び出す必要があります。redirect
は、クライアントコンポーネントのレンダリングプロセス中に呼び出すことができますが、イベントハンドラーでは呼び出すことができません。useRouter
フックを使用してください。redirect
は絶対 URL も受け入れ、外部リンクへのリダイレクトにも使用できます。- レンダリングプロセスより前にリダイレクトしたい場合は、
next.config.js
またはミドルウェアを使用してください。
詳細については、redirect
API リファレンスを参照してください。
permanentRedirect
関数
permanentRedirect
関数を使用すると、ユーザーを**永続的に**別の URL にリダイレクトできます。permanentRedirect
は、サーバーコンポーネント、ルートハンドラー、およびサーバーアクションで呼び出すことができます。
permanentRedirect
は、ユーザー名変更後のプロフィール URL の更新など、エンティティの正規 URL を変更するミューテーションやイベントの後に使用されることがよくあります。
'use server'
import { permanentRedirect } from 'next/navigation'
import { revalidateTag } from 'next/cache'
export async function updateUsername(username: string, formData: FormData) {
try {
// Call database
} catch (error) {
// Handle errors
}
revalidateTag('username') // Update all references to the username
permanentRedirect(`/profile/${username}`) // Navigate to the new user profile
}
知っておくと良いこと:
permanentRedirect
はデフォルトで 308 (永続的なリダイレクト) ステータスコードを返します。permanentRedirect
は絶対 URL も受け入れ、外部リンクへのリダイレクトにも使用できます。- レンダリングプロセスより前にリダイレクトしたい場合は、
next.config.js
またはミドルウェアを使用してください。
詳細については、permanentRedirect
API リファレンスを参照してください。
useRouter()
フック
クライアントコンポーネントのイベントハンドラー内でリダイレクトする必要がある場合は、useRouter
フックの push
メソッドを使用できます。例えば、
'use client'
import { useRouter } from 'next/navigation'
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
ファイルに追加します。
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
async redirects() {
return [
// Basic redirect
{
source: '/about',
destination: '/',
permanent: true,
},
// Wildcard path matching
{
source: '/blog/:slug',
destination: '/news/:slug',
permanent: true,
},
]
},
}
export default nextConfig
詳細については、redirects
API リファレンスを参照してください。
知っておくと良いこと:
redirects
は、permanent
オプションを使用して、307 (一時的なリダイレクト) または 308 (永続的なリダイレクト) ステータスコードを返すことができます。redirects
にはプラットフォームに制限がある場合があります。たとえば、Vercel では 1,024 個のリダイレクトに制限があります。多数のリダイレクト (1000 以上) を管理するには、ミドルウェアを使用したカスタムソリューションの作成を検討してください。詳細については、大規模なリダイレクトの管理を参照してください。redirects
はミドルウェアの**前に**実行されます。
Middleware の 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 の例: 以下の推奨事項の実装例については、Bloom フィルターを使用したミドルウェアの例を参照してください。
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 にリダイレクトされます。これにより、大規模なリダイレクトファイルをミドルウェアにインポートする必要がなくなり、各受信リクエストが遅くなるのを防ぐことができます。
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()
}
次に、ルートハンドラーで
import { NextRequest, NextResponse } from 'next/server'
import redirects from '@/app/redirects/redirects.json'
type RedirectEntry = {
destination: string
permanent: boolean
}
export function GET(request: NextRequest) {
const pathname = request.nextUrl.searchParams.get('pathname')
if (!pathname) {
return new Response('Bad Request', { status: 400 })
}
// 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 new Response('No redirect', { status: 400 })
}
// Return the redirect entry
return NextResponse.json(redirect)
}
知っておくと良いこと
- ブルームフィルターを生成するには、
bloom-filters
のようなライブラリを使用できます。- 悪意のあるリクエストを防ぐために、ルートハンドラーへのリクエストを検証する必要があります。
次のステップ
これは役に立ちましたか?