unauthorized.js
experimental
unauthorized.js 特殊文件的 API 参考。
当调用 unauthorized 函数时,unauthorized 文件会渲染 UI。
在流式传输开始之前,Next.js 返回 401 状态码。流式传输开始后,状态码保持为 200,并在响应中渲染未经授权的 UI。在这两种情况下,Next.js 都会注入一个 <meta name="robots" content="noindex" /> 标签。详情请参阅状态码。
app/unauthorized.tsx
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>
)
}app/unauthorized.js
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。
小知识:Next.js 会将每个
unauthorized.js文件与其段下的每个路由一起发送,即使从未调用unauthorized(),并在这些页面上加载它导入的 Client Component。在那里请优先使用 Server Component 和<Link>,而不是交互式 UI。
示例#
向未经身份验证的用户显示登录 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/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 <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>
)
}app/unauthorized.js
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。 |