That Guy That Guy - 2 years ago 169
Javascript Question

req.session is undefined in Node?

I already looked at the other answers for similar questions, yet none of them worked for me. I two pieces of code, one to test that cookies were working(cookieTest.js), and one to actually use them(users.js). I tried moving the app.use() statements for the session middleware and the cookie middleware to no avail. Any ideas on how to fix this?


//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");
var session = require('express-session');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({secret: '_secret_', cookie: { maxAge: 60 * 60 * 1000 }, saveUninitialized: false, resave: false}))
router.get('/register', function(req, res){
res.sendFile(appDir + "/views/register.html");
})'/register', function(req, res) {
req.check('name', 'Name must be Filled in').notEmpty();
req.check('email', 'Email must be Filled in').notEmpty();
req.check('email', "Invalid Email").isEmail();
req.check('password', 'Password Field must be Filled in').notEmpty();
req.check('password', 'Passwords do not Match').equals(req.body.password2)
var errors = req.validationErrors();
if(errors) res.send(errors)
var newUser = new User({
password: req.body.password,
info: req.body.user_bio
User.createUser(newUser, function(err, user){
if(err) throw err;
router.get('/login', function(req, res){
res.sendFile(appDir + "/views/login.html");
})'/login', function(req, res){
var email =;
var candidatePass = req.body.password;
User.findOne({ 'email': email }, 'password id', function (err, user) {
if (err) return handleError(err);
User.checkPassword(candidatePass, user.password, function(err, isMatch){
if(err) throw err;
if(!isMatch) res.end('Password Incorrect!');
req.session.userId =;
module.exports = router;

When I run this I get the error
TypeError: Cannot set property 'userId' of undefined
, which means that req.session is undefined. However, when I run this, it works fine

var express = require('express');
var session = require('express-session');
var app = express();
var uuid = require('node-uuid');
var bodyParser = require('body-parser');

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

// Use the session middleware
secret: 'jaredasch',
cookie: { maxAge: 60 * 60 * 1000 },
saveUninitialized: false,
resave: false

// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.uuid) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.write('<form method = \'POST\'action = \'/\'><button type = \'submit\'></form>');
} else {
sess.uuid = uuid.v4();
res.setHeader('Content-Type', 'text/html');
res.write('Set Up Session \n')
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.end('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
})'/', function(req,res){
req.session.destroy(function(err) {
if(err) throw err;
console.log('Session Destroyed')

app.listen(3000, function(){
console.log('Listening on Port 3000')

Why does this work and the one above not, and how could I fix the one above? How would you reccomend fixing such an issue?

Answer Source

Try using app.use(cookieParser("_secret_")); so that its the same secret as with Express

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download