Express-session unexpectedly clearing/destroying itself

Viewed 44

In order to pass success/error messages to the frontend, I've been using express-session and attaching messages as an array of strings to req.session['message'].

I have this working in one instance (I've trimmed some of the unrelated stuff from this function):

customerModel.findCustomer(customer, (err, found) => {
  if (err) {
    req.session['message'] = getErrors(err);
    res.redirect('/customers/add');
  } else {
    if (found) {
      req.session['message'] = ["Customer already exists"];
      res.redirect('/customers/add');
    } else {
      customerModel.addCustomer(customer, (err, created) => {
        if (err) {
          req.session['message'] = getErrors(err);
          res.redirect('/customers/add');
        } else {
          if (created) {
            req.session['message'] = ["Customer successfully created"];
            res.redirect('/customers');
          } else {
            req.session['message'] = ["An Error Has Occured"];
            res.redirect('/customers/add');
          }
        }
      })
    }
  }
})

getErrors(err) is called where multiple messages are being passed.

However, I have another function that appears identical, but doesn't maintain the session? I have included this function in its entirety.

deleteCustomer(req, res) {
  try {
    const id = req.params['id'];
    customerModel.deleteCustomer(id, (err, deleted) => {
      if (err) {
        req.session['message'] = getErrors(err);
        res.redirect('/customers');
      } else {
        if (deleted) {
          req.session['message'] = ["Customer successfully deleted"];
          res.redirect('/customers');
        } else {
          req.session['message'] = ["Customer not found"];
          res.redirect('/customers');
        }
      }
    });
  } catch (err) {
  }
}

Both write a message to req.session and then redirect to the /customers route. When this is done within the findCustomer/addCustomer path - I have access to the messages on the frontend. When the deleteCustomer portion is executed I can see the message being written to the session if I console.log() inside the function, but when it redirects back to /customers, the session no longer has my messages.

0 Answers
Related