Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}, []);
like image 592
Jakub Hampl Avatar asked Nov 17 '25 09:11

Jakub Hampl


1 Answers

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 }));
like image 140
Jakub Hampl Avatar answered Nov 18 '25 21:11

Jakub Hampl