How to Customize Login Error Pages in NextAuth


Once the signin process is set up with NextAuth, we’ll want to handle user errors. By default, any login errors will be redirected to NextAuth’s default login page with an error message.

We’ll want to redirect NextAuth to our login page at /pages/signin.jsx and show the error message there.

The code snippets in this article require NextAuth.js v4. Check out how to upgrade to version 4.

// pages/api/[...nextauth].js
export default NextAuth({
  ...
  pages: {
    ...
    error: '/signin', // Error code passed in query string as ?error=
  }
});

Inside /pages/signin.jsx, we can obtain an error code from useRouter(). If there’s no error, this value will be undefined.

Using error, we can conditionally render some error component, which we’ll call SignInError.

// pages/signin.jsx
import { getProviders } from "next-auth/react"
import { useRouter } from "next/router";
const SignIn = ({ providers }) => {
  const { error } = useRouter().query;
  return (
    <>
      <h1>Login</h1>
      {/* Error message */}
      {error && <SignInError error={error} />}
      {/* Login options */}
      {Object.values(providers).map((provider) => (
        <div key={provider.name}>...</div>
      ))}
    </>
  );
};
export async function getServerSideProps(context) {
  return { props: { providers: await getProviders() } };
}

This error component will take in the error code from the router.

These error codes can lead to numerous error messages shown in errors.

// pages/signin.jsx
const errors = {
  Signin: "Try signing with a different account.",
  OAuthSignin: "Try signing with a different account.",
  OAuthCallback: "Try signing with a different account.",
  OAuthCreateAccount: "Try signing with a different account.",
  EmailCreateAccount: "Try signing with a different account.",
  Callback: "Try signing with a different account.",
  OAuthAccountNotLinked:
    "To confirm your identity, sign in with the same account you used originally.",
  EmailSignin: "Check your email address.",
  CredentialsSignin:
    "Sign in failed. Check the details you provided are correct.",
  default: "Unable to sign in.",
};
const SignInError = ({ error }) => {
  const errorMessage = error && (errors[error] ?? errors.default);
  return <div>{errorMessage}</div>;
};

Finally, we can use these errors to print out the error message.

Feel free to style it however you’d like.