Skip to main content

useSession()

The useSession() hook serves as the primary authentication primitive within the Wacht frontend SDKs. It provides synchronous access to the active user’s authentication session, facilitates the management of multi-tenancy context (organizations and workspaces), and exposes the .getToken() method required for securely authenticating requests against backend infrastructure.

Hook Import

import { useSession } from "@wacht/nextjs";

Hook Interface

loading
boolean
Indicates whether the SDK is currently resolving the authentication status via network verification or local storage access. It is critically important to evaluate this state prior to rendering protected components.
session
Session | null
The currently active Session object. In instances where the user is unauthenticated or the session has expired, this property resolves to null.
error
Error | null
Captures exceptions occurring during session retrieval or mutation operations.

Token Acquisition

getToken
(template?: string) => Promise<string>

Session Management

signOut
(signInId?: string) => Promise<void>
switchSignIn
(signInId: string) => Promise<void>

Multi-Tenancy Operations

switchOrganization
(organizationId?: string) => Promise<void>
switchWorkspace
(workspaceId: string) => Promise<void>

Advanced Initialization

exchangeTicket
(ticket: string) => Promise<void>
refetch
() => Promise<void>
Forces the SDK to execute a network request, ensuring the local session snapshot is entirely synchronized with the authoritative server state.

Implementation Guidelines

Conditional Rendering

The primary utility of the useSession() hook is governing access to protected interface elements based on the resolved session state:
import { useSession } from "@wacht/nextjs";

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

  // The loading state must be verified to prevent layout shifting or hydration mismatches
  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 bg-white">
      <h1 className="text-xl font-semibold tracking-tight text-gray-900">Application Dashboard</h1>
      
      {session ? (
        <div className="flex items-center gap-6">
          <span className="text-sm font-medium text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded border border-emerald-200">
            Authenticated Entity
          </span>
          <button 
            onClick={() => signOut()} 
            className="text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors"
          >
            Terminate Session
          </button>
        </div>
      ) : (
        <a href="/login" className="text-sm font-medium bg-gray-900 text-white px-4 py-2 rounded-md hover:bg-gray-800 transition-colors">
          Authenticate
        </a>
      )}
    </header>
  );
}

Secure API Communication

Interacting with external backend infrastructure necessitates the extraction and attachment of a signed JWT via the getToken() method:
import { useSession } from "@wacht/nextjs";
import { useEffect, useState } from "react";

export function SecureDataView() {
  const { session, getToken } = useSession();
  const [data, setData] = useState<any>(null);

  useEffect(() => {
    async function retrieveProtectedResource() {
      // Abort data retrieval if the session context is invalid
      if (!session) return;

      try {
        // Obtains a verified token from the internal cache or forces local minting if required
        const authorizationToken = await getToken();

        const response = await fetch("https://api.your-system.com/v1/protected-resource", {
          headers: {
            Authorization: `Bearer ${authorizationToken}`
          }
        });
        
        if (!response.ok) throw new Error("Resource authorization failed");
        
        const payload = await response.json();
        setData(payload);
      } catch (err) {
        console.error("Data retrieval encounter an error:", err);
      }
    }

    retrieveProtectedResource();
  }, [session, getToken]);

  return (
    <div className="p-4 bg-gray-50 rounded-lg border border-gray-200 font-mono text-sm overflow-x-auto text-gray-800">
      {data ? JSON.stringify(data, null, 2) : "Awaiting securely fetched resource data..."}
    </div>
  );
}

Session Invalidation Architecture

The Wacht architecture dictates that the session object will immediately transition to null on the client if the session naturally expires, or if the authorization grant is revoked at the server level (e.g., via administrative action). This ensures React components strictly dependent on the hook automatically unmount protected views without requiring manual polling implementations.