コンテンツにスキップ
App Routerガイドリダイレクト

Next.jsでリダイレクトを処理する方法

Next.jsでリダイレクトを処理するには、いくつかの方法があります。このページでは、利用可能な各オプション、ユースケース、および多数のリダイレクトを管理する方法について説明します。

API目的場所ステータスコード
redirectミューテーションまたはイベント後にユーザーをリダイレクトするサーバーコンポーネント、サーバーアクション、ルートハンドラ307 (一時) または 303 (サーバーアクション)
permanentRedirectミューテーションまたはイベント後にユーザーをリダイレクトするサーバーコンポーネント、サーバーアクション、ルートハンドラ308 (恒久的)
useRouterクライアントサイドナビゲーションを実行するクライアントコンポーネントでのイベントハンドラ該当なし
next.config.jsredirectsパスに基づいて着信リクエストをリダイレクトするnext.config.js ファイル307 (一時) または 308 (恒久的)
NextResponse.redirect条件に基づいて着信リクエストをリダイレクトするプロキシすべて

redirect関数

redirect関数を使用すると、ユーザーを別のURLにリダイレクトできます。redirectは、サーバーコンポーネントルートハンドラ、およびサーバーアクションで呼び出すことができます。

redirectは、ミューテーションまたはイベントの後に頻繁に使用されます。たとえば、投稿の作成など

app/actions.ts
'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 (その他を参照) を返し、これはPOSTリクエストの結果として成功ページにリダイレクトするために一般的に使用されます。
  • redirectはエラーをスローするため、try/catchステートメントを使用する場合は、tryブロックの外側で呼び出す必要があります。
  • redirectは、レンダリングプロセス中にクライアントコンポーネントで呼び出すことができますが、イベントハンドラでは呼び出せません。代わりにuseRouterフックを使用できます。
  • redirectは絶対URLも受け入れ、外部リンクへのリダイレクトに使用できます。
  • レンダリングプロセス前にリダイレクトしたい場合は、next.config.jsまたはProxyを使用してください。

詳細については、redirect APIリファレンスを参照してください。

permanentRedirect関数

permanentRedirect関数を使用すると、ユーザーを別のURLに恒久的にリダイレクトできます。permanentRedirectは、サーバーコンポーネントルートハンドラ、およびサーバーアクションで呼び出すことができます。

permanentRedirectは、ユーザーのユーザー名変更後にユーザープロフィールのURLを更新するなど、エンティティの正規URLを変更するミューテーションまたはイベントの後に頻繁に使用されます

app/actions.ts
'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またはProxyを使用してください。

詳細については、permanentRedirect APIリファレンスを参照してください。

useRouter()フック

クライアントコンポーネントのイベントハンドラ内でリダイレクトする必要がある場合は、useRouterフックのpushメソッドを使用できます。例:

app/page.tsx
'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.jsredirects

next.config.js ファイルの redirects オプションを使用すると、着信リクエストパスを別の宛先パスにリダイレクトできます。これは、ページのURL構造を変更した場合や、事前にわかっているリダイレクトのリストがある場合に便利です。

redirectsは、パスヘッダー、Cookie、およびクエリマッチングをサポートしており、着信リクエストに基づいてユーザーをリダイレクトする柔軟性があります。

redirectsを使用するには、next.config.jsファイルにオプションを追加します

next.config.ts
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件以上) を管理するには、Proxyを使用したカスタムソリューションを検討してください。「大規模なリダイレクトの管理」を参照してください。
  • redirectsはProxyよりに実行されます。

ProxyでのNextResponse.redirect

Proxyを使用すると、リクエストが完了する前にコードを実行できます。その後、着信リクエストに基づいてNextResponse.redirectを使用して別のURLにリダイレクトします。これは、条件 (認証、セッション管理など) に基づいてユーザーをリダイレクトしたい場合や、多数のリダイレクトがある場合に便利です。

たとえば、認証されていないユーザーを/loginページにリダイレクトするには

proxy.ts
import { NextResponse, NextRequest } from 'next/server'
import { authenticate } from 'auth-provider'
 
export function proxy(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*',
}

知っておくと良いこと:

  • Proxyは、next.config.jsredirects、およびレンダリングのに実行されます。

詳細については、Proxyのドキュメントを参照してください。

大規模なリダイレクトの管理 (高度)

多数のリダイレクト (1000件以上) を管理するには、Proxyを使用したカスタムソリューションの作成を検討してください。これにより、アプリケーションの再デプロイなしでリダイレクトをプログラムで処理できます。

これを行うには、以下を検討する必要があります

  1. リダイレクトマップの作成と保存。
  2. データ検索パフォーマンスの最適化。

Next.jsの例: 推奨事項の実装については、ブルームフィルターを使用したProxyの例を参照してください。

1. リダイレクトマップの作成と保存

リダイレクトマップは、データベース (通常はキーバリューストア) またはJSONファイルに保存できるリダイレクトのリストです。

以下のデータ構造を検討してください

{
  "/old": {
    "destination": "/new",
    "permanent": true
  },
  "/blog/post-old": {
    "destination": "/blog/post-new",
    "permanent": true
  }
}

Proxyでは、VercelのEdge ConfigまたはRedisのようなデータベースから読み込み、着信リクエストに基づいてユーザーをリダイレクトできます。

proxy.ts
import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/edge-config'
 
type RedirectEntry = {
  destination: string
  permanent: boolean
}
 
export async function proxy(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つの方法があります

  • 高速読み込みに最適化されたデータベースを使用する
  • より大きなリダイレクトファイルまたはデータベースを読み込むに、リダイレクトが存在するかどうかを効率的に確認するために、ブルームフィルターのようなデータ検索戦略を使用する。

前の例を考慮すると、生成されたブルームフィルターファイルをProxyにインポートし、着信リクエストのパス名がブルームフィルターに存在するかどうかを確認できます。

存在する場合は、リクエストをルートハンドラに転送しますこれにより、実際のファイルがチェックされ、ユーザーが適切なURLにリダイレクトされます。これにより、Proxyに大きなリダイレクトファイルをインポートするのを回避し、すべての着信リクエストを遅くするのを防ぎます。

proxy.ts
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 proxy(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()
}

次に、ルートハンドラで

app/api/redirects/route.ts
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のようなライブラリを使用できます。
  • 悪意のあるリクエストを防ぐために、ルートハンドラへのリクエストを検証する必要があります。