Trying to set a session in a react app with the use of express and express-session and all the MongoDB session tools.
I’ve tried many approaches even moving the way how I’m setting the middleware for sessions to see if I can see the session in the devTools. Although I can see that the session is saved in MongoDb and the console.log(req.session) displays the cookie, I can’t see it in the devTools. Below my code:
App.js server:
dbConnection.on(
"error",
console.error.bind(console, "MongoDB connection error:")
);
dbConnection.once("open", () => {
console.log("Connected to MongoDB");
});
const mongoStore = new MongoDBStore({
uri: databaseUrl,
collection: "sessions",
});
// CORS configuration
app.use(cors());
// cookie session setup
app.use(cookieParser());
app.use(
session({
secret: "secret",
resave: false, // save session when it changes.
cookie: {
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week
},
store: mongoStore,
saveUninitialized: true,
})
);
app.use(bodyParser.urlencoded({ extended: false })); // x-www-form-urlencoded <form>
app.use(bodyParser.json()); // application/json
app.use("/images", express.static(path.join(__dirname, "images")));
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
app.use((req, res, next) => {
console.log(req.session);
next();
});
app.use("/feed", feedRoutes);
app.use("/auth", authRoutes);
// error middleware
app.use((err, req, res, next) => {
const status = err.statusCode || 500;
const message = err.message;
res.status(status).json({ message: message });
});
mongoose
.connect(databaseUrl)
.then(() => {
app.listen(8080, () => {
console.log("connected to mongoose");
});
})
.catch((err) => {
console.dir;
console.log(err);
});
I’m setting the session to saveUninitialized but it doesn’t work when I load the react app page. Is there something off in my middleware setup? or is there any additional work I need to do in the frontend for this to work. I don’t think so…?