I have an ExpressJS Server that is built with support for sessions backed by MongoDb as the Session Store. My React App is running on localhost and CORS setup is also configured on the ExpressJS Server for that. I am having an issue where even after setting req.session.user=loggedIn after authentication, req.session.user in subsequent calls always returns null.
Below is the code Snippet for My Express Server Setup:
require('dotenv').config();
const express = require('express');
const app = express();
const http = require('http');
const session = require('express-session');
const server = http.createServer(app);
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser())
app.use(session({
secret: Constants.SESSIONS_SECRET,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: process.env.DATABASE_SERVER }),
cookie: { maxAge: 180 * 60 * 1000 }
}));
//CORS Configs
const whitelist = ['http://localhost:3000'];
const corsOptions = {
credentials: true,
origin: (origin, callback) => {
if (whitelist.includes(origin))
return callback(null, true)
callback(new Error('Not allowed by CORS'));
}
};
app.use(cors(corsOptions));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Credentials", true);
next();
});
//Routes are included here just for snippet simplicity sake
app.post('/login', (req, res) => {
//After performing login here....some codes ommitted
let loggedInUserId = '...retrievedFromDb' //Retrieved from database
req.session.user = loggedInUserId; //This is where I set the session
//I can confirm that the session was set here
return res.send('log in success'); //...Some codes omitted
});
app.get('/protected_resource', (req, res, next) => {
if (!req.session.user) { //Even after log in, req.session.user always returns null. It's weird
return res.send('Not Logged in');
}
next();
}, nextFunc());
Then on my ReactJS Frontend I have a function that attempts to fetch the protected resource after login:
import axios from 'axios';
axios.defaults.withCredentials = true
async fetchProtectedResource(cb) {
axios.get(EndPoints.PROTECTED_RESOURCE_PATH, {
headers: await this.getRequestHeaders()
}).then((response) => {
cb(HttpSuccessDataHandler.getSuccessResponseData(response), null);
}).catch((e) => {
cb(null, HttpErrorHandler.spitHttpErrorMsg(e));
});
}
Now, the problem is that even after the authentication, req.session.user is always null.
I am suspecting a flaw in my CORS setup on the Express server but I'm not too certain yet, so any insights on what I might be doing wrong will really appreciated.