3

I need to terminate the user session or log user out when they close the browser or tab. Following is the code implemented to maintain session:

app.use(session({
  store: new RedisStore({
    url: REDIS_CONNECTION_URL,
  }),
  secret: 'COOKIE_SECRET', 
  name: 'COOKIE_NAME',
  resave: true, 
  saveUninitialized: false,
  rolling: true,
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: 'COOKIE_TIMEOUT',
  },
}));

I have tried setting cookie.expires to true but that doesn't help.

Sujit
  • 59
  • 1
  • 3

1 Answers1

1

You have to handler onclose event of client user, then call a http request to destroy client's session on server side.

Client side:

$(window).unload(function () { 
  $.get('/session/destroy');
});

Server side:

app.get('/session/destroy', function(req, res) {
    req.session.destroy();
    res.status(200).send('ok');
});
hoangdv
  • 15,138
  • 4
  • 27
  • 48
  • 1
    as per the documentation, the unload event will be triggered even on page reload, this won't work for me – Sujit Jul 28 '18 at 08:35
  • 2
    @Sujit The simple answer is no - browsers' security models do not allow you to explicitly detect in what way a user has chosen to leave your page (refresh / close / internal link / external link). This article maybe help you https://webkul.com/blog/detect-browser-tab-refresh-browser-tab-close-using-javascript/ – hoangdv Jul 29 '18 at 02:31