Skip to content

useAuth

useAuth is the primary hook for interacting with the OIDC authentication state. It must be called within an AuthProvider.

Terminal window
npm install oidc-js-preact
import { useAuth } from "oidc-js-preact";
function Profile() {
const { isAuthenticated, isLoading, user, tokens, error, actions } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!isAuthenticated) return <button onClick={() => actions.login()}>Log in</button>;
return (
<div>
<p>Hello, {user?.claims.sub}</p>
<button onClick={() => actions.logout()}>Log out</button>
</div>
);
}
PropertyTypeDescription
configOidcConfigThe OIDC configuration
userAuthUser | nullThe authenticated user (claims + profile)
isAuthenticatedbooleanWhether the user is logged in
isLoadingbooleanWhether initialization is in progress
errorError | nullThe most recent auth error
tokensAuthTokensCurrent access, id, and refresh tokens
actionsAuthActionsMethods for login, logout, refresh, fetchProfile
ActionDescription
login(options?)Redirect to IdP login. Options: returnTo, extraParams
logout()Clear state and redirect to IdP logout endpoint
refresh()Exchange refresh token for new tokens
fetchProfile()Fetch the UserInfo endpoint and update user.profile
interface AuthTokens {
access: string | null;
id: string | null;
refresh: string | null;
expiresAt: number | null;
}

Tokens are stored in memory only. They are never persisted to localStorage or sessionStorage.