コンテンツへスキップ

unauthorized

この機能は現在実験的であり、変更される可能性があります。本番環境での使用は推奨されません。ぜひお試しいただき、GitHubでフィードバックをお寄せください。

unauthorized関数は、Next.jsの401エラーページを表示するエラーをスローします。これはアプリケーションでの認証エラー処理に役立ちます。unauthorized.jsファイルを使用してUIをカスタマイズできます。

unauthorizedの使用を開始するには、next.config.jsファイルで実験的なauthInterrupts設定オプションを有効にしてください。

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  experimental: {
    authInterrupts: true,
  },
}
 
export default nextConfig

unauthorizedサーバーコンポーネントサーバーアクション、およびルートハンドラー内で呼び出すことができます。

app/dashboard/page.tsx
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
 
export default async function DashboardPage() {
  const session = await verifySession()
 
  if (!session) {
    unauthorized()
  }
 
  // Render the dashboard for authenticated users
  return (
    <main>
      <h1>Welcome to the Dashboard</h1>
      <p>Hi, {session.user.name}.</p>
    </main>
  )
}

豆知識

未認証ユーザーへのログインUI表示

unauthorized関数を使用して、ログインUIを持つunauthorized.jsファイルを表示できます。

app/dashboard/page.tsx
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
 
export default async function DashboardPage() {
  const session = await verifySession()
 
  if (!session) {
    unauthorized()
  }
 
  return <div>Dashboard</div>
}
app/unauthorized.tsx
import Login from '@/app/components/Login'
 
export default function UnauthorizedPage() {
  return (
    <main>
      <h1>401 - Unauthorized</h1>
      <p>Please log in to access this page.</p>
      <Login />
    </main>
  )
}

サーバーアクションによるミューテーション

認証済みユーザーのみが特定のミューテーションを実行できるように、unauthorizedをサーバーアクションで呼び出すことができます。

app/actions/update-profile.ts
'use server'
 
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
import db from '@/app/lib/db'
 
export async function updateProfile(data: FormData) {
  const session = await verifySession()
 
  // If the user is not authenticated, return a 401
  if (!session) {
    unauthorized()
  }
 
  // Proceed with mutation
  // ...
}

ルートハンドラーによるデータフェッチ

認証済みユーザーのみがエンドポイントにアクセスできるように、ルートハンドラーでunauthorizedを使用できます。

app/api/profile/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
 
export async function GET(req: NextRequest): Promise<NextResponse> {
  // Verify the user's session
  const session = await verifySession()
 
  // If no session exists, return a 401 and render unauthorized.tsx
  if (!session) {
    unauthorized()
  }
 
  // Fetch data
  // ...
}

バージョン履歴

バージョン変更点
v15.1.0unauthorizedを導入。