Search code examples
angularexpresssessionexpress-session

Express session parameters lost after another http request


When I make a post /login request, I get to see session with uid as I want it to be, but when i make a get request just a few seconds after that (same session), the uid is not there anymore. Can anyone help me with that?

app.use(session({
    secret: "rolling-communication",
    rolling: true,
    cookie: {
        maxAge: 1000 * 60,
    }
}));

auth.post("/login", (req, res) => {
    const clientReq = req.body;
    const loginQuery = 'SELECT uid as UID, password as PWD from Users where email = ?';
    pool.query(loginQuery, clientReq.email, async (err, rows) => {
        if (rows.length == 1) {
            req.session.uid = rows[0].UID;
            console.log(req.session); // prints session with uid
    });
});

app.get("/test", (req, res) => {
    console.log(req.session); // prints session withouth uid
    res.end();
});

Solution

  • The code you show NEVER sends a response back from the /login request handler. It's that response that carries the session cookie back to the client that makes the session work for future requests. If you never send a response, that cookie never gets back to the client so when the client makes a future request, it doesn't have a session cookie to send back and thus the backend doesn't get a session cookie and has to create a new empty session.

    Always send a response back from every code branch of every request handler:

    auth.post("/login", (req, res) => {
        const clientReq = req.body;
        const loginQuery = 'SELECT uid as UID, password as PWD from Users where email = ?';
        pool.query(loginQuery, clientReq.email, async (err, rows) => {
            if (err) {
                console.log(err);
                res.sendStatus(500);
                return;
            }
            if (rows.length === 1) {
                req.session.uid = rows[0].UID;
                console.log(req.session); // prints session with uid
                res.send("ok");
            } else if (rows.length === 0) {
                // user not found
                res.sendStatus(404);
            } else {
                console.log(`login query returned ${rows.length} rows`);
                res.sendStatus(500);
            }
        });
    });