Implementing session functionality to my Node/Express server, I am trying to move away from in-memory sessions, I have decided to use my application database (MySQL) as the session store (as opposed to something specialized like Redis, to reduce complexity).
I am using the following libraries:
The first one is the standard session implementation for sessions in Node/Express applications. While the second one allows us to leverage our application database and ORM to persist session data.
The following snippet is from express-session documentation:
// Access the session as req.session
app.get('/', function(req, res, next) {
if (req.session.views) {
req.session.views
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' req.session.views '</p>')
res.write('<p>expires in: ' (req.session.cookie.maxAge / 1000) 's</p>')
res.end()
} else {
req.session.views = 1
res.end('welcome to the session demo. refresh!')
}
})
Please consider the line:
req.session.views = 1
My question is, is this operation asynchronous? When working with in-memory sessions this might not be an issue, but working over a database connection, as in our case, this will be a bottleneck if it is not async.
CodePudding user response:
The session object is loaded (asynchronously) and set on the request BEFORE it reaches our route/endpoint.
The operation
req.session.views = 1
above only mutates the object in application memory.
Once our route handler sends the response, the session object (along with all of our changes) is persisted on the session store again.