[Fixed] How do sessions work in Express.js with Node.js?

Issue

Using Express.js, sessions are dead simple. I’m curious how they actually work though.

Does it store some cookie on the client? If so, where can I find that cookie? If required, how do I decode it?

I basically want to be able to see if a user is logged in, even when the user is not actually on the site at the time (like how facebook knows you’re logged in when you’re on other sites). But I suppose to understand that I should first understand how sessions work.

Solution

I have never used Express.js, although according to their documentation on the subject it sounds like:

  • Cookies are stored on the client, with a key (which the server will use to retrieve the session data) and a hash (which the server will use to make sure the cookie data hasn’t been tampered with, so if you try and change a value the cookie will be invalid)

  • The session data, as opposed to some frameworks (e.g. Play Framework!) is held on the server, so the cookie is more like a placeholder for the session than a holder of actual session data.

  • From here, it looks like this session data on the server is by default held in memory, although that could be altered to whatever storage form implements the appropriate API.

So if you want to check things without a specific req request object, like you said, you need to just access that same storage. On the bottom of the first documentation page, it details required methods the storage needs to implement, so if you’re familiar with your storage API, maybe you could execute a .getAll() if something like that exists, and loop through the session data and read whatever values you want.

Leave a Reply

(*) Required, Your email will not be published