Search code examples
angularjsnode.jsexpresssessionexpress-session

session not persisting with express-session in mobile website


I have a web app built using NodeJS ,Express and AngularJS.I am using express-session for maintaining login sessions.

In desktop browser,the login session persists,as expected,even after the browser is closed,but

While accessing the website from mobile, the user gets automatically logged out every time the mobile browser is closed.

Sample code is as following:

let express = require('express');
let app = express();
let session = require('express-session');
let MongoStore = require('connect-mongo')(session);

app.use(session({
    secret: config.sessionSecret,
    name: "test",
    store: new MongoStore({
        url: mongoConnectionUrl,
        ttl: 2 * 24 * 60 * 60, // = 2 days. Default 
        autoRemove: 'native'
    }),
    resave: true,
    saveUninitialized: true
}));

How to stop auto logout of the user in mobile when the mobile browser is closed?

Website facing the above issue: https://ayan.work/notes


Solution

  • Just use the following code for configuration:

    app.use(session({
        secret: config.sessionSecret,
        name: "test",
        cookie: { maxAge: 3 * 24 * 60 * 60 * 1000 }, //user won't have to login for 3 days
        store: new (require('express-sessions'))({
            storage: 'mongodb',
            instance: mongoose, // optional 
            host: 'localhost', // optional 
            port: 27017, // optional 
            db: 'database name', // optional 
            collection: 'sessions', // optional 
            expire: 86400 // optional 
        })
    }));
    

    The option maxAge will maintain data in cookie there.