Skip to content
IC Reactor

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

Restores an existing session without a popup. Resolves to the recovered Identity, or undefined when there is no session to restore (or the optional @icp-sdk/auth peer is not installed):

const { authenticate } = useAuth()
const identity = await authenticate()
Property Type Description
login (options?) => Promise<void> Triggers the login flow
logout (options?: { returnTo?: string }) => Promise<void> Logs the user out
authenticate () => Promise<Identity | undefined> Restores an existing session without a popup
isAuthenticated boolean Whether the user is currently authenticated
isAuthenticating boolean Whether an authentication process is in progress
identity Identity | null The current user’s @icp-sdk/core/agent Identity
principal Principal | null The current user’s @icp-sdk/core/principal Principal
error Error | undefined Last 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}</>
}