Skip to content

Getting authentication status

Throughout your app, you may want to gate certain user experiences based on whether the current user is authenticated or not. Privy makes it easy to check your user's authentication status and handle it appropriately.

TIP

Before determining a user's auth status from Privy, you should verify that Privy has fully initialized and is ready.

You can use the boolean authenticated from the usePrivy hook to determine if your user is authenticated or not.

tsx
const {authenticated} = usePrivy();

Below is an example of using authenticated in a component that should only be shown to authenticated users. Notice how the value of authenticated is used to determine whether to redirect users to the login page or not.

tsx
import {useRouter} from 'next/router';

import {usePrivy} from '@privy-io/react-auth';

export default function MyComponent() {
  const {ready, authenticated, user} = usePrivy();
  const router = useRouter();

  if (!ready) {
    // Do nothing while the PrivyProvider initializes with updated user state
    return <></>;
  }

  if (ready && !authenticated) {
    // Replace this code with however you'd like to handle an unauthenticated user
    // As an example, you might redirect them to a login page
    router.push('/login');
  }

  if (ready && authenticated) {
    // Replace this code with however you'd like to handle an authenticated user
    return <p>User {user?.id} is logged in.</p>;
  }
}

TIP

In the example above, checking ready ensures that we do not redirect an already-authenticated user to a 'Sign In' page based off of outdated user state that will be updated soon after page load.