useSession
The useSession hook provides access to the current user session and methods for session management including switching organizations/workspaces and signing out.
Return Value
The current session object
Whether session data is loading
Show Refetch session data from server
Resolves when session data is refetched
Show Switch to a different sign-in (multi-session)
The sign-in ID to switch to
Resolves when the sign-in is switched
Show Sign out (all or specific session)
options
{ signInId?: string; all?: boolean }
Optional sign-in ID or sign out from all sessions
Show Get a session token (optionally for a specific token template)
Optional token template name
Show Switch active organization
The organization ID to switch to
Resolves when the organization is switched
Show Switch active workspace
The workspace ID to switch to
Resolves when the workspace is switched
Show Exchange an impersonation ticket
The ticket token to exchange
The session after ticket exchange
Session Object
interface Session {
signins : SigninAttempt [];
active_signin : {
id : string ;
user : {
id : string ;
first_name : string ;
last_name : string ;
username ?: string ;
primary_email_address : EmailAddress ;
profile_picture_url ?: string ;
has_passkeys : boolean ;
};
active_organization_membership_id ?: string ;
active_workspace_membership_id ?: string ;
};
}
Examples
import { useSession } from "@wacht/tanstack-router" ;
function UserInfo () {
const { session } = useSession ();
const user = session ?. active_signin ?. user ;
return (
< div >
< p > Name: { user ?. first_name } { user ?. last_name } </ p >
< p > Email: { user ?. primary_email_address ?. email } </ p >
</ div >
);
}
import { useSession } from "@wacht/tanstack-router" ;
function SignOutButton () {
const { signOut } = useSession ();
return (
< button onClick = { () => signOut () } >
Sign Out
</ button >
);
}
import { useSession } from "@wacht/tanstack-router" ;
function OrgSwitcher () {
const { session , switchOrganization } = useSession ();
const handleSwitch = async ( orgId : string ) => {
await switchOrganization ( orgId );
};
return < button onClick = { () => handleSwitch ( "org_123" ) } >
Switch Organization
</ button > ;
}
Get Bearer Token for API Requests
import { useSession } from "@wacht/tanstack-router" ;
async function fetchWithAuth ( url : string ) {
const { getToken } = useSession ();
const token = await getToken ();
return fetch ( url , {
headers: {
Authorization: `Bearer ${ token } ` ,
},
});
}