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 可以在 伺服器元件、伺服器操作 和 路由處理程式 中呼叫。
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。 |
這有幫助嗎?