Nevzat
Nevzat

Reputation: 35

How to destroy session?

I wanna be able to destroy a session after the user logs out. At the moment it's not working as expected. The session doesn't get destroyed.

I'm able to print the console.log() from the logout route.

That's the code I've used so far:

Frontend

const handleLogout = async (e) => {
    e.preventDefault();
    try {
      await fetch("http://localhost:4000/logout", {
        method: "GET",
      });
    } catch (error) {
      console.error(error.message);
    }
  };

Backend

app.get("/logout", (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      return console.log(err);
    }
    res.send("logged out");
    console.log("logged out");
  });
});

I don't know if this helps but here is the session: enter image description here

P.S. I'm using react, node, express and express-session.

Thanks in advance!

Upvotes: 2

Views: 2696

Answers (1)

jfriend00
jfriend00

Reputation: 707148

req.session.destory() removes the session id from the server-side session store and that will render the client logged out since the session id is removed from the server-side session store and can no longer match the client cookie on future requests. It does not, however, remove the now-orphaned session cookie from the browser.

To do that, you need a res.clearCookie(cookieName) before you do the res.send("logged out"); where you target the name of whatever your session cookie is. That will send the proper header with the response to tell the browser to clear that cookie.

Upvotes: 2

Related Questions