title: Cannot read property 'username' of undefined while trying to access the req.user property in node js
body: <p>I am using MEAN Stack. I want to access the req.user property. But I am getting an error saying <strong>Cannot read property 'username' of undefined</strong> when I try to display the username of current user. I reffered to some sites. 
  <a href="https://www.airpair.com/express/posts/expressjs-and-passportjs-sessions-deep-dive" rel="nofollow noreferrer">https://www.airpair.com/express/posts/expressjs-and-passportjs-sessions-deep-dive</a></p>
  
  <p>Similar question <a href="https://stackoverflow.com/questions/16434893/node-express-passport-req-user-undefined">Node + Express + Passport: req.user Undefined</a></p>
  
  <p>It has been mentioned the order of the middleware functions matters. I corrected those. Still I am getting the same error. What is my mistake?</p>
  
  <blockquote>
    <p>app.js</p>
  </blockquote>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var mongo = require('mongodb');
  var mongoose = require("mongoose");
  var expressValidator = require('express-validator');
  var flash = require('connect-flash');
  var session = require('express-session');
  var passport = require('passport');
  var LocalStrategy = require('passport-local').Strategy;
  var ConnectRoles = require('connect-roles');
  var User = require('./models/user');
  
  
  mongoose.connect("mongodb://localhost:27017/test"); 
  var db = mongoose.connection;
  
  db.on("error", console.error.bind(console, "Connection error:"));
  db.once("open", function(callback){
      console.log("Connection Succeeded."); 
  });
  
  var routes = require('./routes/Login');
  var admin = require('./routes/AdminDatabase');
  var survey = require('./routes/CreateSurvey');
  var submit = require('./routes/SubmitSurvey');
  
  var app = express();
  
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');
  
  app.use(logger('dev'));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(cookieParser());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  
  app.use(session({
      secret: 'secret',
      saveUninitialized: true,
      resave: true
  }));
  
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(flash());
  app.use(function (req, res, next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
  
    next();
  });
  
  app.use('/', routes);
  app.use('/AdminDatabase', admin);
  app.use('/CreateSurvey', survey);
  app.use('/SubmitSurvey', submit);
  
  app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  });
  
  
  if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: err
    });
  }
  
  
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: {}
    });
  });
  
  app.get('/AdminDatabase', function(req, res){
      user.find({}, function(err, profile){
          res.render('AdminDatabase', {profile:profile});  
      });
  });
  module.exports = app;
  </code></pre>
  
  <blockquote>
    <p>Login.js (where I have the passport and routes)</p>
  </blockquote>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var passport = require('passport');
  var LocalStrategy = require('passport-local').Strategy;
  var User = require('../models/user');
  var ConnectRoles = require('connect-roles');
  
  router.get('/', function(req, res, next) {
    res.render('Login', { title: 'Login' });
  });
  
  passport.serializeUser(function(user, done) {
      done(null, user._id);
  });
  passport.deserializeUser(function(id, done) {
      User.findById(id, function(err, user) {
      done(err, user);
      });
  });
  
  passport.use("/", new LocalStrategy(
       function(username, password, done) {
          User.findOne({ username: username }, function(err, user) {
              if (err) { return done(err); }
  
              if (!user) {
                  return done(null, false,
                   { message: "No user has that username!" });
              }
  
              user.checkPassword(password, function(err, isMatch) {
  
              if (err) { return done(err); }
                  if (isMatch) {
                      return done(null, user);
                  } else {
                      return done(null, false,{ message: "Invalid password." });
              }
          });
      });
  }));
  
  router.use(function(req, res, next) {
      res.locals.currentUser = req.user;
      res.locals.errors = req.flash("error");
      res.locals.infos = req.flash("info");
  
      next();
  });
  
  router.post("/", passport.authenticate("/", {
      successRedirect: "/SubmitSurvey",
      failureRedirect: "/",
      session: false,
      failureFlash: true
  }));
  
  router.get("/AdminDatabase", function(req, res) {
     res.render('AdminDatabase', { title: 'AdminDatabase' });
   });
  
  router.get('/CreateSurvey', function(req, res, next) {
    res.render('CreateSurvey', { title: 'CreateSurvey' });
  });
  
  router.get('/SubmitSurvey', function(req, res, next) {
    res.render('SubmitSurvey', { title: 'SubmitSurvey' });
  });
  
  router.get('/profile', function(req, res){
    var user= res.user;
    res.render('profile', { title: 'profile', user: user });
  });
  
  router.get("/Logout", function(req, res) {
      req.logout();
      res.redirect("/");
  });
  
  module.exports = router;
  </code></pre>