Skip to content

unauthorized

unauthorized 函数会抛出错误,并渲染 Next.js 401 错误页面。它对于处理应用中的授权错误很有用。你可以使用 unauthorized.js file 自定义 UI。

¥The unauthorized function throws an error that renders a Next.js 401 error page. It's useful for handling authorization errors in your application. You can customize the UI using the unauthorized.js file.

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

¥To start using unauthorized, enable the experimental authInterrupts configuration option in your next.config.js file:

ts
import type { NextConfig } from 'next'

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

export default nextConfig
js
module.exports = {
  experimental: {
    authInterrupts: true,
  },
}

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

¥unauthorized can be invoked in Server Components, Server Actions, and Route Handlers.

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>
  )
}
jsx
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>
  )
}

很高兴知道

¥Good to know

  • unauthorized 函数无法在 根布局 中调用。

    ¥The unauthorized function cannot be called in the root layout.

示例

¥Examples

向未经身份验证的用户显示登录 UI

¥Displaying login UI to unauthenticated users

你可以使用 unauthorized 函数通过登录 UI 显示 unauthorized.js 文件。

¥You can use unauthorized function to display the unauthorized.js file with a login UI.

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>
}
jsx
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>
}
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>
  )
}
jsx
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>
  )
}

使用服务器操作进行修改

¥Mutations with Server Actions

你可以在服务器操作中调用 unauthorized,以确保只有经过身份验证的用户才能执行特定的修改。

¥You can invoke unauthorized in Server Actions to ensure only authenticated users can perform specific mutations.

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
  // ...
}
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()

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

  // Proceed with mutation
  // ...
}

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

¥Fetching data with Route Handlers

你可以在路由处理程序中使用 unauthorized,以确保只有经过身份验证的用户才能访问端点。

¥You can use unauthorized in Route Handlers to ensure only authenticated users can access the endpoint.

tsx
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
  // ...
}
jsx
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 a 401 and render unauthorized.tsx
  if (!session) {
    unauthorized()
  }

  // Fetch data
  // ...
}

版本历史

¥Version History

版本更改
v15.1.0unauthorized 已引入。

Next.js v15.2 中文网 - 粤ICP备13048890号