Using express-session and connect-mongodb for session based authentication (or trying to at least). I have a logout route that is calling req.session.destroy(), I have the unset
property set to "destroy"
and the sessions are still showing up in my mongo database. I’ve tried playing with different credentials
on my client-side fetch but to no avail. I’m very new and trying to understand the basics of authentication but this detail is tripping me up.
I may also not necessarily NEED to delete the session from the store but I’d like to keep the db as clean as possible. Any help would be appreciated, thank you so much!
Here is my session config:
app.use(
session({
name: process.env.SESSION_NAME,
secret: process.env.SESSION_SECRET,
store: MongoStore.create({
// use the client already set up with mongoose to limit connections
clientPromise: client,
}),
cookie: {
secure: false,
// 30 minute idle timeout
maxAge: 1000 * 60 * 30,
},
rolling: true,
resave: false,
saveUninitialized: false,
// deletes the session from the db
unset: "destroy",
})
);
Here is my logout route:
router.post("/api/logout", async (req, res, next) => {
try {
await logout(req, res);
res.json({ message: "Logged out." });
} catch (error) {
next(error);
}
});
Logout helper function:
export const logout = (req, res) => {
return new Promise((resolve, reject) => {
req.session.destroy(err => {
req.session = null;
if (err) {
reject(err);
}
res.clearCookie(process.env.SESSION_NAME);
resolve();
});
});
};
Client-side code:
await fetch("http://localhost:3000/api/logout", {
method: "POST",
credentials: "include",
});
I can send along more snippets if needed, thank you!
Matthew DeFusco is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.