Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
Session variable not storing data in NodeJs and ExpressJS

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!