Express Session : terminate session on tab/browser close

时间:2018-07-27 06:31:18

标签: node.js passport-local express-session node-redis

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.

1 个答案:

答案 0 :(得分:0)

您必须处理客户端用户的onclose事件,然后调用http请求来破坏服务器端的客户端会话。

客户端:

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

服务器端:

app.get('/session/destroy', function(req, res) {
    req.session.destroy();
    res.status(200).send('ok');
});