跳到内容
API 参考函数unauthorized

unauthorized

此功能目前处于实验阶段,可能会有所更改,不建议用于生产环境。欢迎试用并在 GitHub 上分享您的反馈。

unauthorized 函数会抛出一个错误,该错误会渲染 Next.js 的 401 错误页面。它对于处理应用程序中的授权错误非常有用。您可以使用 unauthorized.js 文件自定义 UI。

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

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  experimental: {
    authInterrupts: true,
  },
}
 
export default nextConfig

unauthorized 可以在 服务器组件服务器操作路由处理程序 中调用。

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()
  }
 
  // Render the dashboard for authenticated users
  return (
    <main>
      <h1>Welcome to the Dashboard</h1>
      <p>Hi, {session.user.name}.</p>
    </main>
  )
}

须知

  • unauthorized 函数不能在根布局中调用。

示例

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

使用服务器操作进行修改

您可以在服务器操作中调用 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()
 
  // If the user is not authenticated, return a 401
  if (!session) {
    unauthorized()
  }
 
  // Proceed with mutation
  // ...
}

使用路由处理程序获取数据

您可以在路由处理程序中使用 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> {
  // Verify the user's session
  const session = await verifySession()
 
  // If no session exists, return a 401 and render unauthorized.tsx
  if (!session) {
    unauthorized()
  }
 
  // Fetch data
  // ...
}

版本历史

版本更改
v15.1.0引入了 unauthorized