Staying authenticated after the page is refreshed using Passportjs Staying authenticated after the page is refreshed using Passportjs express express

Staying authenticated after the page is refreshed using Passportjs


The solution is to store the sessions in the DB. I used connect-mongo.

app.js:

var mongoose = require('mongoose');var expressSession = require('express-session');var MongoStore = require('connect-mongo')(expressSession);mongoose.connect(db_url, function (err) {    if (err) {        console.log(err);    }});app.use(expressSession({    secret: process.env.SESSION_SECRET || 'keyboard cat',    resave: false,    saveUninitialized: false,    store: new MongoStore({ mongooseConnection: mongoose.connection })}));

after this, req.isAuthenticated() returns true on every request even after refreshing the page. (Thanks to app.use(passport.session()) which comes before any route handler)

app.use('/', function (req, res, next) {    if (req.isAuthenticated()) {        // returns true if a user already logged in.    }    next();});


Looking at your post i can guess where problem is happening. In question you have pasted your back end expressjs code, but the problem is happening in the front end.

Think of a situation when you are working on normal javascript files, you make some edit in the variable values using Chrome dev tools of firebug n all. Let's say you refresh the page, do you still see the same edited value in the view? No right. Same is the case with your view, you are temporary holding user data. Although your backend is holding the values in req.user but your front end loses it when you refresh.

So you have to do either of below two :

  • Store your value in cookie on successful login and erase it whenlogged out. So that cookie is never going to loose data even if yourefresh the page. Access the user data from that cookie whenever you need it
  • Call the backend API which returns value of req.user on your everypage refresh

I am not sure what frontend framework you are using for SPA, if you are using AngularJS then you can make use of cookieStore service it does the job beautifully.