3

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, Thanks for your response. I got it. But how to calculate the idle time (not the total time spending) of a user so that I can log him out.
@Subham the main idea behind logout after some time is to add timestamp to this user. For example, on every request from user with some session you have to update time field in your user session object. Save it as timestamp. And while you process user request you can verify, if current server timestamp less or more than allowed for user idle and produce some action. Return data or error.
Got it. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.