Menu

unauthorized

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

unauthorizedを使い始めるには、next.config.jsファイルで実験的なauthInterrupts設定オプションを有効にします:

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

unauthorizedServerコンポーネントServer Actions、およびRouteハンドラで呼び出すことができます。

app/dashboard/page.tsx
TypeScript
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
 
export default async function DashboardPage() {
  const session = await verifySession()
 
  if (!session) {
    unauthorized()
  }
 
  // 認証されたユーザー向けにダッシュボードをレンダリング
  return (
    <main>
      <h1>Welcome to the Dashboard</h1>
      <p>Hi, {session.user.name}.</p>
    </main>
  )
}

補足

未認証ユーザーにログインUIを表示する

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

app/dashboard/page.tsx
TypeScript
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
TypeScript
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>
  )
}

Server Actionsでのミューテーション

Server Actionsでunauthorizedを呼び出して、認証されたユーザーのみが特定のミューテーションを実行できるようにすることができます。

app/actions/update-profile.ts
TypeScript
'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()
 
  // ユーザーが認証されていない場合、401を返す
  if (!session) {
    unauthorized()
  }
 
  // ミューテーションを続行
  // ...
}

Routeハンドラでのデータ取得

Routeハンドラでunauthorizedを使用して、認証されたユーザーのみがエンドポイントにアクセスできるようにすることができます。

app/api/profile/route.ts
TypeScript
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> {
  // ユーザーのセッションを確認
  const session = await verifySession()
 
  // セッションが存在しない場合、401を返しunauthorized.tsxをレンダリング
  if (!session) {
    unauthorized()
  }
 
  // データを取得
  // ...
}

バージョン履歴

バージョン変更点
v15.1.0導入時期:unauthorized関数