How to implement a logout method in an Express application

Destroying the session to log out a user

Now that we are able to log in a user in our Express application, after it's being authenticated using a session, we can think of setting up a logout method.

In our application we have a specific router that defines all the authorization routes, called authRouter, so let's set up the logout route handler there as well.

Now the question is: what HTTP method are we going to use for the logout endpoint?
We could use a variety of methods, like POST or GET, but in my opinion, the most logical method to use is the DELETE method.

The reason I would use DELETE is because all we will be doing as a result of calling this route handler is a delete, or destroy, operation. We will destroy the cookie, and by doing so we will take authorization away from the user, so they would be effectively unable to reach protected endpoints.

router.delete('/logout', (req, res) => {

  // ... logout code here ...

})

A logout action only happens in the context of a session. So, we need to check if a session exists, and if so we call its destroy() method, so it will be removed.

if (req.session) {
  req.session.destroy();
}

If something goes wrong while destroying the session, the destroy() method gets passed an error object. We can handle this possible error with a callback function.
Our function will simply send back an error status code and a message.

If there is no error, we can send back a logout confirmation message instead. In this case, a success status code will be sent back by default.

req.session.destroy(err => {
  if (err) {
    res.status(400).send('Unable to log out')
  } else {
    res.send('Logout successful')
  }
});

Of course, if there is no session in the first place, we just end the request there and then, because there is nothing for us to do. We can't log out a user that's not logged in.

Here's the full code for the logout route handler:

// DELETE /api/auth/logout
router.delete('/logout', (req, res) => {
  if (req.session) {
    req.session.destroy(err => {
      if (err) {
        res.status(400).send('Unable to log out')
      } else {
        res.send('Logout successful')
      }
    });
  } else {
    res.end()
  }
})

If we now log in a user and then call the log out endpoint, the sessions will be destroyed, the user will get an appropriate logout message and won't be able to access restricted endpoints anymore.


Did you like this article? Share it with your friends.
I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!

Follow me on Twitter