I am trying to validate a cookie using cookie-parser
to check if the user is authenticated to access to restricted routes in my app. I am using NodeJS and Express for the server, and Sveltekit for the frontend.
I've set the cookie when creating the user, and it is saved correctly in the headers (as I can see it on the Request Headers from the network in the Dev Tools), but when I try to access to the cookie from my Express Middleware, it returns undefined, and req.cookies
returns an empty object.
Here is how I set the cookie when the user is authenticated:
// create jwt and cookie
const jwToken = jwt.sign({ id: user._id }, JWT_SECRET);
return res
.cookie("authToken", jwToken, {
httpOnly: true,
})
.status(200)
.json({
loggedIn: true,
message: "Email verified successfully",
});
Here is the middleware from which I am trying to access to the cookie:
export const isAuth = async (req, res, next) => {
console.log("token value:", req.cookies?.authToken);
next();
};
Here is my router:
router.get("/is-auth", isAuth, checkIsAuth);
I am using a different domain for frontend and backend, but the request it is accessing to the endpoint correctly (I'm in localhost), so I think is not a CORS issue.
I've tried adding options when setting up the cookie: { // secure: true, // sameSite: "none", // path: "/", httpOnly: true, }
What am I missing?