I am implementing authentication system using jsonwebtoken and bcryptjs. For backend I am using Nojes + Typescript + Mongodb and for the frontend I am using Nexjs 14. I am basically generating a token a storing it into the cookie when the user is trying to log in. Here you can see my login api.
export const loginUser = async (
req: Request<{}, {}, LoginUser>,
res: Response,
next: NextFunction
) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return next(
new MyErrorClass("Please enter all the required fields", 404)
);
}
const user = await userModel.findOne({ email });
if (!user) {
return next(new MyErrorClass("No user found", 404));
}
const hasshedPassword = await bcrypt.compare(password, user.password);
if (!hasshedPassword) {
return next(new MyErrorClass("Invalid Email or password", 401));
}
const token = jwt.sign(
{
_id: user._id,
},
process.env.SECRET_KEY!
);
return res
.status(200)
.cookie("token", token, {
httpOnly: true,
sameSite: "none",
secure: true,
maxAge: 1 * 24 * 60 * 60 * 1000, // 90days
})
.json({
success: true,
message: `Welcome back ${user.email}`,
});
} catch (error: any) {
return next(new MyErrorClass(error.message, 500));
}
};
Now when in the logout api i am simply putting an empty string in the cookie.
Logout api
export const logoutUser = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
return res
.status(200)
.cookie("token", {
httpOnly: true,
sameSite: "none",
secure: true,
expires: new Date(0),
path: "/"
})
.json({
success: true,
message: `User logged out successfully`,
});
} catch (error: any) {
return next(new MyErrorClass(error.message, 500));
}
};
In the frontend I am getting the message from the server that I have been logged out but the cookie is still there.
I have tried every possible changes that can be made into my api, but still not working. How can I remove the token from my cookie?
In your logoutUser API, make sure that the path property of the cookie you are trying to clear matches the path property used when setting the cookie. By default, cookies are set with the path /, so this should be correct if your login API also sets the cookie with the path /.
In the logoutUser API, you’re using expires: new Date(0), which should theoretically clear the cookie. However, you can also try setting a past expiration date explicitly:
expires: new Date(Date.now() - 3600 * 1000)
Ensure SameSite and Secure Flags Match
The sameSite and secure flags must match between the login and logout requests. Make sure both are set to none for cross-site requests. For secure, it must be true if you are working in HTTPS.