Skip to content

useAuth

useAuth is the primary hook for authentication. It automatically initializes the client on mount and provides access to auth state and methods.

import { useAuth } from "./reactor/hooks"
function AuthButton() {
const {
login, // Function to trigger login
logout, // Function to trigger logout
authenticate, // Function to authenticate without popup
isAuthenticated, // boolean
isAuthenticating, // boolean
identity, // Identity | null
principal, // Principal | null
error, // Error | undefined
} = useAuth()
return isAuthenticated ? (
<button onClick={logout}>Logout {principal?.toText()}</button>
) : (
<button onClick={() => login()}>Login</button>
)
}

Triggers the Internet Identity login flow:

login({
// Identity provider URL (auto-detected based on network)
identityProvider?: string,
// Session duration in nanoseconds
maxTimeToLive?: bigint,
// Callback on successful login
onSuccess?: () => void,
// Callback on login error
onError?: (error: string) => void,
})

Logs out and clears the session:

const { logout } = useAuth()
logout() // Clears session and updates state

Authenticates the user without a popup. Useful for re-authenticating an existing session:

const { authenticate } = useAuth()
await authenticate()
PropertyTypeDescription
login(options?) => Promise<void>Triggers the login flow
logout() => Promise<void>Logs the user out
authenticate() => Promise<void>Authenticates without popup
isAuthenticatedbooleanWhether the user is currently authenticated
isAuthenticatingbooleanWhether an authentication process is in progress
identityIdentity | nullThe current user’s @icp-sdk/core/agent Identity
principalPrincipal | nullThe current user’s @icp-sdk/core/principal Principal
errorError | undefinedLast authentication error
import { useAuth } from "../reactor/hooks"
import { Navigate, useLocation } from "react-router-dom"
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isAuthenticating } = useAuth()
const location = useLocation()
if (isAuthenticating) return <Loading />
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />
}
return <>{children}</>
}