End Auth0 User Session with the logout Method from useAuth0 Hook

Will Johnson
InstructorWill Johnson
Share this video with your friends

Social Share Links

Send Tweet

You can log out users from your React application by logging them out of their Auth0 sessions using the logout() method from the Auth0 React SDK.

Create a logout-button.js file in the src/components/buttons folder

Create a logout button component with the following code

import { useAuth0 } from "@auth0/auth0-react";
import React from "react";

export const LogoutButton = () => {
  const { logout } = useAuth0();

  const handleLogout = () => {
    logout({
      logoutParams: {
        returnTo: window.location.origin,
      },
    });
  };

  return (
    <button className="button__logout" onClick={handleLogout}>
      Log Out
    </button>
  );
};

The `logout() method from Auth0 React SDK clears the application session and redirects to the Auth0 /v2/logout endpoint to clear the Auth0 session.

You can pass an object argument to logout() to customize the logout behavior of the React application. You can define a logoutParams property on that object to define parameters for the /v2/logout call. This process is invisible to the user.

Pass the logoutParams.returnTo option to specify the URL where Auth0 should redirect your users after they log out.

Setting logoutParams.returnTo to window.location.origin will ensure that Auth0 redirects your users to your production URL that you add to the "Allowed Logout URLs" list.

Instructor: [0:00] Inside of the buttons folder, create a LogoutButton file. Then import the useAuth0 hook from the Auth0 React SDK, as well as React from React. Then create a component call LogoutButton. Then we'll grab the logout method from the useAuth0 hook.

[0:21] The logout method clears the React application session and redirects the user to the Auth0/V2/logout endpoint to clear the Auth0 session under the hood. Create a function called handleLogout, and then call logout passed in an object as an argument.

[0:40] Then we'll use logout params as the property. Logout params defines the parameters for the call to the /V2 /logout endpoint. The property will be returned to and the value of return to is window.location.origin, which will return the base URL.

[1:00] Then finally return some JSX, which will be a button with a class name of logout__button and onClick Handler with the handleLogout function. Then we'll set the copy to logout.

[1:17] To recap, creating the LogoutButton, we imported the useAuth0 hook from the Auth0 React SDK. We created a LogoutButton component. We also grabbed the logout method from the useAuth0 hook. Created a function called handleLogout, called logout, passed in an object as an argument.

[1:41] Used logout params as the property and used the return to property and set it to window.location.origin. Then we returned some JSX that was a button with an onClick handler that called the handleLogout function.