unauthorized

unauthorized 函數會拋出錯誤並渲染 Next.js 的 401 錯誤頁面。這個函數在處理應用程式中的授權錯誤時非常有用。您可以透過 unauthorized.js 檔案 來自訂 UI。

要開始使用 unauthorized,請在 next.config.js 檔案中啟用實驗性的 authInterrupts 設定選項:

import type { NextConfig } from 'next'

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

export default nextConfig

unauthorized 可以在伺服器元件 (Server Components)伺服器動作 (Server Actions)路由處理器 (Route Handlers) 中呼叫。

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

須知事項

範例

向未驗證使用者顯示登入 UI

您可以使用 unauthorized 函數來顯示帶有登入 UI 的 unauthorized.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>
}

使用伺服器動作進行變更

您可以在伺服器動作 (Server Actions) 中呼叫 unauthorized 以確保只有已驗證的使用者可以執行特定變更。

'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()

  // 如果使用者未驗證,回傳 401
  if (!session) {
    unauthorized()
  }

  // 繼續執行變更
  // ...
}

使用路由處理器取得資料

您可以在路由處理器 (Route Handlers) 中使用 unauthorized 以確保只有已驗證的使用者可以存取端點。

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> {
  // 驗證使用者的 session
  const session = await verifySession()

  // 如果沒有 session 存在,回傳 401 並渲染 unauthorized.tsx
  if (!session) {
    unauthorized()
  }

  // 取得資料
  // ...
}

版本歷史

版本變更內容
v15.1.0首次引入 unauthorized 函數。

On this page