How to update req.user session object set by passportjs?

req.user undefined
req.user express
req user not being set
req login', passport
failed to serialize user into session
passport custom callback
passport.authenticate not working

I'm trying to do this since a lot of days but all my tests fails...

Users on my platform connect them by using passportjs strategies (paypal, facebook, google...).

When the user is connected I write his nickname on the right in the header. The html code of the header is generated from a handlebars template, and when this partial is served by expressjs, I send the req.user session object to the template in order to write nickname and other informations...

By the way, this works great but I have a problem when the user update his nickname from his profile, I can't update session object on the server side and if the user reload the page, the old nickname appears again.

And I don't want to request user informations from DB every time a user load a page, so i want to keep this config :

// -- Passport session setup
passport.serializeUser(function(user, done) { done(null, user); });
passport.deserializeUser(function(obj, done) { done(null, obj); });

My middleware to set locals :

// -- Set accessible datas from the template
res.locals = _.extend(res.locals, {
    user: req.user,
    query: req.url,
    title: app.config.title,
    url: app.config.url

My fails :

// Trying to update req.user directly : not persistent
req.user.nickname = User.get('nickname');

// Trying to update passport session : exception error
req.session.passport.user = User.toJSON();

// Trying to replace full session object : not persistent
var session = req.session;
session.passport.user = User.toJSON();
req.session = session;

Any suggestion ?

For moment, only a logout then a login works... It's not really efficient :)


// Application router
var Router = require('./helpers/router.js');

// Create Express Server
var app = express().http().io();

// -- Init app router
var router = new Router(app);

// -- Framework Middleware


// Export router
module.exports = function(app) {

    // Set instance
    var router = this;

    // Returns routes register & middleware methods
    return {

        // -- Register routes
        register: function() {
            requirejs(['routes'], function(routes) {
                _.each(routes, function(name, route) {
                    app.get(route, function(req, res, next) {
                        requirejs(['views/'+name], function(view) {
                            if ( view ) {
                                var _view = new view(_.extend(req.params, {server: {req: req, res: res, next: next}})); 
                                _view.render(name, req, res, next); 
                            else {
                        }, function (err) {
                            console.log('error' + err)


        // -- Bind middleware
        middleware: function(req, res, next) {

            // Get the current path
            console.log("Middleware :: "+req.url);

            // Add user informations
            res.locals = _.extend(res.locals, {
                user: req.user,
                query: req.url,
                title: app.config.title,
                url: app.config.url

            // Go next 


This works and persists for me:

req.session.passport.user.nickname = 'mynewnickname'

Are you employing caching on your routes that might need busting before refresh?

(passport serialize is the same)

passport.serializeUser(function(user, done) { done(null, user); });
passport.deserializeUser(function(obj, done) { done(null, obj); });

How to update req.user session object set by passportjs?, toJSON(); // Trying to replace full session object : not persistent var session = req. session; session.passport.user = User.toJSON(); req.session = session; Any� The mistake I did was not being in the code I posted above, which is correct. I had a wrong way of linking to URLs so I somehow forced express to create a new session every time I used one of the broken links. With the new session I also lost my req.user object. So if you are having similar issues, also check your links inside your html.

I got the same problem and finally I found the solution:

var user = newDataObj;
req.logIn(user, function(error) {
    if (!error) {
       console.log('succcessfully updated user');
res.end(); // important to update session

The req.logIn will call serialize function and save a new session to db. res.end() is important. without it the session will not be saved.

Document req.login for refreshing req.user � Issue #208 , I hit a use case where I needed to refresh req.user with new Behind the scenes , passport will then reload the User object into session req.user . Pretty easy to set up, and then you can have as many app servers as you like� After the successfull login and callback, i use res.redirect to redirect the user to a different route , but the requests coming from that route contains the sessionID (so i dont think its the issue with the session store), but the req.user field doesnt exist(may be because passport.initialize() and passport.session() middlewares dont find the

For 'serializeUser' you are returning the entire user... which will serialize the entire object and put it inside the cookie used to track sessions. That serialization only happens one time (when the session is established). When the next request comes in, it always deserializes that exact same user object you stored originally, which doesn't have any updates you made to it. That's why logging out and logging back in works, because it retrieves the edited user from your database (I assume), and recreates the session tracking cookie.

To confirm this answer, put a breakpoint on 'serializeUser', and notice that it is only hit when you login.

Documentation: Authenticate, `req.user` contains the authenticated user. res.redirect('/users/' + req.user. username); }); When this is the case, session support can be safely disabled by setting the This gives the callback access to the req and res objects through closure. Removes req.user, and clears the session. Passport and Sessions. Passport creates a key in the session called session.passport. When a request comes in to the passport.session() middleware, passport runs the built-in 'session' strategy - this calls deserializeUser(session.passport.user, done) to read the user out of the session, and stores it

This is still one of the top results for 'update session passport js', so I thought I'd add what worked for me (the provided answers didn't work for me):

req.session.passport.user.updatedfield= 'updatedvalue' {console.log(err);}

Without the session data would not update for me. Hope this helps someone.

Documentation: Configure, Authentication strategies; Application middleware; Sessions (optional) Before asking Passport to authenticate a request, the strategy (or strategies) used The purpose of a verify callback is to find the user that possesses a set of credentials. database and/or object mapper, without imposition by the authentication layer. which, upon successful authentication should redirect to the users profile page. This does not work though as the user object in req is only set in the next request, after the redirect. I think it would be a good idea to set req.user to the user in authenticate before invoking the callback

Quan Duong's answer was the most useful to me, but here is a bit more realistic scenario:

async function foo(req, res) {
  // get some data from somewhere
  const newNickname = req.body.nickname;

  // update the user database somehow - e.g. mongodb 
  const users = db.getCollection('users');
  await users.updateOne({
    _id: req.user._id
  }, {
    $set: {
      nickname: newNickname

  // create a temporary copy of the user w/ the updated property
  const updatedUser = req.user;
  updatedUser.nickname = newNickname

  // persist the change to the session
  req.login(updatedUser, async(error) => {
    if (error) {
        err: 'Sorry, there was an error updating your account.'

       maybe you need to call another function from here that uses the updated info before 
       responding to the original request
    try {
      await bar(req.user);
    } catch (error) {
        err: 'Sorry, there was an error updating your account.'

    // done

Everything you need to know about the `passport-local` Passport JS , Session based authentication is at the root of the passport-local strategy. cookies, those users would have to login every time they refresh the page! Just like we set a custom property on the req object, we could also set� The final pieces of our Passport section we need to add are the serialization and deserialization of users into and out of the session. Since our user objects are very simple we will be serializing and deserializing the entire user object, but as they become larger and more complex using only one aspect of the user object can be more efficient.

How to update req.user session object set by passportjs?, The html code of the header is generated from a handlebars template, and when this partial is served by expressjs, I send the req.user session object to the� Simple Nodejs Authentication System Using Passport. We will use Node.js, Express, MongoDB, and passport package to build a simple web-based authentication system. Node.js Authentication using Express is very easy. You can use OAuth and other social media service providers using passport to authenticate the users.

Understanding Sessions and Local Authentication in Express with , This article aims to change that by going in-depth into how these concepts are This module expands the Express request object with the session property To configure passport correctly, you need to provide three things: For our local use case, the strategy is provided by the passport-local package. After a successful authentication, passport,js sets req.user. But in some of my routes, i update the user object in mongodb database. When i try to reach it again from req.user, i get the outdated version. Doesn't passport.js automatically update the req.user object? Or what is the appropriate way of doing this? ( I'm using express.js 3.x

Passport + NodeJs + Express getting “req.user” undefined , I am facing a session problem, Getting req.user undefined after I have used a hackathon starter which was using mongo, I tried to change things to use Postgres. 'uploads') }); /** * Load environment variables from .env file, where API app.set('host', ''); app.set('port', 8080); app.set('views',� In the previous post in this mini-series, we started our conversation about building an authentication system using Node.js, Express and Passport.js.This tutorial assumes that you already have a starting point (a login/registration form, and access to an Express back-end), if you do not, please check out the aforementioned blog post.

  • The question is really where you are assigning res.locals and req.user.nickname. Can you show some more code? What functions are those lines happening in?
  • The middleware is called just after static routes, set locals for the view and continue with defined routes. I've edited the post to show more code !
  • possible duplicate of Update logged in user details in session
  • I confirm, this works for me too. Thanks for the workaround!
  • I think you mean logIn with a capital I, not login.