自訂錯誤頁面
當使用者驗證流程(登入、登出等)發生錯誤時,可以設定 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 會將使用者重新導向至我們的自訂錯誤頁面
