log out function in passport js

Posted by masis on Tue Jun 21 2022

I will briefly discuss the logout function using passportjs.  Passport is an authentication library which is extensible with a lot of plugins already developed to allow many forms of authentication to issue your authorization method.  The passportjs documentation seems outdated especially for the logout function, but with some googling and stackoverflow
I figured out how to log out of my user session properly for my application.

My original logout function had the following argument with a callback function:

app.post('/logout', function(req, res){

After dealing with different errors and inspecting the console and troubleshooting,
I realized I needed to include a middleware third argument and searching different stackoverflow
forums I added the following:

app.post('/logout', function(req, res, next) {
    req.logout(function(err) {
      if (err) { return next(err); }

In addition using express-session library, my session was being stored and would not log out properly
without a middleware.  I had to add "session: false" so I won't get my session cached after a logout

And also I added a DEELTE method in addition to POST method for the logout button.

<form action="/logout?_method=DELETE" method="POST">
        <button type="submit">Log Out</button>