Search code examples
node.jsfetchexpress-session

req.session is not persistent on browser?


So I have a very typical query.

I am new to this and I am building a simple login web app using node and express-session which are stored in MongoDB.

Here is my code:

sessionRouter.post("", async(req, res) => {
  try {
    const user = await User.findByCredentials(
      req.body.email,
      req.body.password
    );


    if (user) {
      const sessionUser = sessionizeUser(user);

      req.session.user = sessionUser;

      console.log(req.session.id);
      res.send(req.session.user);
    } else {
      throw new Error("invalid details.");
    }
  } catch (e) {
    res.status(400).send(e);
  }
});

//route to logout
sessionRouter.delete("", ({
  session
}, res) => {
  try {
    const user = session.user;

    if (user) {
      console.log(session.id);
      session.destroy((err) => {
        if (err) console.log(err);
        res.clearCookie(process.env.SESS_NAME);
        res.send(session.id);
      });
    } else {
      throw new Error("Something went wrong");
    }
  } catch (err) {
    console.log("things went wrong!");
    //res.status(422).send(JSON.stringify(err));
  }
});

I am storing a 'user' attribute to req.session when I call the login API but when I call the logout API it generates a totally new session!.

Things go smoothly when I use postman to call these endpoints but when using a browser nothing works.

These are the calling functions I am using in browser:

const loggerin = () => {
  var myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");
  myHeaders.append("Connection", "keep-alive");

  var raw = JSON.stringify({
    email: "xxxxxxxxxx",
    password: "xxxxxx",
  });

  var requestOptions = {
    method: "POST",
    headers: myHeaders,
    body: raw,
    redirect: "follow",
  };

  fetch("http://localhost:3001/api/session", requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};

const loggerout = () => {
  var myHeaders = new Headers();

  myHeaders.append("Content-Type", "text/plain");
  myHeaders.append("Connection", "keep-alive");

  var requestOptions = {
    method: "DELETE",
  };

  fetch("http://localhost:3001/api/session", requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};

const test = () => {
  var myHeaders = new Headers();

  myHeaders.append("Content-Type", "text/plain");
  myHeaders.append("Connection", "keep-alive");

  var requestOptions = {
    method: "GET",
  };

  fetch("http://localhost:3001/api/session", requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};

Please help!!! Thanks in advance!


Solution

  • The issue was that I was creating the session in the wrong function. I corrected that and it worked.