unauthorized
unauthorized 函数抛出一个错误,渲染 Next.js 401 错误页面。它对于处理应用程序中的授权错误很有用。你可以使用 unauthorized.js 文件 自定义 UI。
要开始使用 unauthorized,请在 next.config.js 文件中启用实验性的 authInterrupts 配置选项:
- TypeScript
- JavaScript
next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
authInterrupts: true,
},
}
export default nextConfig
next.config.js
module.exports = {
experimental: {
authInterrupts: true,
},
}
unauthorized 可以在 服务端组 件、服务器操作 和 路由处理器 中调用。
- TypeScript
- JavaScript
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 (
<main>
<h1>Welcome to the Dashboard</h1>
<p>Hi, {session.user.name}.</p>
</main>
)
}
app/dashboard/page.js
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>欢迎来到仪表板</h1>
<p>你好,{session.user.name}.</p>
</main>
)
}
提示
unauthorized函数不能在 根布局 中调用。