Reputation: 43
Is it possible to create a session cookie (one that is automatically deleted when the browser closes) AND also has an expiration so that it will expire after a set time, let's say 15 minutes unless the user continues using the site? If they use the site, i'd like to reset the expiration so it lasts another 15 minutes.
I've only really had luck with either creating a session cookie that expires when the browser is closed OR stays around as a persistent cookie but has an expiration either using expires or maxAge arguments.
The only thing I can think of is to create a session cookie that has a timestamp value stored in it and in the session middleware, check of the current time > the timestamp value and then deny the request and delete the cookie by setting it to null. If current time is <= the timestamp updating the timestamp to the new date effectively extending the session timeout.
While my idea may work, it makes me think there is a more official way of accomplishing what I want.
I'm currently experimenting with node and express so any insight that is tailored for that build-out would be appreciated.
Upvotes: 4
Views: 452
Reputation: 708106
Because the way you create a session cookie is to leave out the expiration, you can't really do it with a single cookie.
But, you can do it with two cookies, one session cookie and one expiring cookie. Here's some logic for doing it with two cookies:
session=randomNumber
.expiry=randomNumber
that expires in 15 minutes.If the browser is closed, the session cookie will be deleted. If 15 minutes passes, the second cookie will be deleted. If the browser is closed and then reopened, there won't be a session cookie and even if you coin another one, the second cookie won't have the same random number in it.
By checking for the presence of both cookies, you're making sure that both conditions have been met.
And, if you want the 15 minute cookie to continually refresh itself on any page load, you can have your server recreate that cookie on each page load with a new fresh time 15 minutes from now.
Upvotes: 1