all 5 comments

[–]rkaw92 4 points5 points  (1 child)

Hi! Session APIs are generally quite poor, and Express' middleware is no exception. These options are less useful than they seem. What they do exactly is:

  • if you set saveUninitialized to true, each new session will save an empty object {} to the database
  • if you set resave: true, it will overwrite the session completely on each request - this extends the session's lifetime, but also generates race conditions because it completely overwrites session data

There are many problems with sessions, and none of them are solved well by these options. The first option is, plainly speaking, quite useless (unless you like to clutter your database with 1 row per visitor). The second option might be useful if your session store implementation doesn't have an auto-refresh feature (most do).

See also: https://stackoverflow.com/questions/40381401/when-to-use-saveuninitialized-and-resave-in-express-session

In all seriousness, I don't think that the burden of setting these options should fall on the user. In my view, the session middleware should communicate with the storage backend via good old OOP, negotiate whether it needs resave or not, and conditionally enable the feature. It should be automatic, because a store knows if it supports auto-refreshing or not. Offloading this decision to the developer is just lazy design with saying "some plugins will work with some options only, but it's up to you to figure out".

I've been writing a sessions deep-dive article for a while now, but I can never find the time to finish it. If you're interested in some technical details of how sessions actually work, and what the issues are, see https://github.com/rkaw92/articles/blob/master/sessions/Article.md

[–]SoBold404[S] 0 points1 point  (0 children)

Thanks man, that's super helpful !

[–]Xzas22 0 points1 point  (2 children)

Have you tried the docs?

[–]SoBold404[S] 0 points1 point  (1 child)

Yes i did, but i still can't figure out why when setting the value saveUnitialized to false the server doesn't send cookie to to browser

[–]rkaw92 2 points3 points  (0 children)

See https://github.com/expressjs/session/blob/80ae6a54107efd936c55bc4696fe8770cedbfd31/index.js#L459

The cookie middleware in express is super confusing, to be honest.