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

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

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

API目的場所ステータスコード
useRouterクライアントサイドナビゲーションを実行するコンポーネント該当なし
next.config.jsredirectsパスに基づいて受信リクエストをリダイレクトするnext.config.js ファイル307 (一時) または 308 (永続)
NextResponse.redirect条件に基づいて受信リクエストをリダイレクトするプロキシ任意

useRouter() フック

コンポーネント内でリダイレクトする必要がある場合は、useRouter フックの push メソッドを使用できます。たとえば

app/page.tsx
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.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 の例: 推奨事項の実装については、Bloom filter を使用した Proxy の例を参照してください。

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

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

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

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

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

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 つの方法があります。

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

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

存在する場合、リクエストを API Routes に転送します。これは実際のファイルをチェックし、ユーザーを適切な 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()
}

次に、API Route で

pages/api/redirects.ts
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 filter を生成するには、bloom-filters のようなライブラリを使用できます。
  • 悪意のあるリクエストを防ぐために、Route Handler へのリクエストを検証する必要があります。