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 nextConfigunauthorizedはServer Components、Server Actions、およびRoute Handlersで呼び出すことができます。
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>
)
}Good to know
unauthorized関数は、ルートレイアウトでは呼び出すことができません。
例
未認証ユーザーへのログイン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>
)
}Server Actions を使用したミューテーション
Server Actions で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
// ...
}Route Handlers を使用したデータ取得
unauthorizedをRoute Handlersで使用することで、認証されたユーザーのみがエンドポイントにアクセスできるようにすることができます。
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.0 | unauthorizedが導入されました。 |
役に立ちましたか?