I'm using the express-session package to manage sessions in my Node.js application. I've configured it to use a MongoDB store to store sessions, and when a user logs in, the session data is successfully stored in the MongoDB database. However, I'm not seeing a session cookie in the browser.
Here's a simplified version of my session configuration:
const session = require('express-session')
const MongoDBStore = require('connect-mongodb-session')(session)
const store = new MongoDBStore({
uri: process.env.BD_URL,
collection: 'sessions',
});
store.on('error', function (error) {
console.error('Session store error:', error);
});
module.exports = (app) => {
app.use(
session({
name: 'ziraat',
secret: process.env.JWT_SECRET_KEY,
resave: false,
saveUninitialized: false,
store: store,
cookie: {
maxAge: 3600000,
secure: process.env.NODE_ENV === "production",
sameSite:false,
httpOnly: true
},
})
);
};
Here's a app.js code
// Use the built-in middleware to parse incoming JSON data.
app.use(express.json());
// Enable Cross-Origin Resource Sharing (CORS) to allow requests from different origins.
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
//------------ Configure Body Parser for Data ----------//
// Use the 'body-parser' middleware to parse JSON data from request bodies.
app.use(bodyParser.json());
//------------ Cookie Parser Configuration ------------//
// Use the 'cookie-parser' middleware to parse cookies from incoming requests.
app.use(cookieParser());
// Use the session to store the user data into session
session(app)
// Configure session serialization and deserialization
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
//------------ Error Handling Middleware ------------//
// Use the 'errorHandlerMiddleware' to handle errors in the application.
app.use(errorHandlerMiddleware);
//------------ Define Routes ------------//
// Mount the 'productsRoute' middleware under the "/api/v1" path.
app.use("/api/v1", productsRoute);
// Mount the 'userRoutes' middleware under the "/api/v1" path.
app.use("/api/v1", userRoutes);
// Mount the authRoute middlware under the "/api/v1" path.
app.use("/api/v1/", authRoute)
// Export the configured Express application to be used elsewhere.
module.exports = app;
Here is simplified version of the react app code to check authentication.
useEffect(() => {
// Check authentication status when the component mounts
const checkAuthentication = async () => {
try {
const response = await axios.get('http://localhost:8000/api/v1/auth/check-auth', {
withCredentials: true,
});
if (response.data.isAuthenticated) {
setIsAuthenticated(true);
setUserId(response.data.userId);
} else {
console.log(response);
setIsAuthenticated(false);
}
} catch (error) {
console.log(error);
}
};
checkAuthentication();
}, []);
Despite these configurations, I'm not seeing the session cookie being set in the browser, and as a result, response.data.isAuthenticated is always false.
I've also checked my backend route, and it correctly sets the session data and responds with isAuthenticated as true when accessed via Postman.
session(app)when you're already adding session management usingapp.use(session....)?