Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change cookie expiration in Express

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'

Thanks for the help!

** EDIT **

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'

Grrrrrrr....

like image 915
user1161657 Avatar asked Dec 27 '12 04:12

user1161657


2 Answers

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'
  }));
like image 133
chovy Avatar answered Sep 18 '22 15:09

chovy


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

like image 28
AmirtharajCVijay Avatar answered Sep 20 '22 15:09

AmirtharajCVijay