Session cookie expiration in Sails


When you generate new Sails application, session use transient (aka session) cookies. In most cases, web browsers usually delete transient cookies when the user closes the browser. As the cookie is deleted, users session is terminated. In some cases, this is desired behavior, but sometimes it is required that session expires within a specific time of application inactivity.

To change session’s cookie from transient cookies to persistent cookies with specific expiration time / date, you need to set session.cookie.maxAge configuration variable with session cookie maximum age in milliseconds.

The best way to set that value is to add (or uncomment) the following code to session configuration file: /config/session.js. In this example the maximum age of the session cookie will be an hour:

cookie: {
  maxAge: 60 * 60 * 1000
}

If you would like to change session max-age value for different environments, e.g., the session expires after an hour in production, but after a day in the development environment, you can add session.cookie.maxAge configuration into environment specific configuration file e.g.

  • /session/env/development.js for development environment
  • /session/env/production.js for production environment.

Alternatively, you can provide session cookie max-age value as a command-line argument (–session.cookie.maxAge) e.g.

sails lift --session.cookie.maxAge=3600000

Sails will look for configuration in the following order of descending priority:

  • command-line arguments
  • environment specific configuration file
  • configuration files in the application’s config/ directory

Thanks to the different configuration layers, you have considerable flexibility in the configuration of your applications.


Tags:

#javascript#node.js#sails.js#session


You may also be interested in: