title: passport js fails to maintain session when nodejs server restarts
body: <p>I am using  <code>nodejs, passportjs, jwtoken and mongoose</code> to develop an application. I am facing some critical situation and stuck since 2 days.</p>
  
  <p>I have used <code>passport js</code> for server side authentication and <code>jwtoken</code> for persistent login. It works very well ,with regular situation. But I have faced an issue before 3 days ago that when I restart server passport js fails to maintain session or expire nodejs user session. I don't know how to revalidate and recreate new passport session in nodejs.</p>
  
  <p>I have tried a lot but failed to recreate. I found this issue when I tried to restart server and from web application any request sent to server. When I tried to access req.user to get user data from session it throws me req.user is undefined.</p>
  
  <p>I even tried to use <code>connect-mongo</code> to store session but it throws an error - </p>
  
  <p><code>"Error: failed to deserialize user out of session"</code>. </p>
  
  <p>I don't know how to deal with situation. Provide me guidelines to resolve this issue.</p>
  
  <p>Please refer below source code.</p>
  
  <blockquote>
    <p>config.js</p>
  </blockquote>
  
  <pre><code>var express = require("express");
  var http = require("http");
  var path = require("path");
  var bodyParser = require("body-parser");
  var cookieParser = require("cookie-parser");
  var expressSession = require("express-session");
  var methodOverride = require("method-override");
  var morgan = require("morgan");
  var passport = require("passport");
  var randToken = require('rand-token');
  var jwt = require("jsonwebtoken");
  var mongoose = require("mongoose");
  var app = express();
  
  var useragent = require('express-useragent');
  app.use(useragent.express());
  
  require("./utils")(express, app, path);
  
  require("./db");
  
  app.set("port", process.env.PORT || 2000);
  app.set("env", "development");
  
  if (app.get("env") === 'production') {
      process.env['RECAPTCHA_PRIVATE_KEY'] = **** ;
      process.env['JWT_PRIVATE_KEY'] = **** ;
      process.env['COOKIE_PRIVATE_KEY'] = **** ;
      process.env['JWT_TIME_OUT'] = 60 * 60 * 24 * 30 * 1000; // 30 days
      process.env['SECURE_COOKIES'] = true;
  } else if (app.get('env') === 'staging') {
      process.env['RECAPTCHA_PRIVATE_KEY'] = **** ;
      process.env['JWT_PRIVATE_KEY'] = **** ;
      process.env['COOKIE_PRIVATE_KEY'] = **** ;
      process.env['JWT_TIME_OUT'] = 60 * 60 * 24 * 30 * 1000; // 30 days
      process.env['SECURE_COOKIES'] = false;
  } else if (app.get('env') === 'development') {
      process.env['RECAPTCHA_PRIVATE_KEY'] = **** ;
      process.env['JWT_PRIVATE_KEY'] = **** ;
      process.env['COOKIE_PRIVATE_KEY'] = **** ;
      process.env['JWT_TIME_OUT'] = 60 * 60 * 24 * 30 * 1000; // 30 days
      process.env['SECURE_COOKIES'] = false;
  }
  
  app.enable('trust proxy');
  
  app.use(bodyParser.urlencoded({
      extended: false
  }));
  
  app.use(bodyParser.json());
  app.use(cookieParser());
  
  app.use(expressSession({
      secret: process.env.COOKIE_PRIVATE_KEY,
      name: 'hz-app',
      proxy: true,
      resave: true,
      saveUninitialized: true,
      httponly: true
  }));
  
  app.use(passport.initialize());
  app.use(passport.session());
  
  app.use(methodOverride('X-HTTP-Method-Override'));
  
  var router = express.Router();
  var expressJWT = require("express-jwt");
  var allowAccess = expressJWT({
      secret: process.env.JWT_PRIVATE_KEY,
      userProperty: 'payload'
  }).unless({
      path: [
          '/api/user/register',
          '/api/user/useractivation',
          '/api/user/authenticate',
          '/api/user/checkEmail',
          '/api/user/checkNickName',
          '/api/user/resetPassword',
          '/api/user/addip',
          '/api/user/forgetPasswordRequest',
          '/api/user/logout',
          '/api/cms/getCms',
          '/adminapi/admin/authnticate',
          '/adminapi/admin/logout',
          '/adminapi/common/getLanguageList',
          '/api/common/getCurrencyList',
          '/adminapi/common/getUserType',
          '/api/newsSubscriber/create',
          //        '/api/newsSubcrib/create',
          //        '/adminapi/admin/userList',
          //        '/adminapi/admin/getUserType',
          //        '/adminapi/admin/userCreate',
          //        '/adminapi/admin/userEdit',
  
      ]
  });
  
  app.use(function(req, res, next) {
  
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization');
      next();
  });
  
  app.all(["/api/*", "/adminapi/*"], allowAccess, function(req, res, next) {
      if (req.user) {
          console.log("log in authorize obj for check");
          console.log(JSON.stringify(req.user));
      } else {
          console.log("not authenticated (not log in)");
          //res.clearCookie('hz-token');
          //res.clearCookie('hz-token-admin');
      }
  
      var reqPath = req.path.split("/");
      console.log('../app/data/routes/' + reqPath[2]);
      app.use(require('../app/data/routes/' + reqPath[2]));
      next();
  });
  
  app.get("/", function(req, res) {
      //app.use(function (req, res) {
      res.sendFile(basePath + "app/client/views/index.html");
  });
  
  app.get("/admin", function(req, res) {
      res.sendFile(basePath + "app/admin/views/index.html");
  });
  
  //Development error handler will print stacktrace
  if (app.get('env') === "development") {
      router.use(function(err, req, res, next) {
          res.status(err.status || 500);
          res.render('error', {
              message: err.message,
              error: err
          });
      });
  }
  
  router.use(function(err, req, res, next) {
      res.status(err.status || 500);
  });
  
  http.createServer(app).listen(app.get('port'), function() {
      console.log('Epsilon is listening on port ' + app.get('port'));
  });
  exports = module.exports = app;
  </code></pre>
  
  <blockquote>
    <p>user.js</p>
  </blockquote>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var Helper = require("../components/helper");
  var bcrypt = require("bcryptjs");
  var moment = require("moment");
  var User = require('../models/user');
  var passport = require("passport");
  var localStrategy = require("passport-local"),
          Startegy;
  
  router
          .route('/api/user/authenticate')
          .post(
                  function (req, res, next) {
                      console.log("&gt;&gt; authentication process initiated");
  
                      passport.authenticate('user-local', function (err, user, info) {
                          if (err) {
                              return res.status(401).json({
                                  status: 0,
                                  code: 401,
                                  type: "error",
                                  message: err
                              });
                          }
                          if (!user) {
                              console.log("not user:");
                              console.log(user);
                              return res.status(401).json({
                                  status: 0,
                                  code: 401,
                                  type: "error",
                                  message: info
                              });
                          }
                          req.login(user, {}, function (err) {
                              if (err) {
                                  return res.status(500).json({
                                      status: 0,
                                      code: 500,
                                      type: "other",
                                      err: 'could not login user'
                                  });
                              }
  
                              NextProcessForGenerateWebToken();
  
                              var NextProcessForGenerateWebToken = function () {
                                  if (err) {
                                      return next(err);
                                  }
                                  var _res = user.generateJWT(user);
                                  res.cookie('hz-token', _res, {maxAge: process.env.JWT_TIME_OUT, httpOnly: false});
                                  res.status(200).json({
                                      status: 1,
                                      type: "success",
                                      message: 'login successful',
                                      res: {
                                          link: user.link_id,
                                          nick_name: user.nick_name
                                      }
                                  });
                              };
                          });
                      })(req, res, next);
                  });
  
  
  /**
   * Serialize user for passport authentication
   */
  passport.serializeUser(function (user, done) {
      console.log("serialize:&gt;&gt;"+user.id);
      console.log(user);
      done(null, user.id);
  });
  
  /**
   * Deserialize user for passport authentication
   */
  passport.deserializeUser(function (id, done) {
      User.findById(id, function (err, user) {
          console.log("deserialize:&gt;&gt;"+user.id);
          done(err, user);
      });
  });
  
  /**
   * Passport local authentication policy to validate email/username and passport
   */
  passport.use('user-local', new localStrategy({
      usernameField: 'txtSigninEmail',
      passwordField: 'txtSigninPassword'
  },
          function (username, password, done) {
              User.findOne({$or: [{email: username}, {nick_name: new RegExp('^' + username + '$', "i")}], user_type: 3, is_active: 1, is_close: 0}, function (err, user) {
                  if (!user) {
                      return done(null, false, {message: 'Incorrect username.'});
                  }
  
                  user.comparePassword(password, function (err, isMatch) {
                      if (err)
                          throw err;
                      if (!isMatch) {
                          return done(null, false, {message: 'Incorrect password.'});
                      }
                      return done(null, user);
                  });
              });
          }
  ));
  
  module.exports = router;
  </code></pre>