Search code examples
javascriptnode.jsreactjsnext.jsnext-auth

NextAuth: how to return custom errors without redirection


I have been looking at implementing NextAuth with username and password credentials and I am not finding a way to return custom errors to the client side. It seems that I can only return a 200 ok or a redirection to an error page from the authorize method, where then you could add a custom error to a query string. However that is not a proper solution to my case as I need the client side to simply receive a custom error code or message from the sigIn call.

How do you return custom errors like

"Invalid email address"

"Account blocked"

"Invalid password"

Or any other customization required?

Thanks


Solution

  • I found the solution that I needed by implementing a signIn callback. The authorize method can return a custom object and the signIn callback catches it and handles it accordingly.

    See the documentation here

    // [...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 we 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
      }