0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Auth.js+NEXT.sのCredentialでログイン失敗した時のエラー画面をカスタム

Posted at

Auth.js+NEXT.sのCredential(パスワード、メールアドレス)でログイン時にエラーになった時の
エラー画面のカスタム方法を備忘録として残します。

公式のドキュメントでも一応やり方は紹介されてます。
https://authjs.dev/guides/pages/error?framework=next-js

しかし、自分の環境ではうまくいかないところもあったので
どうすればうまくいったかを説明します。

まず、auth.tsにエラーページのルートを定義します。
ルートは自由に設定できます。

auth.ts
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"//emailとパスワードでログインするために使用


export const { handlers, signIn, signOut, auth } = NextAuth({
    providers: [
        Credentials({
            credentials: {
                email: {},
                password: {},
            },
            authorize: async (credentials) => {
      
                // ログイン処理

            },
          }),
    ],
    callbacks: {
        //省略
    },

    //ルートを定義
    pages: {
        error: "/auth/error",
    }
      
})

今回は、"/auth/error"というルートにしました。
app routerでページの表示を行っているので、"/auth/error"にアクセスした際に
カスタムしたページが表示されるようにします。src>appの中にauthディレクトリを作り、
その中にerrorディレクトリを作り、その中にpage.tsxを作成します

このpage.tsxがカスタムエラーページになります。
公式ドキュメントの例を参考に、下記のように作ってみました。

/src/app/auth/error/page.tsx
"use client"
 
import { useSearchParams } from "next/navigation"
 
enum Error {
  Configuration = "Configuration",
}
 
const errorMap = {
  [Error.Configuration]: (
    <p>
        ログイン時に問題が起きました
    </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">
      <div
        className="block max-w-lg 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-rose-600">
          ログインできませんでした
        </h5>
        <div className="font-normal text-gray-700 dark:text-gray-400">
          {errorMap[error] || "Please contact us if this error persists."}
        </div>
      </div>
    </div>
  )
}

以上がエラーページのカスタム方法です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?