Skip to main content

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:
npm install @ouim/logto-authkit

Basic Usage

Wrap your application with AuthProvider at the root level:
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

config
LogtoConfig
required
Logto configuration object containing authentication settings.
callbackUrl
string
The URL to redirect to after authentication. Defaults to current page.
<AuthProvider callbackUrl="/callback" config={config}>
enablePopupSignIn
boolean
default:"false"
Enable popup-based sign-in instead of full page redirects.
<AuthProvider enablePopupSignIn={true} config={config}>
customNavigate
(url: string, options?: NavigationOptions) => void
Custom navigation function for framework-specific routing (e.g., Next.js router).
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)
        }
      }}
    >
  )
}
children
React.ReactNode
required
Your application components that need access to authentication context.

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
When enablePopupSignIn is enabled, sign-in operations open in a popup window instead of redirecting the entire page:
<AuthProvider config={config} enablePopupSignIn={true} callbackUrl="/callback">
  {children}
</AuthProvider>
Popup sign-in provides a better user experience as it doesn’t interrupt the user’s current page state.

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

app/layout.tsx
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)

'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):
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

Always wrap your entire application with AuthProvider to ensure all components have access to authentication context.
Store sensitive configuration like endpoint and appId in environment variables, not hardcoded in your source.
For better user experience, enable enablePopupSignIn to avoid full page redirects during authentication.
The provider includes built-in SSR handling with ClientOnly wrapper. No additional configuration needed for Next.js.

Troubleshooting

If you see “useAuthContext must be used within an AuthProvider” error, ensure the AuthProvider wraps your component tree.
The provider automatically handles token refresh and manages authentication state across page navigations.

useAuth Hook

Access authentication state and methods

CallbackPage

Handle authentication callbacks

UserCenter

Pre-built user menu component

Route Protection

Protect routes and pages