Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Express Session in Cookie

I have found various ways to store a session ID in a cookie for expressjs. What I actually want is to store all my session data in a cookie and not have to worry about a server-side session store.

Why? My session data is tiny and having a session store adds unnecessary complexity in my case.

Can this be done with express? Bonus points if you know how to encrypt it.

like image 795
Nik Avatar asked Aug 17 '15 14:08

Nik


1 Answers

Express cookie-session should do what you are wanting.

var cookieSession = require('cookie-session');
var express = require('express');
var app = express();

app.use(cookieSession({
  secret: 'secret-key-you-don\'t-tell-the-client',
  signed: true,
}));

Using a combination of the secret key and ensuring your cookies are signed will prevent any cookie tampering by your end users.

Once setup you can then access the session using the req.session object in your controllers or use a compatible authentication module such as Passport.

like image 97
oznu Avatar answered Oct 13 '22 09:10

oznu