Skip to main content

useSession()

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.

Import

import { useSession } from "@wacht/react-router";

Anatomy

loading
boolean
Boolean indicating if the SDK is currently making a network request or loading state.
session
Session | null
The current Session object (or null if unauthenticated).
error
Error | null
Any error that occurred during session fetching or manipulation.
getToken
(template?: string) => Promise<string>
signOut
(signInId?: string) => Promise<void>
switchSignIn
(signInId: string) => Promise<void>
switchOrganization
(organizationId?: string) => Promise<void>
switchWorkspace
(workspaceId: string) => Promise<void>
exchangeTicket
(ticket: string) => Promise<void>
refetch
() => Promise<void>
Manually triggers a re-fetch of the session data from the server.

Usage: Conditional Rendering

The most common use case for useSession() is gating UI elements based on authentication status when laying out complex, stateful pages.
import { useSession } from "@wacht/react-router";

export function DashboardHeader() {
  const { loading, session } = useSession();

  // Always handle the loading state first to prevent hydration errors or UI flashes
  if (loading) {
    return <div className="h-16 bg-zinc-100 animate-pulse w-full border-b" />;
  }

  return (
    <header className="flex items-center justify-between p-4 border-b">
      <h1 className="text-xl font-bold">Acme Corp</h1>
      
      {session ? (
        <span className="text-sm font-medium text-emerald-600 bg-emerald-50 px-2 py-1 rounded">
          Status: Authenticated
        </span>
      ) : (
        <a href="/login" className="text-sm font-medium text-zinc-600 hover:text-zinc-900">
          Sign In
        </a>
      )}
    </header>
  );
}

Usage: Fetching Secure JWTs

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.
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>;
}

Session Expiration

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.