Doubt in showing the error in client side while using Next-auth
Unanswered
Santhosh Prabhakaran posted this in #help-forum
I'm checking the user credentials with the MongoDB data and authenticating it. The authentication is working fine but if any error, How to show the error in client side ? I'm only getting hte error in console. The code looks like,
import { MongoClient } from "mongodb";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
export const authOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text", placeholder: "Username" },
password: { label: "Password", type: "text", placeholder: "Password" },
},
async authorize(credentials, req) {
try {
const client = await MongoClient.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db("test");
const user = await db
.collection("users")
.findOne({ username: credentials.username });
if (!user) {
throw new Error("User is not found!");
}
const checkPassword = await bcrypt.compare(
credentials.password,
user.password
);
if (!checkPassword) {
throw new Error("Password is incorrect!");
}
return { id: 1, name: user.username };
} catch (error) {
console.log(error);
user.error = error.message;
}
},
}),
],
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };6 Replies
Blanc de Hotot
authOptions is a server component. It will always throw errors on the server. To do what you want, I think you can handle it with an ErrorBoundary (https://nextjs.org/docs/pages/building-your-application/configuring/error-handling#handling-server-errors). Hopefully this helps
But with the ErrorBoundary, we're showing an another component. Instead is there any ways to set the error along with the user object we're sending to client side ?
Blanc de Hotot
You may be able to do this in the Session callback and have the error message be part of the session. Then, if (session.error) render a component
Sorry I don't get it. Could you please explain again or with my code ?
Blanc de Hotot
https://next-auth.js.org/configuration/callbacks
Next-auth provides a number of callbacks that you can read about ^
In the Session callback, you could update an
Next-auth provides a number of callbacks that you can read about ^
In the Session callback, you could update an
error variable that, when changes, will refresh the user's session. Then, in your RootLayout (for example), you could render an error modal containing the error message from the session objectThanks, will try it