Sam Williams Sam Williams - 5 months ago 45x
Javascript Question

Node.js Passport Display username after successful login

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?

This is my users.js file:

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){
// Profile
router.get('/profile', function(req, res){
// Register
router.get('/register', function(req, res){

// Login
router.get('/login', function(req, res){

// About-us
router.get('/about-us', function(req, res){

// Register User'/register', function(req, res){
var 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();

} else {
var newUser = new User({
username: username,
password: password,

User.createUser(newUser, function(err, user){
if(err) throw err;

req.flash('success_msg', 'You are now registered. Log In!');

passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) throw err;
return done(null, false, {message: 'User does not exist!'});

User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
return done(null, user);
} else {
return done(null, false, {message: 'Invalid password'});

passport.serializeUser(function(user, done) {

passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
passport.authenticate('local', {successRedirect:'/users/profile', failureRedirect:'/users/login',failureFlash: true}),
function(req, res) {


router.get('/logout', function(req, res){

req.flash('success_msg', '');


module.exports = router;

And this is my app.js file:

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');
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.urlencoded({ extended: false }));

// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public', express.static('public'));

// Express Session
secret: 'secret',
saveUninitialized: true,
resave: true

// Passport init

// Express Validator
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

// 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;

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'));

I've read a similar question on the site and the answer stated that:

app.get('/example', function(req, res) {
res.render('index', { username: req.user.username });

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.


I added

router.get('/profile', function(req, res){
res.render('profile', { username: req.user.username });

to my users.js file and added:

{{#if user}}
<p>Hello {{username}}</p>
<p>Please <a href='/users/login'>Log In</a></p>

to my profile.handlebars page but still no username display. What am i missing???

SOLUTION: 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
<p>Hi, {{username}}</p>
within his index file but only
was showing up within his browser. On the contrary neither
Hi or {{username}}
was showing in my browser. My entire
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 :)


You need to use the rendering part of the mentioned part of this code:

app.get('/example', function(req, res) {
  res.render('index', { username: req.user.username });

i.e., res.render('index', { username: req.user.username }); at the right/required path.

like you can try using it as

router.get('/profile', function(req, res){
  res.render('profile', { username: req.user.username });

and consume(use) the rendered variable username in your view for displaying.

If this doesn't work or you have some other problem, refer Nodejs Passport display username also.