express-session not being saved locally but works in production

Viewed 191

So I am running a node.js backend with a react frontend, and for some reason with this setup:

app.use(session({
    store: new MongoStore({
        mongooseConnection: mongoose.connection
    }),
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: false,
    cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 7 * 2, // two weeks
        secure: false,
        httpOnly: false,
    }
}));

I save the username using: req.session.username = username; which does save but then whenever I try to check the session on another page the username is gone.

Full source code: https://github.com/CTF-Cafe/CTF_Cafe/tree/master/backEnd

PS: it works in production completely fine, but not locally I tried with httponly false, and secure false. No change.

Any help appriciated

1 Answers

When you serve your frontend from your backend the session will be working because it has the same origin. However, for your local environment, you will be running React app in a different port, and the Express app would be also different. When a port is different it is already considered a different origin and cookies, sessions won't be shared.

You can proxy your frontend via the node app and this way you can have the same origin and your session will remain.

const proxy = require('express-http-proxy');
const app = express();

...
// Add after your routes
app.use(proxy('http://127.0.0.1:3000')); // assuming your Reacts runs on P3000

Check this answer too.

Related