How to clear req.session on clearing browser cookies in node js?

匆匆过客 提交于 2021-01-27 18:53:42

问题


I am using "express": "~4.14.0" with express-session for saving username. Once the user is logged in, I will save the user name in req.session.authorizedUser = username to display it in the application header.

When either the browser history is cleared or the browser is closed, I want to clear the session.

Please suggest me if there is any way to clear the session when doing any of these two operations. I have tried setting the maxAge option for session cookies, as shown below, but it doesn't reflects good:

app.use(session({
    secret: "key test",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: !true, path: '/', httpOnly: true, maxAge: null}
}));

回答1:


Since a browser doesn't notify a server when it deletes cookies (for whatever reason), there's no way of telling purely on the server side if a session should still be valid or not.

That's why most session stores have an expiry mechanism that will delete idle sessions after a specific amount of time (which is usually tied to maxAge).

For instance, the connect-mongo session store uses MongoDB's TTL feature to remove expired sessions from the database.

Apart from taking up a bit of storage space, idle sessions aren't a problem, though. When the user logs in again, a new session will be created for them, and the old one will eventually expire and be removed from storage.



来源:https://stackoverflow.com/questions/42782761/how-to-clear-req-session-on-clearing-browser-cookies-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!