Create a Picture Competition Website in Express JS, MEVN

Logout

Since now the user is logged-in, we need to make him able to log out. We will clear the authentication token from Mongo DB once the user is logged out. We just need to create a “doLogout” function in our “navApp” object in the “footer.ejs” file:

doLogout: function () {
	// send beacon to server before redirecting
    var formData = new FormData();
    formData.append("accessToken", localStorage.getItem(accessTokenKey));

    navigator.sendBeacon(this.baseUrl + "/logout", formData);

    // remove access token from local storage
    localStorage.removeItem(accessTokenKey);
    return true;
},

Then we need to create a POST route in our “server.js” file that will clear out the authentication token from Mongo DB.

// empty the access token of user (logout)
app.post("/logout", async function (request, result) {
    var accessToken = request.fields.accessToken;
 
    await db.collection("users").findOneAndUpdate({
        "accessToken": accessToken
    }, {
        $set: {
            "accessToken": ""
        }
    });
 
    result.json({
        "status": "success",
        "message": "User has been logged out."
    });
});

Refresh the page now and try to click the “Log out” button. You will be redirected to the login page and you will again see the login and sign up button at the top navigation bar. The “accessToken” value from the “users” collection will also get empty from Mongo DB.