First off, unless you're building things yourself just because you want to learn how to do it all yourself, there's really no reason to re-invent things that have already been well engineered in existing modules. Because this is server-side code, there's really no penalty for using an already tested module that does what you want. So, my first recommendation would be to use Express and express-session. It does all the session management for you and will give you lots more time to work on the aspects of your project that will really help it succeed or fail.
And, THE top benefit of using node.js in the first place is being able to use the huge library of existing code available through NPM and Github.
Conceptually, here's how a session works in the node.js/web browser client/server world.
- Incoming request from client to web server.
- Server creates some sort of guaranteed unique cookie value and sets that as a cookie on the response.
- Server also creates a serve-side session object and puts that object into some data store with the session cookie value as an index into that data store.
- Now every time a future request arrives from that same client, it will be accompanied with that session cookie.
- On each incoming request, the server can grab the session cookie value, use it as the key to look up the corresponding session object and get it.
- Any request handler can then read data from the session object or write data to the session object.
- In this manner you can keep data associated with a particular client secure and safe on the server and usable from one request to another.
If you're going to implement your own session system, you have to be able to create these unique session cookies and create some sort of session storage (can be anything from a Map object in memory to a database), implement session expiration and session store cleanup and then provide appropriate middleware or utility functions that makes it easy to use on any individual http request.