SDKsReact SDK
useSession
React hook for accessing the current session — token, expiry, refresh, and session metadata with the HelloJohn React SDK.
useSession
The useSession hook provides access to the current authentication session, including the access token, session metadata, and refresh controls.
import { useSession } from "@hellojohn/react";
const { session, isLoading, refresh } = useSession();Return Value
| Property | Type | Description |
|---|---|---|
session | Session | null | Current session, or null if not authenticated |
isLoading | boolean | true on initial session load |
refresh | () => Promise<void> | Manually refresh the session token |
Session Object
interface Session {
id: string; // Session ID
userId: string; // User ID
accessToken: string; // JWT access token (use for API calls)
expiresAt: Date; // Access token expiry
refreshExpiresAt: Date; // Refresh token expiry
createdAt: Date; // Session creation time
lastActiveAt: Date; // Last activity timestamp
userAgent: string | null; // Browser/device user agent
ipAddress: string | null; // Last known IP
}Usage
Getting the Access Token
import { useSession } from "@hellojohn/react";
function MyComponent() {
const { session } = useSession();
async function fetchData() {
if (!session) return;
const res = await fetch("/api/data", {
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
});
// ...
}
}Checking Authentication State
const { session, isLoading } = useSession();
if (isLoading) return <Spinner />;
if (!session) return <SignInPrompt />;
return <Dashboard />;Manual Token Refresh
The SDK automatically refreshes tokens before they expire. To force a refresh manually:
const { refresh } = useSession();
// E.g., after changing permissions on the server
await refresh();Session Expiry Handling
Monitor when the session is about to expire:
import { useSession } from "@hellojohn/react";
function SessionTimer() {
const { session } = useSession();
if (!session) return null;
const msUntilExpiry = session.expiresAt.getTime() - Date.now();
const minutesLeft = Math.floor(msUntilExpiry / 60000);
return (
<p>Session expires in {minutesLeft} minutes</p>
);
}Auto-Refresh Behavior
The SDK automatically refreshes the access token when it has less than 60 seconds remaining. This happens silently in the background. The session.accessToken property always returns the latest valid token.
If the refresh token expires (user has been inactive for longer than the refresh TTL), session becomes null and the user must sign in again.