I am developing a web application with NodeJs. I save the session information to the session object in the login function, but this value returns undefined in the requests I make from the front end. I configured CORS settings on the NodeJs side but the result is the same. But when I send the same request with Postman, it works smoothly. Can you offer any solution or can I do this in a different way?
The login function code I use in the router is as follows:
exports.loginWithLdap = catchAsync(async (req, res, next) => {
const { username, password } = req.body;
if (!username || !password) {
return next(new AppError('Please provide username and password!', 404));
}
const user = await ldapService.authenticate(username, password);
if (!user) {
return next(new AppError('Ldap authentication failed!', 401));
}
const otp = await otpService.generateAndSaveOTP(user.mail);
await otpService.sendOTP(user.mail, otp);
req.session.user = user;
res.cookie('user', user, { httpOnly: true });
res.status(200).json({
status: 'success',
message: 'OTP sent successfully!',
});
});
My cors and session settings are as follows:
app.use(
cors({
origin: 'http://localhost:5173',
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
})
);
app.use(
session({
secret: 'yourSecretKey',
resave: true,
saveUninitialized: true,
cookie: {
httpOnly: true,
secure: false,
sameSite: 'none',
maxAge: 24 * 60 * 60 * 1000,
},
})
);
app.use('/api', userRouter);
And i am trying to read req.session.user in this function:
exports.verifyOtp = catchAsync(async (req, res, next) => {
console.log(req.session.user);
const { otp } = req.body;
if (!otp) {
return next(
new AppError('Please provide an OTP code for authentication!', 404)
);
}
await otpService.verifyOTP(req.session.user.mail, otp);
res
.status(200)
.json({ message: 'OTP verified successfully!', user: req.session.user });
});
I tried to send request from Postman and it works fine. After that updated cors and session setings many times because i think that might be the problem. But it doesn’t work at all.