> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ouim.me/llms.txt
> Use this file to discover all available pages before exploring further.

# useAuth

> React hook for managing authentication state and access control

## Overview

The `useAuth` hook provides access to authentication state and handles automatic redirects based on authentication status and middleware configuration.

## Signature

```typescript theme={null}
function useAuth(options?: AuthOptions): AuthContextType
```

## Parameters

<ParamField path="options" type="AuthOptions" optional>
  Configuration options for authentication behavior

  <Expandable title="AuthOptions properties">
    <ParamField path="middleware" type="'auth' | 'guest' | undefined" optional>
      Defines the authentication requirement for the current page:

      * `'auth'`: Requires authentication (redirects unauthenticated users)
      * `'guest'`: Guest-only page (redirects authenticated users)
      * `undefined`: No automatic redirects
    </ParamField>

    <ParamField path="redirectTo" type="string" optional default="/404">
      URL to redirect to when `middleware: 'auth'` and user is not authenticated
    </ParamField>

    <ParamField path="redirectIfAuthenticated" type="string" optional>
      URL to redirect to when `middleware: 'guest'` and user is authenticated
    </ParamField>

    <ParamField path="navigationOptions" type="NavigationOptions" optional>
      Navigation behavior options

      <Expandable title="NavigationOptions properties">
        <ParamField path="replace" type="boolean" optional default={false}>
          Use `replaceState` instead of `pushState` for navigation
        </ParamField>

        <ParamField path="force" type="boolean" optional default={false}>
          Force navigation even if already on the same page
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

## Returns

<ResponseField name="AuthContextType" type="object">
  Authentication context object containing user state and authentication methods

  <Expandable title="AuthContextType properties">
    <ResponseField name="user" type="LogtoUser | null">
      Current authenticated user object, or `null` if not authenticated

      <Expandable title="LogtoUser properties">
        <ResponseField name="id" type="string" required>
          Unique user identifier
        </ResponseField>

        <ResponseField name="name" type="string" optional>
          User's display name
        </ResponseField>

        <ResponseField name="email" type="string" optional>
          User's email address
        </ResponseField>

        <ResponseField name="avatar" type="string" optional>
          URL to user's avatar image
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="isLoadingUser" type="boolean">
      Loading state indicator for user authentication status
    </ResponseField>

    <ResponseField name="signIn" type="(callbackUrl?: string, usePopup?: boolean) => Promise<void>">
      Function to initiate sign-in flow
    </ResponseField>

    <ResponseField name="signOut" type="(options?: { callbackUrl?: string; global?: boolean }) => Promise<void>">
      Function to sign out the current user
    </ResponseField>

    <ResponseField name="refreshAuth" type="() => Promise<void>">
      Function to refresh authentication state
    </ResponseField>

    <ResponseField name="enablePopupSignIn" type="boolean" optional>
      Whether popup sign-in is enabled
    </ResponseField>
  </Expandable>
</ResponseField>

## Examples

### Basic Usage

```tsx theme={null}
import { useAuth } from '@ouim/logto-authkit'

function Profile() {
  const { user, isLoadingUser } = useAuth()

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

  if (!user) {
    return <div>Not authenticated</div>
  }

  return (
    <div>
      <h1>Welcome, {user.name}</h1>
      <p>Email: {user.email}</p>
    </div>
  )
}
```

### Protected Route

```tsx theme={null}
import { useAuth } from '@ouim/logto-authkit'

function Dashboard() {
  const { user, signOut } = useAuth({
    middleware: 'auth',
    redirectTo: '/login'
  })

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Welcome, {user?.name}</p>
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  )
}
```

### Guest-Only Route

```tsx theme={null}
import { useAuth } from '@ouim/logto-authkit'

function Login() {
  const { signIn } = useAuth({
    middleware: 'guest',
    redirectIfAuthenticated: '/dashboard'
  })

  return (
    <div>
      <h1>Login</h1>
      <button onClick={() => signIn()}>Sign In</button>
    </div>
  )
}
```

### Custom Navigation Options

```tsx theme={null}
import { useAuth } from '@ouim/logto-authkit'

function ProtectedPage() {
  const { user } = useAuth({
    middleware: 'auth',
    redirectTo: '/login',
    navigationOptions: {
      replace: true, // Use replace instead of push
      force: false
    }
  })

  return <div>Protected content</div>
}
```

## Behavior

* The hook automatically handles redirects based on the `middleware` option and authentication state
* Redirects only occur after the loading state completes (`isLoadingUser` is `false`)
* When `middleware: 'auth'` is set and user is not authenticated, redirects to `redirectTo` (defaults to `/404`)
* When `middleware: 'guest'` is set and user is authenticated, redirects to `redirectIfAuthenticated`
* The hook memoizes options to prevent infinite re-renders when the options object reference changes

## See Also

* [AuthProvider](/logto-authkit/api/components/auth-provider) - Provider component required to use this hook
* [verifyAuth](/logto-authkit/api/server/verify-auth) - Server authentication verification
