Build a logout button with Vue
In this section, we create a custom logout button that will:
- Show a disabled state when not logged in
- Clear the user's tokens
- Redirect after logout to your After-logout path
#Example: custom logout button with Vue.js
You can clone the example logout button on CodePen(opens new window) and make edits, or follow along below.
The example form has the Userfront Core JS library added to the document, as described in the next section.
#Add the Userfront Core JS library
You can add the Userfront Core JS library by CDN or using npm.
You only need to do one of these.
#Set up the button
Create your logout button with the elements you want to use.
In this case, we're using a custom-styled <button>
element that is red when active and gray if the user is not logged in.
#Logout button Vue code
#Logout <button> element
We set the logout <button>
element to call handleLogout()
when it is clicked.
Additionally, we set the disabled
property for the button based on the isLoggedOut
variable so that the button will be gray if the user is not logged in.
#handleLogout()
When the logout button is clicked, this function calls Userfront.logout()
.
#isLoggedOut
This computed property checks Userfront.tokens.accessToken
, which is only present when the user is logged in. Thus if it is absent, the user is logged out.
#Userfront.logout()
The logout() method allows you to log out a user.
Userfront then does the following:
- Invalidates the user's current session
- Clears any Userfront-issued tokens from the browser
- Redirects the page to the After-logout path
If the user is not logged in, calling Userfront.logout()
will not do anything.
#Disabled state
We can show a disabled state by adding the disabled
property to the button.
If the user is logged out, Userfront.tokens.accessToken
will not return a value, so we can use this to set the isLoggedOut
property.
Note that you are not required to show the button when the user is not logged in; usually the logout button is only shown on pages where the user must be logged in.
#Clearing tokens
Whenever Userfront.logout()
is called, the method makes an API call to Userfront to invalidate the user's current session and clear any refresh tokens.
The method then removes the access token and ID token cookies from the browser.
#Redirect after logout
Once the user's session has been invalidated and their tokens have been cleared from the browser, the browser is redirected to your account's After-logout path.
If the user is not logged in and Userfront.logout()
is called, the browser will not be redirected.