Search code examples
node.jsherokupassport.jsexpress-session

How can I keep user sessions alive indefinitely?


I have Nodejs, ReactJS and React Native app, MERN app is deployed on Heroku using free dynos. The session automatically times out after some time. I wish to maintain session forever without expiry.

I haven't set any expiry time, or MaxAge at the time of initialize session:

app.use(session({
  secret: 'thesecret',
  saveUninitialized: false,
  resave: false
}))

app.use(passport.initialize());
app.use(passport.session());

I expect to maintain session forever in my ReactJS and React Native app. How can I do that on Heroku?


Solution

  • By saving session in mongodb database we can maintain a continuous session in our nodeJS app.

    var MongoDBStore = require('connect-mongodb-session')(session);
    var store = new MongoDBStore({
    uri: process.env.MONGODB_URI,
      collection: 'mySessions'
    });
    
    // Catch errors
    store.on('error', function(error) {
      console.log(error);
    });
    app.use(session({
      secret: 'thesecret',
      saveUninitialized: false,
      resave: false,
      cookie: {expires: new Date(1586323351000),maxAge:31536000000},
      store: store,
    }))