-1

Am trying to create a simple blog project to understand nodejs and I would like to be able to authenticate users and store their ids in sessions like $_SESSION for PHP. Is this possible in vanilla nodejs? If yes? How do you start a session, how do you end it and how do you save data in the session?

I have currently tried to search all the results I get are related to expressjs (express-session)

iamafasha
  • 848
  • 10
  • 29
  • May be a duplicate of https://stackoverflow.com/questions/34838983/session-management-in-nodejs – Nigel Ren May 03 '21 at 11:52
  • PHP sessions have a very simple design, all work goes to the endless implementation details. But I'm afraid your question is extremely broad. To keep it suitable to be answered here, perhaps you can edit it and boil it down to some specific detail you're stuck with. – Álvaro González May 03 '21 at 12:07

1 Answers1

0

The basic logic for handling sessions is:

  • Create a place to put the data for all the sessions. e.g. an object in memory or a database.
  • Pick a cookie name to store session IDs in
  • If a request comes in with no cookie of that name:
    • Generate a unique id
    • Create a space with that ID as its name in the store
    • Set the cookie with the given name and ID
  • If a request comes in with a cookie of that name:
    • Read the data associated with that ID from the store

Then you need to expire old sessions to clean up their data, and add error checking for when a request for a non-existent session comes in. You'll probably want to enhance security by restricting access to a session to the IP address that originally created it. Etc.

This is a bunch of work. The reason you keep finding Express related results is because it is a solved problem so you can use Express and a session middleware and not have to reinvent this wheel.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335