Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stay signed in option with cookie-session in express

I would like to have a "Stay signed in" option such as the one provided by Gmail. This way, the user can decide if they want to keep the session open upon opening a new browser session after previously closing it.

Looking into the github issues I saw the cookie-session component doesn't provide a way to upate the maxAge property dynamilly.

I'm wondering then if there's any way at all to achieve the "Stay signed in" feature with the cookie-session component.

It seems to me a basic feature for a component which is being downloaded 80K times a month.

like image 240
Alvaro Avatar asked Jan 07 '16 13:01

Alvaro


People also ask

How do I use cookies in Express session?

var cookieSession = require('cookie-session') var express = require('express') var app = express() app. use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })) // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.

How do I keep a session alive in node JS?

Try something like: app. use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) );

What is saveUninitialized in Express session?

saveUninitialized. Forces a session that is “uninitialized” to be saved to the store. A session is uninitialized when it is new but not modified.

What can I use instead of Express session?

There are many alternatives to Express-session and it is likely that you are considering building a custom solution. However, as an alternative to Express-session, we have built a secure, open-source and feature-complete solution called SuperTokens. It is already being used by 100s of developers all.


2 Answers

// This allows you to set req.session.maxAge to let certain sessions 
// have a different value than the default. 
app.use(function (req, res, next) {
  // here you can see whether they checked the checkbox or not, and change maxAge.
  // the default should be that it expires when the browser is closed
  req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge

  // or you can try to set expires to 1 day from now:
  req.sessionOptions.expires = new Date(Date.now()+86400000)
  // or at the end of the session:
  req.sessionOptions.expires = 0
})
like image 141
Gavriel Avatar answered Oct 08 '22 05:10

Gavriel


If you are using ExpressJS, session module has an option.

https://github.com/expressjs/session

Alternatively req.session.cookie.maxAge will return the time remaining in milliseconds, which we may also re-assign a new value to adjust the .expires property appropriately. The following are essentially equivalent

like image 40
Anakin Avatar answered Oct 08 '22 05:10

Anakin