Skip to Content
Using the client

State

Read the client's state outside React, follow its changes, scope cached data to the session, and know what each field holds.

In a component, useAuth reads the state and re-renders when it changes. Code outside React, such as a logger, a cache or an analytics hook, reads the same state from auth.state. It holds who is signed in and where the session stands, never a token.

This page shows how to read and follow the state, what each field holds, and how to keep one account's data away from the next.

Read and follow the state

Read the state at any moment with get, and follow its changes with subscribe:

src/status-log.ts
import {  } from "./auth.js";

/** Logs each change of status. Returns a function that stops it. */
export function () {
  let  = ..().;
  const {  } = ..(({  }) => {
    if ( === ) return;
     = ;
    .(`Auth is ${}`);
  });
  return ;
}

subscribe calls the listener on each later change, not with the current state, so read the current state with get first, as logStatus does.

A listener that throws doesn't interrupt the client. Its error is thrown again asynchronously, where your error reporting can catch it.

What the state holds

The state has these fields:

FieldHolds
statusWhere the session stands, such as authenticated or unavailable. How it works lists each one.
userThe signed-in user, or null. Checking status tells TypeScript whether it's set.
sessionIdThe ID of this sign-in, or null when signed out. It's new on every sign-in, and stays the same across refreshes and profile updates.
errorThe latest failure, as an AuthError, or null. The next successful change clears it.
versionA number that changes when route guards must check the session again. connectAuth and useAuthRevalidation watch it.

version changes on a sign-in, a sign-out, a new user or a change of status. A token refresh doesn't change it, even while the status is refreshing, so guards don't run again for one.

Scope cached data to the session

An account switch is a sign-out followed by a sign-in, and it can happen in another tab. Data cached for the first account must never show for the second. Because sessionId is new on every sign-in, it's the key to cache private data under.

This cache keeps each session's orders under its sessionId, and drops them when the session ends:

src/orders-cache.ts
import {  } from "./api.js";
import {  } from "./auth.js";

const  = new <string, <unknown>>();

// After a sign-out or an account switch, drop the old session's entries.
..(({  }) => {
  for (const  of .()) if ( !== ) .();
});

async function (: number): <unknown> {
  const  = await (`auth/carts/user/${}`);
  if (!.) throw new (`Orders failed (${.})`);
  return .();
}

export async function (): <unknown> {
  const  = await .();
  if (!) return null;
  let  = .(.);
  if (!) {
     = (..);
    .(., );
    // A failed load isn't kept, so the next call tries again.
    .(() => .(.));
  }
  return ;
}

The same idea applies to other caches:

  • TanStack Query and similar libraries: put sessionId in the key of every private query, so each account gets its own entries.
  • Components: SessionOutlet and Expo's SessionGate remount the pages under them when the account changes. For a layout outside them, such as a sidebar, pass key={sessionId}, as the TanStack Router guide shows.
  • Slow work: auth.isCurrent(session) checks that a session is still the signed-in one before you use a result that took a while. See Sessions and credentials.

Check status, not user

user is set while the session is authenticated or refreshing, and also while it's locked. A locked session can show who is signed in, but it can't make requests. To know whether the user has access, check status.

isSignedIn(state) is that check. It's true while authenticated or refreshing, and it tells TypeScript that user is set:

src/greeting.ts
import {  } from "@monarcode/session-kit";

import {  } from "./auth.js";

export function (): string {
  const  = ..();
  return () ? `Hi, ${..}` : "Please sign in";
}

In a component, useAuth(isSignedIn) reads the same check.

Next steps

  • Errors: show state.error to the user, and know which failures appear there.
  • Sessions and credentials: ask who is signed in from a loader, and wait for the saved session to be read.
  • Core reference: the AuthState type and each status.

On this page