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>
)
}
豆知識
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>
)
}
サーバーアクションによるミューテーション
認証済みユーザーのみが特定のミューテーションを実行できるように、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.0 | unauthorized を導入。 |
この情報はお役に立ちましたか?