Skip to main content
useAuth is a client-side React hook that provides access to the authentication context created by AuthKitProvider. It returns the current user, session data, and methods for authentication operations.

Usage

'use client';

import { useAuth } from '@workos-inc/authkit-nextjs';

export function UserProfile() {
  const { user, loading } = useAuth();

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!user) {
    return <div>Not signed in</div>;
  }

  return <div>Welcome, {user.email}</div>;
}

Signature

function useAuth(options?: { ensureSignedIn?: boolean }): AuthContextType;

function useAuth(options: { ensureSignedIn: true }): 
  AuthContextType & (
    | { loading: true; user: User | null }
    | { loading: false; user: User }
  );

Parameters

options.ensureSignedIn
boolean
default:"false"
When true, the hook will automatically trigger authentication if no user is signed in. This narrows the TypeScript type to guarantee a User object when loading is false.
const { user, loading } = useAuth({ ensureSignedIn: true });

if (!loading) {
  // TypeScript knows user is not null here
  console.log(user.email);
}

Return value

user
User | null
The authenticated user object from WorkOS, or null if not authenticated.
interface User {
  id: string;
  email: string;
  firstName?: string;
  lastName?: string;
  emailVerified: boolean;
  profilePictureUrl?: string;
  createdAt: string;
  updatedAt: string;
}
sessionId
string | undefined
The current session ID.
organizationId
string | undefined
The ID of the organization the user is currently in.
role
string | undefined
The user’s role in the current organization.
roles
string[] | undefined
Array of all roles assigned to the user.
permissions
string[] | undefined
Array of permissions granted to the user.
entitlements
string[] | undefined
Array of entitlements for the user.
featureFlags
string[] | undefined
Array of feature flags enabled for the user.
impersonator
Impersonator | undefined
Information about the admin impersonating this user, if applicable.
interface Impersonator {
  email: string;
  reason: string | null;
}
loading
boolean
Indicates whether authentication data is being loaded.
getAuth
(options?: { ensureSignedIn?: boolean }) => Promise<void>
Fetches the latest authentication state from the server. Useful for manually refreshing user data.
const { getAuth } = useAuth();

const handleRefresh = async () => {
  await getAuth();
};
refreshAuth
(options?: { ensureSignedIn?: boolean; organizationId?: string }) => Promise<void | { error: string }>
Refreshes the authentication session by exchanging the refresh token for a new access token. Optionally switches to a different organization.
const { refreshAuth } = useAuth();

const handleSwitch = async (orgId: string) => {
  const result = await refreshAuth({ organizationId: orgId });
  if (result && 'error' in result) {
    console.error(result.error);
  }
};
signOut
(options?: { returnTo?: string }) => Promise<void>
Signs out the current user and optionally redirects to a specific URL.
const { signOut } = useAuth();

const handleSignOut = async () => {
  await signOut({ returnTo: '/goodbye' });
};
switchToOrganization
(organizationId: string, options?: SwitchToOrganizationOptions) => Promise<Omit<UserInfo, 'accessToken'> | { error: string }>
Switches the user’s active organization.
const { switchToOrganization } = useAuth();

const handleSwitch = async (orgId: string) => {
  const result = await switchToOrganization(orgId, {
    revalidationStrategy: 'none'
  });

  if ('error' in result) {
    console.error(result.error);
  }
};

Examples

Conditional rendering based on auth state

'use client';

import { useAuth } from '@workos-inc/authkit-nextjs';

export function Dashboard() {
  const { user, loading, organizationId } = useAuth();

  if (loading) {
    return <LoadingSpinner />;
  }

  if (!user) {
    return <SignInPrompt />;
  }

  return (
    <div>
      <h1>Welcome, {user.firstName || user.email}</h1>
      {organizationId && <OrganizationView orgId={organizationId} />}
    </div>
  );
}

Using ensureSignedIn for protected components

'use client';

import { useAuth } from '@workos-inc/authkit-nextjs';

export function ProtectedComponent() {
  const { user, loading } = useAuth({ ensureSignedIn: true });

  if (loading) {
    return <div>Loading...</div>;
  }

  // TypeScript knows user is not null here
  return <div>Hello, {user.email}</div>;
}

Permission-based rendering

'use client';

import { useAuth } from '@workos-inc/authkit-nextjs';

export function AdminPanel() {
  const { permissions, loading } = useAuth();

  if (loading) return <div>Loading...</div>;

  const canManageUsers = permissions?.includes('users:manage');

  return (
    <div>
      <h1>Admin Panel</h1>
      {canManageUsers && <UserManagement />}
    </div>
  );
}

Manual sign out

'use client';

import { useAuth } from '@workos-inc/authkit-nextjs';

export function SignOutButton() {
  const { signOut } = useAuth();

  return (
    <button onClick={() => signOut({ returnTo: '/' })}>
      Sign Out
    </button>
  );
}

Important notes

This hook must be used within a component that is a child of AuthKitProvider. It will throw an error if used outside the provider.
The hook is client-side only. Use the withAuth server function for server components and API routes.

AuthKitProvider

Set up the authentication provider

useAccessToken

Get the user’s access token

withAuth

Server-side authentication

Build docs developers (and LLMs) love