Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save data in express session

I would need to save some token in express session. So, I would need help how to save this token in session object. Any example would be more helpful.

Also is it a good practice to save such information in session object or do I need to use some persistent storage like redis cache DB.

like image 893
Abhishek Jain Avatar asked Feb 04 '23 03:02

Abhishek Jain


1 Answers

Yes, you can store a token in the session. This is generally done as follows:

app.use(session({
      token : your_token_value
    })
}));

Or, as an alternative way:

app.get('/', function(req, res, next) {
  var sessData = req.session;
  sessData.token = your_token_value;
  res.send('Returning with some text');
});

Regarding the storage place. It is a kind of a different layer under the session. The values which you store in the session can be placed in different locations: in the application memory, in memcache, a database or in cookies.

For production you can use Memory Cache. For instance, https://github.com/balor/connect-memcached:

It can be achieved as follows:

app.use(session({
      token : your_token_value,
      key     : 'test',
      proxy   : 'true',
      store   : new MemcachedStore({
        hosts: ['127.0.0.1:11211'], //this should be where your Memcached server is running
        secret: 'memcached-secret-key' // Optionally use transparent encryption for memcache session data 
    })
}));
like image 118
Andremoniy Avatar answered Feb 08 '23 12:02

Andremoniy