Custom error messages on signIn callback, next-auth v5
Answered
Smalandstövare posted this in #help-forum
SmalandstövareOP
Hi, is it possible to return custom messages back when I return false in the signIn callback? I'm using nextauth v5, and the app router, and using google oauth
async signIn({ user, account }) {
await connectDB();
const userExists = await User.findOne({ email: user.email });
if (!userExists) {
try {
const newUser = await User.create({
email: user.email,
provider: account.provider,
});
return true; // Return true if user is successfully created
} catch (error) {
return false; // how can i add an error message to pass onto the frontend?
}
}
}Answered by B33fb0n3
Iirc you can use next-auth errors to display a proper message. You might want to look at this: https://next-auth.js.org/configuration/pages
3 Replies
@Smalandstövare Hi, is it possible to return custom messages back when I return false in the signIn callback? I'm using nextauth v5, and the app router, and using google oauth
js
async signIn({ user, account }) {
await connectDB();
const userExists = await User.findOne({ email: user.email });
if (!userExists) {
try {
const newUser = await User.create({
email: user.email,
provider: account.provider,
});
return true; // Return true if user is successfully created
} catch (error) {
return false; // how can i add an error message to pass onto the frontend?
}
}
}
you can throw an error and add a specific message to it like:
Keep in mind, that your frontend should catch the error and display it correctly
// ...
} catch (error) {
throw new Error(error.message ?? "Wrong credentials")
}Keep in mind, that your frontend should catch the error and display it correctly
SmalandstövareOP
When I do that, it directs me to
/api/auth/error?error=AccessDenied and shows the custom message in just the console. How can I see the message, possibly in the url?@Smalandstövare When I do that, it directs me to `/api/auth/error?error=AccessDenied` and shows the custom message in just the console. How can I see the message, possibly in the url?
Iirc you can use next-auth errors to display a proper message. You might want to look at this: https://next-auth.js.org/configuration/pages
Answer