unauthorized.js
unauthorized 文件用于在身份验证过程中调用 unauthorized
函数时渲染 UI。除了允许你自定义 UI 外,Next.js 还会返回 401
状态码。
app/unauthorized.tsx
TypeScript
import Login from '@/app/components/Login'
export default function Unauthorized() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>Please log in to access this page.</p>
<Login />
</main>
)
}
参考
Props
unauthorized.js
组件不接受任何 props。
示例
向未认证用户显示登录 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>
)
}
版本历史
版本 | 变更 |
---|---|
v15.1.0 | 引入 unauthorized.js 。 |