4

I am trying to use the express-session package for session management in an express-js application.

I have the following requirements:

  1. Cookie is destroyed client-side when browser is closed.
  2. Cookie is destroyed after 15 minutes idle time.
  3. Cookie is destroyed after 3 hours since creation (regardless of activity).

(Numbers are just examples).

I can deal with the idle time by manipulating the cookie maxAge up to a maximum. However, when I read the express-session documentation, I see:

By default cookie.maxAge is null, meaning no "expires" parameter is set so the cookie becomes a browser-session cookie. When the user closes the browser the cookie (and session) will be removed.

So, how do I create a "browser-session" cookie that also has a maxAge (used for idle/absolute timeout)?

I have also investigated using node-client-session package, but it does not allow for ephemeral and maxAge.

jzacharuk
  • 2,058
  • 1
  • 16
  • 22
  • I don't think there is such a thing as _ephemeral AND expiring_ cookies, it's one or the other (if a cookie isn't set with a `maxAge` or `expires` attribute, it's a session/ephemeral cookie). See [RFC 6265](https://tools.ietf.org/html/rfc6265#section-4.1.2). – robertklep Jun 03 '16 at 18:22
  • So I guess the answer would be to set it to an ephemeral cookie and then do all of the idle/timeout management myself server side. – jzacharuk Jun 03 '16 at 18:24
  • Yeah I'm afraid so. – robertklep Jun 03 '16 at 18:27
  • @robertklep Set that as an answer so I can accept it. Was trivial to implement, would actually make a decent package. – jzacharuk Jun 07 '16 at 15:54
  • Feel free to answer your own question, your solution may be helpful for others (whereas my comment was mere just that: a comment) :D – robertklep Jun 07 '16 at 16:19

1 Answers1

0

I have done an implementation of this after finding this question and wanting to have both a session timeout and ephemeral sessions. Here is what I have done to make this work in an actual application.

I use maxAge in my express-session configuration, and then in my client / web app code I hook the browser event "onbeforeunload". onbeforeunload info

It's not foolproof, and has some browser quirks, but when onbeforeunload fires, I use it to send an ajax request to the server to "logout" and kill the session.

It's important to now ask yourself what doing this does to the user experience (UX) and expected behavior of the session experience. If you want an ephemeral session, then it would be for a specific application in which you want something to be available as long as the browser is open. This could be accomplished with a short session age as well. We have to think about what the purpose of implementing this would be.

tremor
  • 3,068
  • 19
  • 37