Tanoy B
Tanoy B

Reputation: 41

How to store user data into node js express-session

I'm using express and express-session with mysql on nodeJS. I was able to set a cookie and session also.

Here is my code:

app.use(cookieParser('3CCC4ACD-6ED1-4844-9217-82131BDCB239'));
session({resave: true, saveUninitialized: true, secret: '2C44774A-D649-4D44-9535-46E296EF984F', cookie: { maxAge: 600000 }}));

I can see on browser that a cookie named connect.id has been set. But now I can't understand how to store the user id and username after getting them from a mysql database.

Have googled it but was unable to find a solution. Kindly help me. Thanks!!

Upvotes: 0

Views: 8738

Answers (2)

Ryan
Ryan

Reputation: 443

Here is how you set up a session

const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const store = new MongoDBStore({
  uri: MONGODB_URI,
  collection: 'sessions'
});
app.use(session({
  secret: 'secret string',
  resave: false,
  saveUninitialized: false
  store: store, /* store session data in mongodb */ 
  cookie: { /* can add cookie related info here */ }
}));

In order to store data in the session, you simply do,

req.session.user = user;
req.session.isLoggedIn = true;

Access is the same way. These values will be stored server-side using the session cookie as a lookup value.

Upvotes: 3

Jairo
Jairo

Reputation: 350

You don't store those on cookies, in the first login of that user, you link the cookieID with that username in the database, now every time a user connects, you first look in the database for the cookieID, if it does not exists, then you send the user he needs to login. If there is a register in the database, then you know that is the trusted user.

You can use the username as key so if the same username come with a different cookieID, it is overwrited, anyway it would be good that you save a timestamp in the database too, and delete those registers that have a determined old.

This is basically what a session does, it has an id in the cookie and save variables related to that id, I had bad experiences with the express sessions, so I just prefer to use a cookie and handle the sessions by myself, it is my recommended way.

In node, to get a cookie:

req.cookie.cookieName

And to set a cookie:

res.cookie('cookieName', cookieValue);

Please never save private data in cookieValue as it can be stealth.

Upvotes: 0

Related Questions