跳到主要內容

unauthorized.js

此功能目前為實驗性功能,可能會有所變動,不建議用於生產環境。試用看看,並在 GitHub 上分享您的意見回饋。

當身份驗證期間呼叫 unauthorized 函式時,unauthorized 檔案會用於渲染 UI。除了允許您自訂 UI 之外,Next.js 也會傳回 401 狀態碼。

app/unauthorized.tsx
import Login from '@/app/components/Login'
 
export default function Unauthorized() {
  return (
    <main>
      <h1>401 - Unauthorized</h1>
      <p>Please log in to access this page.</p>
      <Login />
    </main>
  )
}

參考

Props

unauthorized.js 元件不接受任何 props。

範例

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

版本歷史

版本變更
v15.1.0引入 unauthorized.js。