Req.session forgets added properties after being set in previous route

To try and accomplish storing session cookies in MongoDB, I am using express-session (1.17.3) with connect-mongo (5.1.0). When I log in, req.session.isAuth and req.session._id is supposed to be added to req.session.

After I log in, I am supposed to be redirected to the home page and will be able to fetch user data, based on the stored req.session properties. However, when I reach the home page after logging in, everything but isAuth and _id is visible in my MongoDB session store, nor is the cookie visible in my Chrome Developer Tools.

When I am fetching the user on the home page using the get request for /user, I check for .isAuth using a middleware. .isAuth was one of the req.session properties added back in /login. Currently, if I console.log(req.session.isAuth) in the isAuth middleware, I get undefined.

I have tried adding options to cors in my backend server, but those did not do anything.

If I do credentials: ‘include’ for the post request for /login, it gives me this error

If I change saveUninitialized to true, my MongoDB session database saves two cookies when somebody logs in, still without the .isAuth property.

res.end() doesn’t help express-session save req.session, nor does req.session.save() right after adding .isAuth.

So far, inside the post request to /login a console.log(req.session) gives me this:

Session {
  cookie: {
    path: '/',
    _expires: blahblahblah,
    originalMaxAge: blahblahblah,
    httpOnly: true,
    secure: true
  },
  isAuth: true,
  _id: new ObjectId('blahblahblah')
}

Right after doing this post request, doing a console.log(req.session) inside the get request to /user gives me this:

Session {
  cookie: {
    path: '/',
    _expires: blahblahblah,
    originalMaxAge: blahblahblah,
    httpOnly: true,
    secure: true
  }
}

Here is what my code for index.js looks like:

import 'dotenv/config'
const PORT = 8080;
import cors from 'cors';
import mongoose from 'mongoose';
import express from "express";
import session from 'express-session';
import MongoStore from 'connect-mongo';
import bcrypt from 'bcrypt';
import User from './models/userModel.js'

import { checkLogin } from './validation.js';
import { validationResult } from 'express-validator';

const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors({ 
    origin: "http://localhost:3000", 
    credentials: true, 
    methods: ["GET", "PATCH", "POST", "DELETE"],
    allowedHeaders: ["Content-Type", "Authorization"],
    optionsSuccessStatus: 200
}));

const clientP = mongoose.connect(
    mongoUrl,
    { dbName: 'dbName' }
)
.then(m => m.connection.getClient())
.then(() => {
    console.log('MongoDB Connected')
    app.listen(PORT, () => {
        console.log(`- - - Listening on PORT ${PORT} - - -`)
    })
})
.catch(err => console.log(err));

app.use(session({
    secret: secret,
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({
      mongoUrl: mongoUrl,
      dbName: "dbName",
      collectionName: 'the_collection_of_sessions',
      clientPromise: clientP,
      autoRemove: 'native',
      autoRemoveInterval: 15,
      crypto: {
        secret: secret
      },
      ttl: 14 * 24 * 60 * 60,
    }),
    cookie: { 
        secure: true, 
        maxAge: 14 * 24 * 60 * 60,
    },
}));

// below is the middleware to check if the user is authenticated, 
// used in app.get('/user')

const isAuth = (req, res, next) => {
    
    // returns undefined
    console.log(req.session.isAuth);

    if (req.session.isAuth) {
        console.log('is auth is true!')
        next();
    } else {
        console.log('is auth is false!')
        return res.status(400).send({ message: "Authentication Failed" });
    }

}

app.post("/login", checkLogin(), async (req, res) => {
    try {
        validationResult(req);
        
        const { username, email, password } = req.body;

        if (username === undefined) {
            console.log('set up email verification!')
        }

        const user = await User.find({ 'user.username': username })

        if (user === null) {
            console.log('user does not exist')
            return res.status(400).send({ message: "Authentication Failed" });
        }

        if (await bcrypt.compare(password, user[0].user.password)) {

            // where .isAuth is added

            req.session._id = user[0]._id
            req.session.isAuth = true;

            req.session.save()

            return res.status(201).end("Authentication Successful");

        } else {
            return res.status(400).end("Authentication Failed");
        }

    } catch (error) {
        console.log(error.message)
        res.status(500).send({ message: error.message })
    }

});

app.get("/user", isAuth, async (req, res) => {

    const user = await User.find({ _id: req.session._id })

    console.log(user)

    if (user === null) {
        return res.status(400).send({ message: "Authentication Failed" });
    }

    return res.status(201).json(user);
});

Here is my frontend code for the post request for /login:

const res = await fetch('http://localhost:8080/login', {
                method: 'POST',
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(user),
                // credentials: "include",
            })

if (res.status === 201) {
                router.refresh();
                router.push('/');
            } else {
                router.push('/not-found');
            }

Here is my frontend code for the get request for /user, just in case:

async function getUser() {
    const user = await fetch("http://localhost:8080/user", {
        method: 'GET',
        credentials: 'include'
    })
    return user;
}

export default async function Home() {
    const user = await getUser()
    ...
}

Please notify me of any suggestions you might have for solving this issue.

Thank you.