简体   繁体   中英

How to detect first connection using express-session

It must be native, am I missing something ? I can set a counter bound to the request.session variable, although, I want a more explicit way.

If you want to use express-session, it does not have a built-in way to know when the session is brand new. A counter is a simple solution. Or, this simple middleware implements the isNew property you asked about and avoids saving the session except the first two times it is accessed:

app.use(session(...));

app.use((req, res, next) => {
    if (typeof req.session.isNew === "undefined") {
        req.session.isNew = true;
        req.session.save(next);
    } else if (req.session.isNew) {
        req.session.isNew = false;
        req.session.save(next);
    } else {
        next();
    }
});

// output value of isNew (only here for demonstration purposes)
app.use((req, res, next) => {
   console.log(req.session.isNew);
   next();
});

I should add that this also attempts to avoid race conditions by immediately saving the session (to the session store) as soon as it is updated so if two requests arrive close in time and the first one goes asynchronous allowing the second one to start, then the second one will still see the accurate value for req.session.isNew .

req.session.isNew

session is always accessed through a request object, also there is a boolean field called isNew.

Edit: This is part of cookie-session which is a session middleware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM