I have noticed that in order to store a value into the session you simply call req.session.key = value without the need to specify a callback. I have set mysql as my session storage adapter using the connect-mysql module. So I am wondering that consider each time I save a value to the session it is being updated in the db, shouldn't there be a callback associated with this? Yet everywhere I look people are happily using it synchronously. Can someone please explain why this is the case? THanks.
1 Answer
The session middleware only actually interacts with the data-store twice per request, rather than immediately with each change:
- With
Store#get()to retrieve theSessionin bulk at the start of a request. (source) - With
Store#set()(viaSession#save()) to persist theSessionin bulk at the end of the request. (source)
Between these steps, changes to the session can be done synchronously. They just should be done before res.end() or similar (res.render(), res.json(), etc.) is called.
1 Comment
ReneGAED
Thanks that makes perfect sense.