跳至內容
正在從 NextAuth.js v4 遷移嗎?請閱讀 我們的遷移指南.
指南頁面自訂錯誤

自訂錯誤頁面

當使用者驗證流程(登入、登出等)發生錯誤時,可以設定 Auth.js 顯示自訂錯誤頁面。

為了覆寫 Auth.js 的 /api/auth/error 頁面,我們必須在 AuthConfig 中定義我們的自訂頁面

./auth.ts
const authConfig: NextAuthConfig = {
...
  pages: {
    error: "/error",
  }
...
};

使用範例應用程式,讓我們建立一個簡單的自訂錯誤頁面,方法是建立 app/error/page.tsx

app/error/page.tsx
export default function AuthErrorPage() {
  return <>Oops</>
}

Auth.js 會將以下錯誤以 URL 中的錯誤查詢參數的形式轉發到我們的自訂錯誤頁面

查詢參數範例網址描述
組態/auth/error?error=Configuration伺服器組態有問題。請檢查您的選項是否正確。
AccessDenied/auth/error?error=AccessDenied通常發生於您透過 signIn 回呼或 redirect 回呼限制存取時。
Verification/auth/error?error=Verification與電子郵件提供者相關。Token 已過期或已被使用。
Default/auth/error?error=Default全域捕捉,如果以上皆未符合,則會應用此錯誤。

現在我們可以更新我們的自訂錯誤頁面

app/error/page.tsx
"use client"
 
import { useSearchParams } from "next/navigation"
 
enum Error {
  Configuration = "Configuration",
}
 
const errorMap = {
  [Error.Configuration]: (
    <p>
      There was a problem when trying to authenticate. Please contact us if this
      error persists. Unique error code:{" "}
      <code className="rounded-sm bg-slate-100 p-1 text-xs">Configuration</code>
    </p>
  ),
}
 
export default function AuthErrorPage() {
  const search = useSearchParams()
  const error = search.get("error") as Error
 
  return (
    <div className="flex h-screen w-full flex-col items-center justify-center">
      <a
        href="#"
        className="block max-w-sm rounded-lg border border-gray-200 bg-white p-6 text-center shadow hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700"
      >
        <h5 className="mb-2 flex flex-row items-center justify-center gap-2 text-xl font-bold tracking-tight text-gray-900 dark:text-white">
          Something went wrong
        </h5>
        <div className="font-normal text-gray-700 dark:text-gray-400">
          {errorMap[error] || "Please contact us if this error persists."}
        </div>
      </a>
    </div>
  )
}

現在,當發生錯誤時,Auth.js 會將使用者重新導向至我們的自訂錯誤頁面

Custom Error Page
Auth.js © Balázs Orbán 與團隊 -2024