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
unauthorized
はServerコンポーネント、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>
)
}
補足
unauthorized
関数はルートレイアウトでは呼び出せません。
例
未認証ユーザーにログイン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 関数 |