0

I have using express-session and connect-mongo for storing the session and it is working fine in the development environment. However, it is not persisting sessions in production. When I logged in I can get the session on the server by console.log(req.sesssion). However, the session is undefined if I move to another url.

const whitelist = ['https://example.com', 'https://www.example.com'];
const corsOptions = {
  origin(origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
};
app.use(cors(corsOptions));
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  store,
}));

1 Answers1

0

After searching for the answer I have spent about a day. Finally, I found the issues causing all the headaches. The issue was related to http requests. I am using axios for the requests and by default, Axios does not fetch send or receive any cookies. To be able to work cookies I needed to pass Axios config options.{withCredentials: true} for every requests that I made. Thanks to the post author.

Axios.post(url, data, { withCredentials: true })...

However, that lead me to another issue.

"The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'."

Then I have added credentials: true to my cors() module like so.

const corsOptions = {
  origin(origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true
};

Now My project is live and serving users to make their lives easier :).