Search code examples
node.jsangularjsexpresscorsexpress-session

Express session not persisting after CORS calls in Angular-Node application


I am trying to create a basic express session and save it to mongodb. I am getting stuck because the session does not persist through the CORS calls

I am doing this using express-sessions and saving the session in 'mongodb' using 'connect-mongodb-session'.

I have made the proper configurations and I have managed to create the session, save the required variables in it, and save the session in Mongodb.

My Imports:

const session = require('express-session');
const MongoSessionStore = require('connect-mongodb-session')(session);

My CORS configuration

app.use((req, res, next)=>{
  // The below 2 headers are for cookies
  res.setHeader("Access-Control-Allow-Credentials", true);
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
  res.setHeader("Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept");
  res.setHeader("Access-Control-Allow-Methods",
    "GET, POST, PUT, PATCH, DELETE, OPTIONS");
  next();
});

For Session:

const store = new MongoSessionStore({
  uri: MONGO_URI,
  collection: 'sessions',
});

app.use(session({secret: 'secret', resave: false, saveUninitialized: false,
  store: store}));

This is how I save the data in session in one call:

router.get('/login', (req, res, next) => {
    req.session.isLoggedIn = true;
    req.session.user = result;
    req.session.save();
    console.log(req.sessionID);
    console.log(req.session);
....}

Result for above logs:

Session {
  cookie:
  { path: '/',
    _expires: null,
    originalMaxAge: null,
    httpOnly: true },
  isLoggedIn: true,
  user: { _id: '1.6419261913557492',
    name: 'Vegeta',
    email: 'veg@gmail.com',
    password: 'galick',
    cart: { items: [] },
    __v: 0 } }

YCinv0rm8MOFplCHyc5l1z9wtXKVJKTR

Now, in another call:

router.put('/cart/add/:_id', (req, res, next) => {
  console.log(req.sessionID);
  console.log(req.session);
  ...}

Result:

oL2C7j5HYLF-GJx4bzOl_1_84homq7Lx

Session {
  cookie:
  { path: '/',
    _expires: null,
    originalMaxAge: null,
    httpOnly: true } }
TypeError: Cannot read property 'cart' of undefined
    at router.put (d:\MEAN\shopping\backend\routes\shop-router.js:38:42)
    at Layer.handle [as handle_request] (d:\MEAN\shopping\node_modules\express\lib\router\layer.js:95:5)
    at next (d:\MEAN\shopping\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (d:\MEAN\shopping\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (d:\MEAN\shopping\node_modules\express\lib\router\layer.js:95:5)
    at d:\MEAN\shopping\node_modules\express\lib\router\index.js:281:22
    at param (d:\MEAN\shopping\node_modules\express\lib\router\index.js:354:14)
    at param (d:\MEAN\shopping\node_modules\express\lib\router\index.js:365:14)
    at Function.process_params (d:\MEAN\shopping\node_modules\express\lib\router\index.js:410:3)
    at next (d:\MEAN\shopping\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (d:\MEAN\shopping\node_modules\express\lib\router\index.js:174:3)
    at router (d:\MEAN\shopping\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (d:\MEAN\shopping\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (d:\MEAN\shopping\node_modules\express\lib\router\index.js:317:13)
    at d:\MEAN\shopping\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (d:\MEAN\shopping\node_modules\express\lib\router\index.js:335:12)

I don't know what I am doing wrong. I have checked similar questions on stackoverflow, github etc, but none have helped me. Any help would be great. Thank you


Solution

  • Found the answer. It seems that for every server request I make through HttpClient, I need to set the withCredentials option to true. Like this:

    this.http.get<{message: string, orders: any}>
    ('http://localhost:3000/orders/get', {withCredentials: true});
    

    I guess I just have to find a way to set this option globally.