8. Logout

In the previous chapter, we displayed a logout button on the top navbar. But it was not functional. In this chapter, we are going to make it functional. To log out a user, we first must attach an event listener that will be called when the user taps the logout button from the top navbar.

Video tutorial:

So open your AppHeader.vue file and attach an v-on:click event listener to the logout button from the dropdown menu:

<a class="dropdown-item" v-on:click="doLogout" href="javascript:void(0);">Logout</a>

Then we need to create this function in our “methods” object:

doLogout: async function () {
    const response = await axios.post(
        this.$apiURL + "/logout",
        null,
        {
            headers: this.$headers
        }
    );

    if (response.data.status == "success") {
        // remove access token from local storage
        localStorage.removeItem(this.$accessTokenKey)

        window.location.href = "/login"
    } else {
        swal.fire("Error", response.data.message, "error");
    }
},

This will call an API and if the response returned is “success”, then it will remove the access token from local storage and redirect the user to the login page. After that, we need to create an API that will handle this request. So open your server.js file and create a POST route for it:

// route for logout request
app.post("/logout", auth, async function (request, result) {
	const user = request.user

	// update JWT of user in database
	await db.collection("users").findOneAndUpdate({
		_id: user._id
	}, {
		$set: {
			accessToken: ""
		}
	})

	result.json({
		status: "success",
		message: "Logout successfully."
	})
})

Test the app now, hit the submit button, you will see that it will redirect you to the login page. You will again see the login and registration link in the navbar. And if you check your database from Mongo DB Compass, you will see that the access token field of that user becomes empty.

And if you type “localStorage” in your browser console and hit enter, you will see that the access token key is removed from local storage too.

local storage empty after successful logout
local storage empty

Your local storage might have other fields too. But if the “access token” field is removed, then it means the user is successfully logged out. You can also check from Mongo DB the accessToken field of user will become empty.