Express nodejs session cookies: req.cookies['connect.sid'] is not generated and req.sessionID is different after each refresh

Issue

I use express 4.13.3 and express-session 1.11.3. Here my configuration session:

app.use( session({/*store: new redis_store,*/name: 'connect.sid', secret: 'azerty is qwerty', resave: false, saveUninitialized: false, cookie:{httpOnly: false, secure: false, maxAge: null}}) );

Here I print req.cookies['connect.sid'] and req.sessionID :

app.get("/", function (req, res) {
  console.log(req.sessionID);
  console.log(req.cookies['connect.sid']);

  res.sendStatus(200);
});

On each refresh req.sessionID is different and req.cookies['connect.sid'] is undefined. Some months ago, as req.sessionID was changing at refresh, I decided to use req.cookies['connect.sid'] and it was working like a charm. Today I checked my code and I notice that connect.sid doesn’t exist anymore in the cookie.

So what is the problem? How I can use the session id of the cookie?

Solution

req.session.id is the same as req.sessionID and req.session.cookie is the session config object.

After some tests I concluded that, if you want to access req.cookies['connect.sid'], you need to use manually the session. For example, you can write req.session.i = 1 or whatever. Then the id connect.sid will be visible in your navigator (using Chrome Dev Tools for instance). Moreover, if you want that req.sessionID stays the same, you must not forget to call res.sendStatus(200) or another response at the end of the function.

But one problem persists. Look at this code:

app.post("/upload-files", upload.array('files'), function (req, res, next) { 
    if(!req.session.i) req.session.i = 0;
    ++req.session.i;
    console.log("i: " + req.session.i);
}

Here I send a post request with an array of files using multer. As multer doesn’t work with names of the form "files[]" (see multer-not-accepting-files-in-array-format-gives-unexpected-filed-error-used), I am obliged to send the files one by one. Here the problem occurs: the variable i will not persist and will stay equal to 1.

I think that they are some bugs.

Answered By – Thomas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published