Ready-to-use logout button with React
In this section, we add an automatic 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: React logout button
It's often easier to build your own logout button than to use this automatic one.
#Install the Userfront React library
To add the form to your React project, first install @userfront/react
with npm (or yarn).
#Render the logout button in React
First, initialize the Userfront React library with your account ID using Userfront.init()
.
Build the LogoutButton
component with Userfront.build()
using the tool ID corresponding to your logout button. This can be found in the Toolkit section of the Userfront dashboard.
Render the <LogoutButton />
component in your React app.
#Disabled state
If the user is not logged in, the logout button will show in a disabled state.
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.
Whenever the user is logged in, the logout button will be clickable.
#Clearing tokens
Whenever the logout button is clicked, it makes an API call to Userfront to invalidate the user's current session and clear any refresh tokens.
The button 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 After-logout path.
If the user is not logged in and the button is clicked, the browser will not be redirected.