The useSession() hook is one of the most frequently utilized primitives in the Wacht React SDK. It provides synchronous access to the active user’s authentication context, the raw Session object, and utilities for fetching secure API tokens.
If you are communicating with your own backend servers, you must attach a secure Bearer token to your API requests to prove the user’s identity.You can retrieve a fresh .getToken() method directly from the useSession hook.
Copy
import { useSession } from "@wacht/react-router";import { useEffect, useState } from "react";export function DataFetcher() { const { session, getToken } = useSession(); const [data, setData] = useState(null); useEffect(() => { async function fetchData() { // 1. Ensure a session exists before fetching if (!session) return; try { // 2. Await the minting of a short-lived JWT const token = await getToken(); // 3. Attach it to your Authorization header const res = await fetch("https://api.yourdomain.com/v1/protected-data", { headers: { Authorization: `Bearer ${token}` } }); const json = await res.json(); setData(json); } catch (err) { console.error("Failed to fetch secure data", err); } } fetchData(); }, [session, getToken]); return <pre>{JSON.stringify(data, null, 2)}</pre>;}
The session object will automatically become null if the user’s session expires, if they are logged out remotely (via the Wacht API), or if their session is forcefully revoked. Because React state automatically invalidates, any component using useSession() will instantly re-render to reflect the logged-out state.