リダイレクト
Next.js でリダイレクトを処理する方法はいくつかあります。このページでは、利用可能な各オプション、ユースケース、および多数のリダイレクトを管理する方法について説明します。
API | 目的 | 場所 | ステータスコード |
---|---|---|---|
redirect | ミューテーションまたはイベント後にユーザーをリダイレクトする | サーバーコンポーネント、サーバーアクション、ルートハンドラー | 307 (一時的) または 303 (サーバーアクション) |
permanentRedirect | ミューテーションまたはイベント後にユーザーをリダイレクトする | サーバーコンポーネント、サーバーアクション、ルートハンドラー | 308 (永続的) |
useRouter | クライアントサイドナビゲーションを実行する | クライアントコンポーネントのイベントハンドラー | N/A |
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 (一時的なリダイレクト) ステータスコードを返します。サーバーアクションで使用した場合、POST リクエストの結果として成功ページにリダイレクトするためによく使用される 303 (See Other) を返します。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
ファイルにオプションを追加します。
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 件以上) を管理するには、Middleware を使用してカスタムソリューションを作成することを検討してください。詳細については、大規模なリダイレクトの管理を参照してください。redirects
は、Middleware の前に実行されます。
Middleware の NextResponse.redirect
Middleware を使用すると、リクエストが完了する前にコードを実行できます。次に、受信リクエストに基づいて、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*',
}
知っておくとよいこと:
- Middleware は、
next.config.js
のredirects
の後、レンダリングの前に実行されます。
詳細については、Middleware ドキュメントを参照してください。
大規模なリダイレクトの管理 (高度)
大量のリダイレクト (1000 件以上) を管理するには、Middleware を使用してカスタムソリューションを作成することを検討できます。これにより、アプリケーションを再デプロイすることなく、プログラムでリダイレクトを処理できます。
これを行うには、以下を検討する必要があります。
- リダイレクトマップの作成と保存。
- データ参照パフォーマンスの最適化。
Next.js の例: 以下の推奨事項の実装については、ブルームフィルターを使用した Middleware の例を参照してください。
1. リダイレクトマップの作成と保存
リダイレクトマップは、データベース (通常はキーと値のストア) または JSON ファイルに保存できるリダイレクトのリストです。
次のデータ構造を検討してください。
{
"/old": {
"destination": "/new",
"permanent": true
},
"/blog/post-old": {
"destination": "/blog/post-new",
"permanent": true
}
}
Middleware では、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 など、高速読み取りに最適化されたデータベースを使用します。
- ブルームフィルター などのデータ参照戦略を使用して、大きなリダイレクトファイルまたはデータベースを読み込む前に、リダイレクトが存在するかどうかを効率的に確認します。
前の例を考慮して、生成されたブルームフィルターファイルを Middleware にインポートし、受信リクエストのパス名がブルームフィルターに存在するかどうかを確認できます。
存在する場合は、リクエストを ルートハンドラー に転送します。これにより、実際のリダイレクトファイルを確認し、ユーザーを適切な URL にリダイレクトします。これにより、Middleware に大きなリダイレクトファイルをインポートする必要がなくなり、受信リクエストごとに処理速度が低下するのを防ぐことができます。
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
などのライブラリを使用できます。- 悪意のあるリクエストを防ぐために、ルートハンドラーに対して行われたリクエストを検証する必要があります。
次のステップ
この記事は役に立ちましたか?