NodeJS cookies do not work with sessions in Express 4

I upgraded the NodeJS app to version 4.0 and now I can’t set my own cookies in addition to the express session cookie. This problem only occurs the first time you request any session, when the user reloads the page where the user cookies are located.

var express = require('express'); var routes = require('./routes'); var http = require('http'); var path = require('path'); var session = require('express-session'); var app = express(); app.set('port', process.env.PORT || 3000); app.use(express.static(path.join(__dirname, 'public'))); app.use(require('body-parser')()); app.use(require('method-override')()); app.use(require('cookie-parser')('cookie-secret')); //app.use(session({ secret: 'secret', key: 'sid'})); //uncomment this to see the problem app.get('/', function(req, res, next) { res.cookie('testing', 'test'); //this isn't set if using 'app.use(session...)' res.send('This is a cookie test'); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); 

To verify: 1. Run the above code, the test cookie will be sent to the browser correctly. 2. Then clear the cookies and uncomment the line "app.use (session ..."). 3. Launch the application and the only cookie is "sid". Where is the "testing"? 4. Reload the page (without clearing cookies) and there will be a "cookie" test.

It is important that all my cookies are on request.

+6
source share
3 answers

This works for me:

 var mw = { favicon: require('static-favicon'), logger: require('morgan'), bodyParser: require('body-parser'), cookieParser: require('cookie-parser'), session: require('express-session'), methodOverride: require('method-override') }; var MongoStore = require('connect-mongo')(mw); app.store = new MongoStore(...); app.use(function(req, res, next) { if ('HEAD' === req.method || 'OPTIONS' === req.method) return next(); var writeHead = res.writeHead; res.writeHead = function() { res.cookie('XSRF-TOKEN', req.session && req.session._csrfSecret); writeHead.apply(res, arguments); }; next(); }); app.use(mw.session({ key: 'yourCookieID', cookie: { maxAge: 3600000 * 24 * 7 }, store: app.store })); 
+3
source

In express-session you are trying to use the key: option, which has been replaced by the name: option. You want to use the genid: parameter to set sid , make sure it is unique (I suggest, uuid version 4). The express-session package will also handle your cookie management.

 // Session create var hour = 3600000; app.use(session({ genid: function(req) { return uuid.v4(); // This comes from the node-uuid package }, secret: 'secret key', cookie: { secure: true, expires: new Date(Date.now() + hour), maxAge: hour }, saveUninitialized: true, resave: true })); 

To access session data:

 req.session 

To access cookies:

 req.session.cookie 
+2
source

This is a known issue. See this GH.

+1
source

All Articles