dgrcode dgrcode - 1 year ago 240
Node.js Question

req.session is undefined express-session

I know this question has been asked several times. However, none of the answers I've read has solved my question.

Many of them were outdated for express v4, as express-session is currently a separate module. Those question/answers are here:

Other questions are updated, however the solution given doesn't fix my problem. Those question/answers are here:

Most of the solutions are the sequence of middlewares when configuring the app. I've tried different options and I doesn't find the correct way to do it. Maybe it's just that.

In other solution, someone says that
middleware cannot be called, because if it were,
would be defined. I've used middlewares just before an after
, and checked that both get called.

I've also found in this issue someone saying that he gets
undefined when the store disconnects. I'm using the default store so far. Could this be the problem?

I'm getting this error:

TypeError: Cannot read property 'destroy' of undefined

It breaks just when I try to logout a session with
at login.js (see code below)

My code


const express = require('express');
const session = require('express-session');
const mongo = require('mongodb');
const passport = require('passport');
const path = require('path');
const routes = require('./app/routes');
const login = require('./app/routes/login.js');

const app = express();
secret: 'key',
resave: false,
saveUninitialized: true,
app.use('/public', express.static(path.normalize('./public')));
app.set('view engine', 'pug');

const MongoClient = mongo.MongoClient;
.then((db) => {
// Link the database through the app. It will be available in the req.app object
app.db = db;
console.log('App listening on port ' + process.env.PORT);
.catch((err) => {
console.log('There was an error connecting to the database.');

module.exports = app; // For testing


const express = require('express');
const passport = require('passport');
const router = new express.Router();

// Other login logic here

router.get('/logout', (res, req) => {
req.session.destroy((err) => {

module.exports = router;

Answer Source

You swapped the req and res arguments in your handler:

router.get('/logout', (res, req) => { ... })

That should be the other way around:

router.get('/logout', (req, res) => { ... })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download