Subham
Subham

Reputation: 1465

session management using core node.js without express.js

How to handle/create middleware for server side session management in a core node.js /non express.js project. I can find modules for express based project but not for core node.js. Please suggest me any modules or middleware for non express.js project.

Upvotes: 3

Views: 1404

Answers (1)

Grynets
Grynets

Reputation: 2525

Session management can be implemented via database (MySQL, MongoDB, Redis etc.) or some local cache.
The main logic behind sessions - is object with data.
So you can provide user on first interaction with some random id, like uuid.
And save it to some module, which looks like this:

class OwnSession(){
  constructor(){
   this.sessions = {};
  }

  getUser(sessionId){
   return this.sessions[sessionId];
  }

  setUser(sessionId, userData){
   if(this.sessions[sessionId]){
     Object.assign(this.sessions[sessionId], userData);
     return;
   }

    this.sessions[sessionId] = userData;
  }
}
// We export here new OwnSession() to keep singleton across your project.

module.exports = new OwnSession();

And then, in any module you require OwnSession and call the method.

Upvotes: 3

Related Questions