node.jsexpressexpress-session

Express session resets on every request


I have a vue frontend on localhost:8080 and a server at localhost:1234 I am using no https. Every time the vue app switches pages or gets reloaded, the Session resets. I've followed various solutions on the web, like these:Express session resets session on every request and Session keeps resetting on Node.js Express

However to no avail.

This is my session config:

// app.set('trust proxy', 1 );
app.use(session({
    secret: sessionServerToken,
    resave: true,
    saveUninitialized: true,
    cookie: {
        // Session expires after 1 hour of inactivity.
        expires: 60 * 1000 * 60,
        // sameSite: 'none',

        secure: false
    }
})); 

and this is my auth code:

router.post('/auth', (req, res) => {
    console.log(req.body);
    const session = req.session;
    AuthManager.authenticate(req.body.user, req.body.pass).then(response => {
        session.loggedIn = true;
        session.userID = response.user.id;
        res.status(200).send(response);
        res.end();
    }).catch(response => {
        res.status(response.statusCode).send({ message: response.message });
    });
});

Solution

  • Cookies won't be shared between different origins. Session data is not shared to the frontend app that's why it acts like the session is being reset.

    If you build your Vue app and serve it over Express you won't face this problem and the session will be shared as expected.

    However for development, it will be annoying, you can proxy the front-end app over Express.

    As a minimal example, you can try the code below. Run your Vue app as you normally do and then run the server with the following

    const express = require('express');
    const session = require("express-session");
    const proxy = require('express-http-proxy');
    const app = express();
    
    app.use(
      session({
        secret: 'keyboard cat',
        cookie: {
          maxAge: 60000
        },
        value: 0
      })
    );
    app.get('/api', (req, res) => {
      req.session.value ++;
      res.json({
        session: req.session.value
      });
    });
    app.use(proxy('http://127.0.0.1:8080'));
    
    app.listen(1234, '0.0.0.0', () => {
      console.log('Server is running at http://127.0.0.1:1234');
    });
    

    Vue app content will be available on http://127.0.0.1:1234 and if you navigate http://127.0.0.1:1234/api and refresh several times you will see the session value is present and not resetting.