NNext.js 中文网 GitHub

unauthorized

experimental

unauthorized 函数的 API 参考。

unauthorized 函数会抛出一个错误,从而渲染未授权 UI。当请求未登录时,它可用于处理身份验证错误。你可以使用 unauthorized.js 文件自定义该 UI。

调用 unauthorized() 会抛出 NEXT_HTTP_ERROR_FALLBACK;401 错误,并终止抛出该错误的路由段的渲染。Next.js 还会注入一个 <meta name="robots" content="noindex" /> 标签,使该页面不被索引。由于它依靠抛错来工作,请在渲染路径中调用它:在组件中,或在组件 await 的函数中。留在未被 await 的 promise 中的调用会在无人捕获的地方抛出,且不会渲染未授权 UI。

要开始使用 unauthorized,请在 next.config.js 文件中启用实验性的 authInterrupts 配置选项:

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 可以在 Server Components、Server Functions 和 Route Handlers 中调用。

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>Welcome to the Dashboard</h1>
      <p>Hi, {session.user.name}.</p>
    </main>
  )
}

小知识#

  • unauthorized 函数不能在根布局中调用。
  • 你无需编写 return unauthorized()。它会抛出(其 TypeScript never 返回类型),因此执行会停止。在调用周围加上 try/catch 会抑制中断,且不会渲染未授权 UI。使用 unstable_rethrow 让它继续传播。
  • 留在未被 await 的 promise 中的 unauthorized() 会在无人捕获的地方抛出,因此不会渲染未授权 UI。在开发环境中,服务器会记录 ⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;401。务必 await 可能调用它的函数。

示例#

在流式渲染开始后调用 unauthorized()#

要在验证会话期间保持页面外壳和加载 UI 可见,请将身份验证检查放在加载数据的数据访问层函数中,并在包裹于 <Suspense> 的组件中渲染它。检查在边界内运行,因此当会话解析时,外壳会以流式传输:

app/account/page.tsx
import { Suspense } from 'react'
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'

async function getAccount() {
  const session = await verifySession()
  if (!session) {
    unauthorized()
  }
  return db.accounts.findByUserId(session.userId)
}

async function AccountDetails() {
  const account = await getAccount()
  return <p>Signed in as {account.email}</p>
}

export default function AccountPage() {
  return (
    <main>
      <h1>Account</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <AccountDetails />
      </Suspense>
    </main>
  )
}
app/account/page.js
import { Suspense } from 'react'
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'

async function getAccount() {
  const session = await verifySession()
  if (!session) {
    unauthorized()
  }
  return db.accounts.findByUserId(session.userId)
}

async function AccountDetails() {
  const account = await getAccount()
  return <p>Signed in as {account.email}</p>
}

export default function AccountPage() {
  return (
    <main>
      <h1>Account</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <AccountDetails />
      </Suspense>
    </main>
  )
}

当请求未登录时,getAccount 调用 unauthorized(),从而抛出错误。由于这发生在渲染期间,异常会传播到最近的 unauthorized 边界,该边界会替代流式传入的内容进行渲染,即使页面外壳已经发送。

在路由旁添加 unauthorized.tsx 来定义该 UI:

app/account/unauthorized.tsx
import Link from 'next/link'

export default function Unauthorized() {
  return (
    <main>
      <h1>401 - Unauthorized</h1>
      <p>
        Please <Link href="/login">sign in</Link> to view your account.
      </p>
    </main>
  )
}
app/account/unauthorized.js
import Link from 'next/link'

export default function Unauthorized() {
  return (
    <main>
      <h1>401 - Unauthorized</h1>
      <p>
        Please <Link href="/login">sign in</Link> to view your account.
      </p>
    </main>
  )
}

响应在 unauthorized() 运行之前就从 <Suspense> 边界开始流式传输,因此它保持 200 状态。Next.js 会添加 noindex 标签。

unauthorized() 在响应开始之前运行时会返回 401,包括在预渲染期间。请参阅状态码。

向未认证用户显示登录 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>
  )
}

使用 Server Actions 进行数据变更#

你可以在 Server Actions 中调用 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()

  // 如果未认证,渲染最近的 unauthorized 边界
  if (!session) {
    unauthorized()
  }

  // 继续执行变更
  // ...
}
app/actions/update-profile.js
'use server'

import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
import db from '@/app/lib/db'

export async function updateProfile(data) {
  const session = await verifySession()

  // 如果未认证,渲染最近的 unauthorized 边界
  if (!session) {
    unauthorized()
  }

  // 继续执行变更
  // ...
}

使用 Route Handlers 获取数据#

你可以在 Route Handlers 中使用 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> {
  // 验证用户的会话
  const session = await verifySession()

  // 如果会话不存在,返回空的 401 响应
  if (!session) {
    unauthorized()
  }

  // 获取数据
  // ...
}
app/api/profile/route.js
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'

export async function GET() {
  const session = await verifySession()

  // 如果用户未认证,返回空的 401 响应
  if (!session) {
    unauthorized()
  }

  // 获取数据
  // ...
}

版本历史#

版本变更
v15.1.0新增 unauthorized。
Next.js 中文网