Skip to main content

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.

Overview

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

Signature

function useAuth(options?: AuthOptions): AuthContextType

Parameters

options
AuthOptions
Configuration options for authentication behavior

Returns

AuthContextType
object
Authentication context object containing user state and authentication methods

Examples

Basic Usage

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

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

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

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