Skip to main content

Getting authentication status

Throughout your app, you may want to gate certain content or experiences based on whether the current user is authenticated or not. For example, you might want to prevent an unauthenticated user from accessing protected content, and instead to redirect them to a login page.

Privy makes it easy to check your user's authentication status and handle it appropriately.

Verifying that the PrivyProvider is ready

On page load, the PrivyProvider will initialize some state about the current user. This might include checking if the user has a wallet connected, refreshing expired auth tokens, fetching up-to-date user data, etc. As a consequence, it's important to wait until the PrivyProvider has finished initializing before you consume any state about the current user (e.g. whether or not they are authenticated, their user object, etc.).

To check whether the PrivyProvider has finished initializing, you should check the boolean ready from the usePrivy hook. When ready is true, the user state has properly been initialized and is safe for consumption.

Determining if your user is authenticated

Once the Privy client is ready, you can then use the boolean authenticated from the usePrivy hook to determine if your user is authenticated.

Below is an example of how you may determine the current user's authentication state:

Sample Authenticated Page
import { usePrivy } from '@privy-io/react-auth';
import { useRouter } from 'next/router';

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 sign-in page
router.push('/sign-in');
}

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 an 'Sign In' page based off of outdated user state that will be updated soon after page load.