跳到主要內容
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>
  )
}

要知道的好資訊

範例

向未驗證的使用者顯示登入 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