Creating sessions without express

Viewed 912

How can I create sessions and manage them in Node.js without a framework like express?

Most of the questions that mentions managing sessions in node is using express to do so but I want to know how to do that without using express.

1 Answers

It's kind of reinventing the wheel. But sometimes it is useful for learning purposes to reinvent the wheel.

Session handling is mainly done through cookies (sometimes also encoded in the URL). In this process, Server sends a unique identifier(cookie) to the client and creates a local file containing the data you stored in the session and in the next request it checks if the unique identifier exists if yes, it matches it with all the saved files if matched it'll pick the file and will read data from that file and then you'll be able to use that session. If the file or the unique ID doesn't exist it'll create an empty file with that unique ID and will send it in the set-cookie header to the client to identify session next time.

Here are some steps you can follow to handle the session:

  1. On receiving a request first check the cookies in the req to find your session cookie.
  2. If it exists, read the unique ID from it and check if the file with that name (unique identifier) exists.
  3. If the file exists, read the object from the file and store it in a local variable named mysession (name it yourself).
  4. If the file or the session cookie doesn't exist, create an empty file with a randomly generated unique identifier. And send this unique identifier in form of session cookie to the client with the help of set-cookie header.

Do all the above stuff before you send any data to the client.

Write the session file with contents of your mysession variable for every modification you made to that variable.

Related