im using express-session with a mongo-store.
However, in my authentication process i call req.session.save() after the user is authenticated successfully. But when i try to send a response to the client i get the message Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
When i send the response before i call req.session.save() and not inside the callback, its working. This is what my code snippet looks like.
// res.json({ data: 'hello world' }); //This is working...
req.session.save((err) => {
if (err) {
console.log('Error saving session: ', err);
} else {
// res.json({ data: 'Hello CB' }); //Headers already sent
}
});
I also can see that the session is saved in my mongoDb. I couldn't find anything which tells me, that req.session.save() is sending some response to the client.
Why are the headers already sent in the callback function of req.session.save() ?
Updated full Requestfunction:
const Create = async (req, res) => {
const { code } = req.body;
await Authenticate(code)
.then((user) => {
//Check if User already exists in database
UserModel.getUser(user.id)
.then((resDB) => {
if (resDB === null) {
console.log('User not found');
//User dont exists, create it
UserModel.createUser({
...
})
.then((is_saved) => {
if (is_saved) {
res.json(user);
res.end();
}
})
} else {
req.session.regenerate((err) => {
req.session.value = "somevalue";
});
req.session.save((err) => {
if (err) {
console.log('Error saving session: ', err);
} else {
// res.json({ cookie: req.session });
res.json({ data: 'Hello from CB' });
res.end();
}
});
}
})
.catch((err) => {
console.log('User Create or Login error: ', err);
res.end();
})
})
.catch((err) => {
console.log('Authentication error', err);
res.end();
});
}
