2

I'm trying to learn the "cookie-session" module for Node. https://github.com/expressjs/cookie-session

I have a hard time understanding how to pass options for the cookie. For example expiration. Default seems to be a year!

This is the instructions about options for the cookie: "Other options are passed to cookies.get() and cookies.set() allowing you to control security, domain, path, and signing among other settings."

But i dont get it! Am I supposed to require cookies module as well? Or do I somehow change the options trough var session = require('cookie-session')? I have tried session.cookies.set(), but that doesnt seems to work.

I have tried to read the sourcecode in the "cookie-session" and "cookies" module for clues, but I dont know what to look for!

aynber
  • 22,380
  • 8
  • 50
  • 63
Anders Östman
  • 3,702
  • 4
  • 26
  • 48

1 Answers1

3

Short answer

Define the options you want to specify in the creation of the session, as illustrated in the docs: https://github.com/expressjs/cookie-session. They will be used when creating the cookie (including the expires option).

app.use(session({
  keys: ['key1', 'key2'],
  secureProxy: true // if you do SSL outside of node
  // more options here...
}))

Long answer

Using the example above, when you pass in the configuration object into session, you are sending this object into the function here. This opts is passed around, but in particular, stored as req.sessionOptions here. req is passed in when creating a new Session, and stored as this._ctx. Finally, when save is called on the Session, these options are pulled from the sessionOptions and used in the set call for the cookies:

Session.prototype.save = function(){
  var ctx = this._ctx;
  var json = this._json || encode(this);
  var opts = ctx.sessionOptions;
  var name = ctx.sessionKey;

  debug('save %s', json);
  ctx.sessionCookies.set(name, json, opts);
};

So the options you pass in originally are passed to the set call when creating the cookie.

dylants
  • 22,316
  • 3
  • 26
  • 22
  • Of course, I have misinterpret this completely. This line: "Other options are passed to cookies.get() and cookies.set()... " tricked me into thinking that all other options has to be applied in another mystic way... but they are just passed on as you clarify =) – Anders Östman Jun 05 '14 at 19:03