0

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?

1 Answers1

0

Does the answer here helps? Express doesn't set a cookie

  • If using fetch:

If you do not specify credentials: 'include' in fetch options, cookies are neither sent to server nor saved by a browser, although the server response sets cookies.


return fetch('/your/server_endpoint', {
    method: 'POST',
    mode: 'same-origin',
    redirect: 'follow',
    credentials: 'include', // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({
        first_name: 'John',
        last_name: 'Doe'
    })
})

  • If using axios: should set withCredentials to true
axios.defaults.withCredentials = true;