Dalibor Dragojevic
Dalibor Dragojevic

Reputation: 315

Session variables in node express-session don't persist to the next request

I am using a basic node express-session setup with memory store and I have this code on the server:

app.use(require('express-session')({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

app.post('/api/logIn', function(req, res) {
    req.session.userName = req.body.userName;
}

app.get('/api/getProfile', function(req, res) { 
    User.findOne({'userName' : req.session.userName}, 
        function (err, userProfile) {
        console.log('getProfile executed for user:' + req.session.userName);
        if (err) throw err;
        console.log(userProfile);
    });
});

The problem is that req.session.userName from getProfile route is undefined, although it is not in the previous request to logIn route. I inspected HTTP headers and strangely there are no headers dealing with cookies, from the server or from the client. Right now I have no idea what could be the problem.

Upvotes: 2

Views: 2023

Answers (3)

Christian Bartram
Christian Bartram

Reputation: 411

Also its important to note if you are using fetch() to make your API calls to include { credentials: 'include' } in the options of your fetch() call. Otherwise the cookie will not set properly and your session will not persist. Make sure that on your server side you do something like:

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

so that your headers are set properly and cors wont be an issue. Took me awhile to figure this out but its working now!

Upvotes: 1

BrTkCa
BrTkCa

Reputation: 4783

The session need is stored in a cookie, so we use this to parse it, some like this:

var cookieParser = require('cookie-parser');

// must use cookieParser before expressSession
app.use(cookieParser());

Full example: http://code.runnable.com/U0tEnHwraXYyp-JG/simple-usage-of-express-session-and-cookie-parser-with-express-for-node-js

Upvotes: 0

Patosai
Patosai

Reputation: 760

You say cookie: { secure: true }, but is your web server actually on a secure connection? If not, then the cookie won't be written.

From the docs:

Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set.

Upvotes: 3

Related Questions