Session lifetime in node.js with express and MongoDB

10,934

Solution 1

Your question is a little vague but from what i can gather you wan't to set the expiration period for the session:

you can use maxAge like so:

app.use(express.cookieParser());
app.use(express.session({
    secret  : "Stays my secret",
    maxAge  : new Date(Date.now() + 3600000), //1 Hour
    expires : new Date(Date.now() + 3600000), //1 Hour
    store   : new MongoStore({ db: 'myDB' })
}));

expires value is required for new versions of express where as maxAge is for older versions, you should only need expires though.

Solution 2

@RobertPitt edit your answer. Cookie (session) object looks like:

{
 "cookie":"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},
 "your_var_1":"value 1",
 "your_var_2":"value 2",
 ...
}

Argument for express.session should look like this (it's in documentation):

app.use(express.session({
    secret  : "Stays my secret",
    cookie: {
        maxAge  : new Date(Date.now() + 3600000), //1 Hour
        expires : new Date(Date.now() + 3600000), //1 Hour
    },
    store   : new MongoStore({ db: 'myDB' })
}));

Moreover this:

maxAge  : new Date(Date.now() + 3600000), //1 Hour

will cause that every cookie (here also session) will be expired automatically one hour after server start

Share:
10,934
Thomas
Author by

Thomas

I am an Informatics scientist interested in machine learning and NLP technology.

Updated on June 19, 2022

Comments

  • Thomas
    Thomas almost 2 years

    I am using node.js with the express framework. As a session store I am using MongoDB. How can I set the lifetime after which the session objects are removed from MongoDB. This is how I am doing the declaration:

    app.use(express.cookieParser());
        app.use(express.session({
                    secret: "Stays my secret",
                    store: new MongoStore({ db: 'myDB' })
                        }));
    
  • Thomas
    Thomas about 13 years
    Thank you. Is the timer for maxAge reset every time the session is used or does it count from session creation?
  • Aaron
    Aaron over 11 years
    Based on stackoverflow.com/questions/10429557/…, it looks like your Date-using setting calls for an "expires" key, not "maxAge".
  • UpTheCreek
    UpTheCreek almost 11 years
    maxAge should be an age (e.g. a value in miliseconds) not a time in the future.
  • wprl
    wprl almost 10 years
    @UpTheCreek I believe the unit is seconds not milliseconds... can anyone confirm?
  • Nalla Srinivas
    Nalla Srinivas over 8 years
    @RoberPitt, here what is the use of MongoStroe and how it will be removed form db after session timeout? can you please explain