Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda