Change cookie expiration in Express
Asked Answered
G

5

22

Because I didn't define a maxAge when calling expressServer.use(express.session({params})) the cookie's expiration is set as "Session".

I would like to add a "remember me" feature when logging in. If "remember me" is selected, the expiration will be extended to a month.

How would I go about doing this? I tried simply extending the maxAge, but that didn't seem to do anything...

expressServer.get '/blah', (request, response) =>
    request.session.cookie.maxAge = 2592000
    response.end 'hello there'

I tried making a simple server to test updating a user's cookie. I'm using Express 3.0.4

When I visit 127.0.0.1:9000/blah, the browser cookie's "expires" field is still "session"...

express = require 'express'

expressServer = express()
expressServer.use express.cookieParser()
expressServer.use express.session
    secret: 'supersecret'
    cookie:
        path: '/'
        httpOnly: true

expressServer.get '/', (request, response) =>
    response.end 'hello'

expressServer.get '/blah', (request, response) =>
    request.session.cookie.maxAge = 3600000
    response.end 'hello again'

expressServer.listen 9000
console.log 'server running'
Gingery answered 27/12, 2012 at 4:15 Comment(4)
However, if I clear my browser cookies and visit "/blah", the "expires" field is set correctly. Which makes sense, since the cookie needs to be set for the first time :)Gingery
Ok... it seems to work ONLY if I update the session... So I just added request.session.blah = Date() and things magically work?Gingery
You could try to set the maxAge with a default value and then expire the cookie if the checkbox is not checked (req.session.cookie.expires = false).Hughes
There's a difference? @_@Gingery
F
20

I have a checkbox that says "remember me" on the /login page:

<p class="remember">
  <input type="checkbox" id="remember" name="remember" value="1" />
  <label for="remember">Remember me</label>
</p>

Then in my POST route to /login I do some sanity checking and set the session if req.body.remember is set otherwise its just a window session:

  //user is authenticated
  //set session length
  if ( req.body.remember ) {
    var hour = 3600000;
    req.session.cookie.maxAge = 14 * 24 * hour; //2 weeks
  } else {
    req.session.cookie.expires = false;
  }

  req.session.userid = user._id;

Add the following few lines (I use redis) in app.js:

  app.use(express.cookieParser('secret-word'));
  app.use(express.session({
    store: new RedisStore({
      host: cfg.redis.host,
      db: cfg.redis.db
    }),
    secret: 'another-secret'
  }));
Fawn answered 27/12, 2012 at 4:55 Comment(2)
For me, it changes the session's cookie on the backend, but doesn't actually change anything in the browser :'(Gingery
I updated the answer. I'm using redis, this is all i had to do to get it to work.Fawn
I
11

Set cookie name to value, where which may be a string or object converted to JSON. The path option defaults to "/".

res.cookie('rememberme', '1', 
                { expires: new Date(Date.now() + 900000), httpOnly: true });

For further references following the link may be used

http://expressjs.com/api.html#res.cookie

Ichthyology answered 21/8, 2013 at 9:20 Comment(0)
B
6

If you want to implement rolling sessions with cookie-sessions in express 4, configure the middleware like this:

app.use(cookieSession({
    secret: your_secret,
    maxAge: your_maxAge,
    key: 'sessionId'
}));

Note that you do not need to set the expires option.

In order to extend your session, simply alter it like this:

app.get('*', function (req, res, next) {
    req.session.foobar = Date.now();
    next();
}

Note that in express 4 there is no req.session.touch().

Borer answered 25/3, 2015 at 12:52 Comment(0)
E
2

I found an answer that seems to work for me; add it to the top of your routes.

app.all '*', (req,res,next) ->
  if req.method is 'HEAD' or req.method is 'OPTIONS'  
    next()
  else
    req.session._garbage = Date();
    req.session.touch();
    next();
Eckenrode answered 14/8, 2013 at 11:11 Comment(1)
Bug reported to the link aboveLumbard
S
0

Or You can try this, it worked for me:

if ( req.body.remember ) 
{
    var oneWeek = 7 * 24 * 3600 * 1000; //1 weeks                    
    req.session.cookie.expires = new Date(Date.now() + oneWeek);
    req.session.cookie.maxAge = oneWeek; 
}
Spadefish answered 20/11, 2017 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.