I'm trying to understand express-session, and I'm still new to Express.
From the Express docs, I learned that when I write:
app.use(middleware1);
app.use(middleware2);
The middleware functions are executed in the order they are registered.
So middleware1 runs before middleware2.
My question is: if express-session is registered at the top, how is it still able to detect changes I make to req.session later?
How does it know that I have modified req.session, so that it can update the session store?
When you create the expression session middleware, you actually get back a function that implements the middleware express calls (see https://github.com/expressjs/session/blob/v1.18.2/index.js#L179). Note that this function's signatue takes req (the request object), res (the response object) and next (the next middleware to call after the express session middleware is done processing the request.
When this middleware is called, it overwrites the response's end function (see https://github.com/expressjs/session/blob/v1.18.2/index.js#L258), and adds, among other things, some logic to save the session (see https://github.com/expressjs/session/blob/v1.18.2/index.js#L343).
So, in short, a simplified example of of the flow would be as follows:
req.session.req.endreq.session.req.end will be called. This is actually the function that was overriden in 2.2. It does whatever needs to be done with req.session (that may have been modified by other middlewares), and then delegates to the original end method to actually send out the response.