title: Node.js Passport Display username after successful login
body: <p>I am using Node.js Passport and I'm trying to figure out how to display username after a successful login. After reading the documentation I've verified that i have Sessions and Middleware configured which is what I need but what are my next steps? </p>
  
  <p>This is my <strong>users.js</strong> file:</p>
  
  <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');
  
  // Home
  router.get('/index', function(req, res){
      res.render('index');
  });
  // Profile
  router.get('/profile', function(req, res){
      res.render('profile');
  });
  // Register
  router.get('/register', function(req, res){
       res.render('register');
  });
  
  // Login
  router.get('/login', function(req, res){
      res.render('login');
  });
  
  // About-us
  router.get('/about-us', function(req, res){
      res.render('about-us');
  });
  
  
  // Register User
  router.post('/register', function(req, res){
  var email = req.body.email;
  var username = req.body.username;
  var password = req.body.password;
  
  // Validation
  req.checkBody('username', 'Username is Required').notEmpty();
  req.checkBody('email', 'Email is required').notEmpty();
  req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('password', 'Password is required').notEmpty();
  
  var errors = req.validationErrors();
  
  if(errors){
      res.render('register',{
          errors:errors   
      });
  } else {
      var newUser = new User({
          email:email,
          username: username,
          password: password,
      });
  
      User.createUser(newUser, function(err, user){
          if(err) throw err;
          console.log(user);
      });
  
      req.flash('success_msg', 'You are now registered. Log In!');
      res.redirect('/users/login');
  }
  });
  
  passport.use(new LocalStrategy(
  function(username, password, done) {
  User.getUserByUsername(username, function(err, user){
  if(err) throw err;
  if(!user){
      return done(null, false, {message: 'User does not exist!'});
  }
  
  User.comparePassword(password, user.password, function(err, isMatch){
      if(err) throw err;
      if(isMatch){
          return done(null, user);
      } else {
          return done(null, false, {message: 'Invalid password'});
      }
      });
      });
      }));
  
  passport.serializeUser(function(user, done) {
   done(null, user.id);
    });
  
  passport.deserializeUser(function(id, done) {
   User.getUserById(id, function(err, user) {
    done(err, user);
  });
  });
  
  
  router.post('/login',
  passport.authenticate('local', {successRedirect:'/users/profile',      failureRedirect:'/users/login',failureFlash: true}),
  function(req, res) {
  res.redirect('/users/profile')
  
  });
  
  router.get('/logout', function(req, res){
  req.logout();
  
  req.flash('success_msg', '');
  
  res.redirect('/');
  });
  
  module.exports = router;
  </code></pre>
  
  <p>And this is my <strong>app.js</strong> file:</p>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var exphbs = require('express-handlebars');
  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 mongo = require('mongodb');
  var mongoose = require('mongoose');
   mongoose.connect('mongodb://localhost/loginandregister');
   var db = mongoose.connection;
  
  var routes = require('./routes/index');
  var users = require('./routes/users');
  
  // Init App
  var app = express();
  
  // View Engine
  app.set('views', path.join(__dirname, 'views'));
  app.engine('handlebars', exphbs({defaultLayout:'layout'}));
  app.set('view engine', 'handlebars');
  
  // BodyParser Middleware
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
  
  // Set Static Folder
  app.use(express.static(path.join(__dirname, 'public')));
  app.use('/public', express.static('public'));
  
  // Express Session
  app.use(session({
      secret: 'secret',
      saveUninitialized: true,
      resave: true
  }));
  
  // Passport init
  app.use(passport.initialize());
  app.use(passport.session());
  
  // Express Validator
  app.use(expressValidator({
    errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
        , root    = namespace.shift()
        , formParam = root;
  
  while(namespace.length) {
    formParam += '[' + namespace.shift() + ']';
  }
  return {
    param : formParam,
    msg   : msg,
    value : value
   };
   }
   }));
  
  // Connect Flash
  app.use(flash());
  
  // Global Vars
  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('/users', users);
  
  // Set Port
  app.set('port', (process.env.PORT || 3000));
  
  app.listen(app.get('port'), function(){
      console.log('Server started on port '+app.get('port'));
  });
  </code></pre>
  
  <p>I've read a similar question on the site and the answer stated that:</p>
  
  <pre><code>app.get('/example', function(req, res) {
  res.render('index', { username: req.user.username });
  });
  </code></pre>
  
  <p>needs to be implemented. But I am confused as to where and how? I tried placing it into to my users.js file but i get a "ReferenceError: app is not defined" error in terminal when restarting the node app.
  What are my next steps? Any and every help is valued and appreciated. Thank you.</p>
  
  <p>EDIT:</p>
  
  <p>I added </p>
  
  <pre><code>router.get('/profile', function(req, res){
  res.render('profile', { username: req.user.username });
  });
  </code></pre>
  
  <p>to my users.js file and added: </p>
  
  <pre><code>&lt;header&gt;
    &lt;h1&gt;Hello?&lt;/h1&gt;
    {{#if user}}
      &lt;p&gt;Hello {{username}}&lt;/p&gt;
    {{else}}
      &lt;p&gt;Please &lt;a href='/users/login'&gt;Log In&lt;/a&gt;&lt;/p&gt;
    {{/if}}
   &lt;/header&gt;
  </code></pre>
  
  <p>to my profile.handlebars page but still no username display. What am i missing???</p>
  
  <p><strong>SOLUTION:</strong> Apparently my code was correct and my problem was solved hours ago however it was hiding in plain site. I am using Firefox to build my site and Chrome to conduct all my research and web searching. After DEEP searching i stumbled upon another similar question to my own and this guy complained that he had <code>&lt;p&gt;Hi, {{username}}&lt;/p&gt;</code> within his index file but only <code>Hi</code> was showing up within his browser. On the contrary neither <code>Hi or {{username}}</code> was showing in my browser. My entire <code>&lt;p&gt;</code> tag was missing. So i simply loaded my site in Chrome and there it was problem solved! Bad practice on my part for only using one browser but that's what I get for silly mistakes :)</p>