> ## 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.

# AuthProvider

> The main authentication provider component that wraps your application

## Overview

The `AuthProvider` component is the core wrapper for logto-authkit authentication. It manages authentication state, handles sign-in/sign-out operations, and provides auth context to your entire application.

## Installation

The `AuthProvider` is included in the logto-authkit package:

```bash theme={null}
npm install @ouim/logto-authkit
```

## Basic Usage

Wrap your application with `AuthProvider` at the root level:

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

function App() {
  return (
    <AuthProvider
      config={{
        endpoint: process.env.NEXT_PUBLIC_LOGTO_ENDPOINT!,
        appId: process.env.NEXT_PUBLIC_LOGTO_APP_ID!,
        resources: [process.env.NEXT_PUBLIC_LOGTO_RESOURCE!],
      }}
      callbackUrl="/callback"
    >
      {/* Your app components */}
    </AuthProvider>
  )
}
```

## Props

<ParamField path="config" type="LogtoConfig" required>
  Logto configuration object containing authentication settings.

  <Expandable title="LogtoConfig properties">
    <ParamField path="endpoint" type="string" required>
      Your Logto instance endpoint URL
    </ParamField>

    <ParamField path="appId" type="string" required>
      Your Logto application ID
    </ParamField>

    <ParamField path="resources" type="string[]">
      Array of API resource identifiers
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="callbackUrl" type="string">
  The URL to redirect to after authentication. Defaults to current page.

  ```tsx theme={null}
  <AuthProvider callbackUrl="/callback" config={config}>
  ```
</ParamField>

<ParamField path="enablePopupSignIn" type="boolean" default="false">
  Enable popup-based sign-in instead of full page redirects.

  ```tsx theme={null}
  <AuthProvider enablePopupSignIn={true} config={config}>
  ```
</ParamField>

<ParamField path="customNavigate" type="(url: string, options?: NavigationOptions) => void">
  Custom navigation function for framework-specific routing (e.g., Next.js router).

  <Expandable title="NavigationOptions">
    <ParamField path="replace" type="boolean">
      Use replaceState instead of pushState
    </ParamField>

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

  ```tsx theme={null}
  import { useRouter } from 'next/router'

  function App() {
    const router = useRouter()
    
    return (
      <AuthProvider
        config={config}
        customNavigate={(url, options) => {
          if (options?.replace) {
            router.replace(url)
          } else {
            router.push(url)
          }
        }}
      >
    )
  }
  ```
</ParamField>

<ParamField path="children" type="React.ReactNode" required>
  Your application components that need access to authentication context.
</ParamField>

## Features

### Automatic State Management

The `AuthProvider` automatically:

* Fetches and updates user information when authentication state changes
* Handles JWT token storage in cookies
* Syncs authentication across browser tabs and windows
* Refreshes auth state on window focus
* Manages loading states during authentication operations

### Popup Sign-In Support

When `enablePopupSignIn` is enabled, sign-in operations open in a popup window instead of redirecting the entire page:

```tsx theme={null}
<AuthProvider config={config} enablePopupSignIn={true} callbackUrl="/callback">
  {children}
</AuthProvider>
```

<Info>Popup sign-in provides a better user experience as it doesn't interrupt the user's current page state.</Info>

### Cross-Tab Synchronization

Authentication state is automatically synchronized across browser tabs:

* Sign in on one tab → all tabs update
* Sign out on one tab → all tabs update
* Uses localStorage events and custom event dispatching

### Error Handling

The provider includes robust error handling:

* Automatic logout on invalid/expired tokens
* Rate limiting to prevent excessive API calls
* Graceful fallback for popup authentication failures

## Advanced Usage

### Next.js App Router

```tsx app/layout.tsx theme={null}
import { AuthProvider } from '@ouim/logto-authkit'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <AuthProvider
          config={{
            endpoint: process.env.NEXT_PUBLIC_LOGTO_ENDPOINT!,
            appId: process.env.NEXT_PUBLIC_LOGTO_APP_ID!,
            resources: [process.env.NEXT_PUBLIC_LOGTO_RESOURCE!],
          }}
          callbackUrl="/callback"
          enablePopupSignIn={true}
        >
          {children}
        </AuthProvider>
      </body>
    </html>
  )
}
```

### With Custom Navigation (Next.js)

```tsx theme={null}
'use client'

import { AuthProvider } from '@ouim/logto-authkit'
import { useRouter } from 'next/navigation'

export function AuthProviderWrapper({ children }: { children: React.ReactNode }) {
  const router = useRouter()

  return (
    <AuthProvider
      config={{
        endpoint: process.env.NEXT_PUBLIC_LOGTO_ENDPOINT!,
        appId: process.env.NEXT_PUBLIC_LOGTO_APP_ID!,
      }}
      customNavigate={(url, options) => {
        if (options?.replace) {
          router.replace(url)
        } else {
          router.push(url)
        }
      }}
    >
      {children}
    </AuthProvider>
  )
}
```

## Context Value

The `AuthProvider` exposes the following context value (accessible via `useAuth` hook):

```typescript theme={null}
interface AuthContextType {
  user: LogtoUser | null
  isLoadingUser: boolean
  signIn: (callbackUrl?: string, usePopup?: boolean) => Promise<void>
  signOut: (options?: { callbackUrl?: string; global?: boolean }) => Promise<void>
  refreshAuth: () => Promise<void>
  enablePopupSignIn?: boolean
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Place at the root of your application">
    Always wrap your entire application with `AuthProvider` to ensure all components have access to authentication context.
  </Accordion>

  <Accordion title="Use environment variables for config">
    Store sensitive configuration like `endpoint` and `appId` in environment variables, not hardcoded in your source.
  </Accordion>

  <Accordion title="Enable popup sign-in for better UX">
    For better user experience, enable `enablePopupSignIn` to avoid full page redirects during authentication.
  </Accordion>

  <Accordion title="Handle SSR properly">
    The provider includes built-in SSR handling with `ClientOnly` wrapper. No additional configuration needed for Next.js.
  </Accordion>
</AccordionGroup>

## Troubleshooting

<Warning>
  If you see "useAuthContext must be used within an AuthProvider" error, ensure the `AuthProvider` wraps your component tree.
</Warning>

<Check>The provider automatically handles token refresh and manages authentication state across page navigations.</Check>

## Related

<CardGroup cols={2}>
  <Card title="useAuth Hook" icon="hook" href="/logto-authkit/frontend/use-auth">
    Access authentication state and methods
  </Card>

  <Card title="CallbackPage" icon="arrow-right-to-bracket" href="/logto-authkit/frontend/callback-page">
    Handle authentication callbacks
  </Card>

  <Card title="UserCenter" icon="user" href="/logto-authkit/frontend/user-center">
    Pre-built user menu component
  </Card>

  <Card title="Route Protection" icon="lock" href="/logto-authkit/frontend/route-protection">
    Protect routes and pages
  </Card>
</CardGroup>
