What exactly does the "saveUninitialized", "resave" and "roll" properties mean in express sessions?

Recently, I’m learning about an intermediate β€œexpress session” of an expression, I want to understand all the properties in these options. But when I read about the express-session API, I am confused by three

properties: saveUninitialized , resave and rolling .

All of them affect the setting of cookies or session work, and what is the difference and connection with them?

Hope someone can help me distinguish them,

Thanks a lot!

+5
source share
1 answer

When a modern browser makes a request, it adds all cookies that match the current domain (website) in the Cookie header. Here is an example of what my browser can send if I am at stackoverflow.com:

Cookie: acct=1234

The browser is not sent when you first visit the site. In this case (and if the owner wanted to use cookies to track user sessions, for example), the server will usually respond with a Set-Cookie header, something like this:

Set-Cookie: acct=5678; expires=Sat, 15 May 2050 15:32:57 GMT; domain=.stackoverflow.com

(It can also add path , secure and HttpOnly parameters, all explained here ) I simplify it, but by default express-session sends a Set-Cookie when you visit the site for the first time.

If rolling is true , it will be sent every time. This has the desired side effect of continuously rolling forward the cookie expiration on every page refresh. The new expiration date is determined by adding maxAge to the current server time.

If you modify the req.session object, it will be saved back to the session store at the end of the request; otherwise it will not be saved. Setting resave to true forces it to be saved every time, even if no changes have been made. This may seem counterintuitive, but some stores may require it (although looking at the list, it seems that it is not currently available).

When a cookie is set for the first time, a new session object is created in memory and stored in the storage at the end of the request. This can take up a lot of space in db if you have a lot of people visiting and then bouncing around without performing any meaningful actions such as logging in. You can only save sessions if they deviate from the default session object (i.e., change it, for example, setting req.session.user = user; at login) by setting saveUninitialized to false .

Something to be aware of is that certain combinations of these values ​​(along with others) can lead to unexpected behavior. For example, the documentation states:

If this [roll] option is set to true, but saveUninitialized is set to false, the cookie will not be set in response to an uninitialized session.

+7
source

Source: https://habr.com/ru/post/1240660/


All Articles