Browser Not Storing Cookies React & ExpressJS

22 Views Asked by At

I am having an issue retrieving cookies i sent from the server, my unsigned cookies are sent parsed the cookies parser middleware in express, This issue doesn't occur when using postman

This is a login route to create new cookies:

app.post("/login", validate(userLoginSchema), async (req, res) => {
  const user: any = await UserModel.findOne({ email: req.body.email })
    .populate({ path: "friends" })
    .exec();
  if (user) {
    const authenticated = await bcrypt.compare(
      req.body.password,
      user.password
    );

    if (authenticated) {
      const jwtToken = jwt.sign({ id: user.id }, JWT_TOKEN);
      res.cookie("jwtToken", jwtToken, {
        maxAge: JWT_MAX_AGE,
        // httpOnly: false,
        secure: true,
        sameSite: "none",
        domain: "https://localhost:3000",
      });
      res.json({
        message: "Login Successfully",
        data: _.pick(user, dataToSend),
      });
      return;
    }
  }
  res.status(403).send("Invalid Email or Password (Unauthorized)")
});

app.get("/auto-login", async (req, res, next) => {
  console.log("cookies ", req.cookies, req.headers.cookie);
  const jwtToken = req.cookies.jwtToken as string;
  try {
    if (!jwtToken) throw new Error("User Token Isn't present");
    let userData = jwt.verify(jwtToken, JWT_TOKEN) as { id: string };
    const user = await UserModel.findById(userData.id)
      .populate({ path: "friends" })
      .exec();
    if (!user) throw new Error("Invalid User Id");
    res
      .status(201)
      .json({ message: "Successful", data: _.pick(user, dataToSend) });
  } catch (err: any) {
    res.status(401).send("Unauthenticated");
    return;
  }
});

My React app

const url = new URL("/users/auto-login", BASE_URL);
      const response = await fetch(url, {
        method: "GET",
        credentials: "include",
      });
      console.log("headers", response.headers);
      if (OK_RESPONSES.includes(response.status)) {
        setSignIn(true);
      } else {
        messageApi?.error("Not LoggedIn", 3);
        navigate("/login");
      }

And if you are wondering why i am using https for the domain, it's because of the sameSite:'none' policy, that requires it's secure, so i used the mkcert tool to create a certificate to enable server run in https, but my browser reports the server isn't secure though:

const server = https.createServer(
  {
    key: fs.readFileSync(`./cert/localhost-key.pem`, "utf8"),
    cert: fs.readFileSync(`./cert/localhost.pem`, "utf8"),
  },
  app
);
server.on("connection", () => {
  console.log("Server is running on https://localhost:3000");
});
await server.listen(3000);

i did this after trying to work with only the http protocol. but to no avail.

 res.cookie("jwtToken", jwtToken, {
        maxAge: JWT_MAX_AGE,
        secure: false,
        sameSite: "lax",
        domain: "http://localhost:3000",
      });

On checking the headers in my developer tools, in edge

Network Headers

I see the Set-Cookie header sent as expected, but it isn't stored in my application > storage > cookies. Application Storage

I have tried running my react app, on netlify https://parcelshare.netlify.app/login , which will support https directly, still using my local express server https://localhost:3000, but it still gives the same issue when i check the network tab, and the stored cookies. I have also tried a recommendation of going to the server route in your browser, with a simple get request, to check the application storage if the cookies are stored, i didn't find any cookie. Please help, Thanks in advance.

0

There are 0 best solutions below