Something I don't understand about the express session middleware is the reassignment of sessions. E.g. When someone opens my page for the first time, the middleware will create a fresh new session for that user, the user registers an account, and we create an association between these login credentials and the session by e.g. having a second database table (besides the middleware required one).
Now if that user opens the page again, a new session is created, then the user logs in and we can see that he already has a session. So now, do we have to destroy the new session and assign the actual one to the request object? If not, I can imagine a lot of not used session will be in the middleware db table.
Why does the middleware immediately create a new session on request? Is something like a login or codeword needed to reassign sessions? How exactly does the reassignment of sessions work?
Express-session works off a client-side cookie. Whenever it receives an incoming request, it checks to see if there's a session cookie coming from the client. If there is, it finds the session object in its session store that corresponds to the id in that session cookie and that becomes the req.session
object and no new session is created.
If there is no session cookie with the incoming request or if the id in the session cookie does not correspond with a session object in the session store, then Express will create a new session object for that request.
If a user logs in from scratch (because they don't have an existing session cookie), then express-session will create a new session object and you may put some things in that new session object when the user's credentials are validate and thus you know their identify in your system.
If a user logs in from scratch and they happen to have an existing session cookie, then express-session will use the pre-existing session object from the session store. When you validate their credentials, you can then re-initialize the session object, the same as you would do in the previous paragraph.
Why does the middleware immediately create a new session on request?
It only creates a new session if there's no valid session cookie that's part of the incoming request.
Is something like a login or codeword needed to reassign sessions?
It's not clear to me what you mean by "reassign sessions". When a user logs in, you should just initialize whatever session express-session has for this request. That may or may not be a new session, depending upon whether the client supplied a valid session cookie. Either way, you just do the same thing and initialize whatever you want in the session object for that user.