N Next.js 中文
原文 ↗

unauthorized

unauthorized 函数的 API 参考。

更新于 2026-11-06Next.js 16.4.6

此功能目前处于实验阶段,可能会发生变化,不建议用于生产环境。欢迎试用并在 GitHub 上分享你的反馈。

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 配置选项:

TypeScript

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    authInterrupts: true,
  },
}

export default nextConfig

JavaScript

next.config.jsjs
module.exports = {
  experimental: {
    authInterrupts: true,
  },
}

unauthorized 可以在服务器组件、服务器函数和路由处理器中调用。

TypeScript

app/dashboard/page.tsxtsx
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>
  )
}

JavaScript

app/dashboard/page.jsjsx
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 函数不能在根布局中调用。
  • 你无需编写 return unauthorized()。它会抛出错误(其 TypeScript never 返回类型),因此执行会停止。在调用外层包裹 try/catch 会抑制这种中断,且不会渲染未授权的 UI。使用 unstable_rethrow 让它通过。
  • 留在未 await 的 promise 中的 unauthorized() 会在无人捕获的地方抛出,因此不会渲染未授权的 UI。在开发环境中,服务器会记录 ⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;401。务必 await 可能调用它的函数。

示例

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

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

TypeScript

app/account/page.tsxtsx
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>
  )
}

JavaScript

app/account/page.jsjsx
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:

TypeScript

app/account/unauthorized.tsxtsx
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>
  )
}

JavaScript

app/account/unauthorized.jsjsx
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。请参阅状态码。

向未认证用户显示登录界面

你可以使用 unauthorized 函数显示带有登录界面的 unauthorized.js 文件。

TypeScript

app/dashboard/page.tsxtsx
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.tsxtsx
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>
  )
}

JavaScript

app/dashboard/page.jsjsx
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.jsjsx
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,以确保只有已认证用户才能执行特定的变更操作。

TypeScript

app/actions/update-profile.tsts
'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 unauthenticated, render the nearest unauthorized boundary
  if (!session) {
    unauthorized()
  }

  // Proceed with mutation
  // ...
}

JavaScript

app/actions/update-profile.jsjs
'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()

  // If unauthenticated, render the nearest unauthorized boundary
  if (!session) {
    unauthorized()
  }

  // Proceed with mutation
  // ...
}

使用路由处理器获取数据

你可以在路由处理器中使用 unauthorized,以确保只有已认证用户才能访问该端点。

TypeScript

app/api/profile/route.tstsx
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 an empty 401 response
  if (!session) {
    unauthorized()
  }

  // Fetch data
  // ...
}

JavaScript

app/api/profile/route.jsjsx
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'

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

  // If the user is not authenticated, return an empty 401 response
  if (!session) {
    unauthorized()
  }

  // Fetch data
  // ...
}

版本历史

版本 变更
v15.1.0 引入 unauthorized。
  • unauthorized.js:unauthorized.js 特殊文件的 API 参考。
  • notFound:notFound 函数的 API 参考。
  • forbidden:forbidden 函数的 API 参考。
  • authInterrupts:了解如何启用实验性的 `authInterrupts` 配置选项,以使用 `forbidden` 和 `unauthorized`。