Search code examples
javascriptnode.jsfetchexpress-session

Express sessionID changes on every client's request


My problem: When I go to server adress (so I'm using get method) it is working as I would want it to work, the sessionID doesn't change upon HTTP requests, but when I'm using client's fetch method to get to the server adress, the sessionID always changes and that is defect, what I don't want.

Any ideas why this is happening and how could I fix it?

Code of how my sessions are set up:

const session = require('express-session');

...

app.set("trust proxy", 1);
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    saveUninitialized: true,
    resave: false,
    cookie: {
      secure: false,
      sameSite: true,
    },
  })
);

...

app.get("/lobby/:id", (req, res) => {
  console.log(req.sessionID);
  req.session.test = 1;
});

Client's request

useEffect(() => {
  fetch(getServerAdress() + "/lobby/" + code, {
    method: "GET",
  })
    .then((response) => response.json())
    .then((data) => setLoading(false))
    .catch(() => setLoadingText("Failed to join the lobby"));
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Solution

  • As Mat J. said, fetch does not send cookies for cross-origin by default, so I had to change it:

    fetch(getServerAdress() + "/lobby/" + code, {
        method: "GET",
        credentials: "include",
    }
    

    Also I had to enable credentials and origin for CORS on my server:

    const cors = require("cors");
    app.use(cors({ credentials: true, origin: true }));