Express-session

Hello, I have few questions regarding express-session middleware. Here is my code:

app.use(
  session({
    secret: 'keyboard cat',
    saveUninitialized: false,
    resave: false,
  })
);

app.get('/', (req, res) => {
  console.log(req.sessionID);
  res.render('index');
});

I noticed that everytime I’m hitting the '/' route the server is console.logging another session ID each time. However when I’m attaching something to req.session like this:

  req.session.dbId = user.id;

Server is console.logging the same session ID after each request. Also after checking Appliaction info in Chrome Dev Tools I noticed that cookie is created (after attaching this dbId to req.session). So here are my questions:

  1. Why cookie was not set at the beggining when I didn’t attach anything to req.session?
  2. Why attaching something to req.session cause express-session to create cookie?

try to use saveUninitialized: true

1 Like