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
2
Answers
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
On the client side we can evaluate the error message and act accordingly:
If you are not using next-auth pages and using custom pages for your application, you have to set redirect to false in your login page when using
signIn
function, here is an example:and in the providers you have to throw the errors you want to be seen
be careful of typos if I made any