I'm trying to store user ID in user session in Express but for some reason the session forgets the value after the program exits the API path in which it was assigned. Here's the session setup in index.js:
var session = require("express-session");
app.use(
session({
secret: "abcdefghijklmnopqrstuvwxyz",
resave: false,
saveUninitialized: false,
})
);
Here's where i'm setting the session variable:
exports.agent_login = (req, res) => {
console.log("Request received");
Agent.findOne({ email: req.body.email })
.then((user) => {
if (!user) {
res.status(403).json({
message: "Email or password is incorrect",
success: false,
});
} else {
bcrypt.compare(req.body.password, user.password, (error, match) => {
if (error) {
console.log("Error seen ", error);
res.status(500).json({
message: "Internal server Error",
success: false,
});
} else if (match) {
req.session._id = user._id;
console.log(
"Request session inside agent login : " + req.session._id
); //Prints the correct value
res.status(200).json({
token: utils.generateToken(user),
message: "Agent login successfully",
success: true,
});
} else {
res.status(403).json({
message: "Email or password is incorrect",
success: false,
});
}
});
}
})
.catch((error) => {
console.log("Error seen ", error);
res.status(500).json({
message: "Internal server Error",
success: false,
});
});
console.log("Agent id inside Brand : " + req.session._id); //Prints undefined
};
And here's where I want to access the said variable but it outputs undefined:
console.log("Agent id inside Brand : " + req.session._id); //Prints undefined
I've been frustrated with this for a while now. If anyone can help me with this it would be very appreciated Thanks