Session not updating after redirect

Issue

I’m trying to create a login system and having some very strange issues.

Page code:

const { email, password } = req.body;
if(!email ||!password) return res.status(400).send("Missing required fields");

let user = await client.fetchUser({ username: email });
if(!user) user = await client.fetchUser({ email });

if(!user) return res.render("login.ejs", {bot:client,message:"Invalid email or password",type:"error"});

const valid = await bcrypt.compare(password, user.account.password);
if(!valid) return res.render("login.ejs", {bot:client,message:"Invalid email or password",type:"error"});

req.session.user = {
   username: user.account.username,
   password: user.account.password
}
return res.redirect('/dashboard');

When doing

return res.status(200).send("Success");

It works.

I’ve tried doing await req.session.save() but that does not work either.
Also did some extensive googling and couldn’t find an answer.

Please note: this is a POST request.

Solution

Sessions are not automatically saved by res.redirect. And req.session.save() does not return a promise but requires a callback function:

req.session.save(function(err) {
  if (err) console.log(err);
  else res.redirect("/dashboard");
});

Answered By – Heiko Theißen

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.