Ron I Ron I - 1 year ago 187
Node.js Question

req.session is undefined using express-session

I am just starting to learn how to use cookies with node and express and I would like some help with getting this to work. I tried to follow the expressjs/session tutorial on GitHub, however I am getting

, so I am unable to set or get any values.

My goal is to save the first and last name of a user to a cookie so that an input field will auto populate. I'm not sure if I need to use
as well or if
can handle that alone. I'm not sure of how to proceed as I am new to cookies and express-session.

All help is appreciated! Thanks in advance.


let express = require('express');
let app = express();
let credentials = require('../modules/credentials.js');
let session = require('express-session');
let sessionOptions = {
secret: credentials.cookieSecret,
cookie: {
saveUninitialized: true,

if (app.get('env') === 'production') {
app.set('trust proxy', 1); = true;
else { = false;

let router = express.Router();

let request = require('request');
let db = require('../modules/queries');
let bodyParser = require('body-parser');
let cookieParser = require('cookie-parser');

// app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));

router.get('/me', function(req, res, next) {
console.log('req.session: '+req.session);

let firstName = req.session.firstName;
let lastName = req.session.lastName;
if (firstName && lastName) {
res.render('student/me.jade', {firstName, lastName});
else {
res.render('student/me.jade', { firstName: '', lastName: ''});
});'/api/me', function(req, res, next) {
let firstName = req.body.firstName;
let lastName = req.body.lastName;
// session.firstName = firstName;
// session.lastName = lastName;
req.session.firstName = firstName;
req.session.lastName = lastName;
console.log('session.firstName: '+session.firstName);
db.addEvent(req, res, next);

module.exports = router;

Answer Source

Once you mount a router onto an Express app, any subsequently declared middleware on that app won't get called for any requests that target the router.

So if you have this:


The session middleware won't get called for any requests that get handled by router (even if you declare the routes that the router should handle at some later point). For that, you need to change the order:


An additional issue is that you're exporting router, which should probably be app (which is the instance that "holds" all the middleware, routers, etc):

module.exports = app;