Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

91
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda