[Fixed] NextAuth: how to return custom errors without redirection – Javascript

by
Ali Hasan
next-auth next.js node.js reactjs

Quick Fix: Implement a signIn callback to handle custom errors returned by the authorization function. The callback can catch and throw the error, allowing you to display a custom error message on the client side without redirection.

The Problem:

Utilizing NextAuth for user authentication with username and password, how can custom error messages or codes be returned to the client-side without triggering a browser redirection? This is necessary to provide specific error feedback on the client side, such as ‘Invalid email address’, ‘Account blocked’, or ‘Invalid password’, rather than relying on redirection to an error page.

The Solutions:

Solution 1: Implement a signIn Callback

The authorize method allows you to return a custom object. The signIn callback captures this object and handles it. By using this method, you can:

  • Return custom error messages like “Invalid email address,” “Account blocked,” or “Invalid password.”
  • Handle the errors on the client side and display them to the user.

Here’s an example implementation:

// [...nextauth].js
providers: [
  // credentials provider
  CredentialsProvider({
    type: 'credentials',
    credentials: {},

    // authorization function
    async authorize(credentials, req) {
      const { credential, password } = credentials

      if (myCustomCondition) {
        return { error: 'my custom error' };
      }
      return data // success
    }
  })
],
callbacks: {
  async signIn({ user, account, profile, email, credentials }) {
    if (user?.error === 'my custom error') {
      throw new Error('custom error to the client')
    }
    return true
  }
}

On the client side, you can evaluate the error message and act accordingly:

const res = await signIn('credentials', {
  credential: data.credential,
  password: data.password,
  redirect: false
})
if (res?.status == 200) {
  push('/')
} else if(res?.error === 'custom error to the client') {
  // handle this particular error
} else {
  // handle generic error
}

Solution 2: Custom Errors Without Redirection

To return custom errors without redirection when using NextAuth, you can set the redirect option to false in your custom login page. This allows you to handle the response and display the error message on the same page.

Here is the sample code for your login page:

// login.jsx

const [datas, setDatas] = useState({ credential: '', password: '' })

const handleSubmit = async e => {
    e.preventDefault()
    try {
      // siging in
      const res = await signIn('credentials', {
        credential: datas.credential, // can be changed to `email` or `username` or anything else
        password: datas.password,
        redirect: false // this is important
      })
      if (res?.status == 200) {
        push('/')
      } else {
        throw new Error(res?.error)
      }
    } catch (error) {
      console.log(error.message) // error in the provider
    }
}

Additionally, you need to throw custom errors in your providers to handle incorrect credentials or other issues. Here is an example of a provider that throws custom errors:

// [...nextauth].js

providers: [
    // credentials provider
    CredentialsProvider({
        type: 'credentials',
        credentials: {},

        // authorization function
        async authorize(credentials, req) {
            const { credential, password } = credentials

            // admin profile
            let data = { credential : 'test', password: 'abcd' } // replace this

            if (!data) throw new Error('no user found')
            if (data.credential != credential) throw new Error('invalid credentials')

            // comparing the password
            const compared = data.password != password // replace this

            // checking if the password was correct
            if (!compared) throw new Error('invalid credentials')

            return data // success
        }
    })
],

Note: Ensure to check for typos in the code provided.

Q&A

How can custom errors be returned from NextAuth without any client side redirections?

The authorize method can return a custom object, which is caught and handled by the signIn callback, sending custom error messages to the client side.

How to manage custom errors if using custom pages for login instead of next-auth pages?

Set redirect to false when using the signIn function in the login page. Throw errors in the credentials provider which will be caught and displayed on the client side.

Video Explanation:

The following video, titled "Full Stack Authentication with Next-Auth and Next.js 13: All You ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Please Support me by subscribing to this channel https://www.youtube.com/@sakuradev?sub_confirmation=1 In this YouTube video, ...