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.
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.
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:
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.