> ## Documentation Index
> Fetch the complete documentation index at: https://docs.theauth.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Persistent sessions in the client and React

> Send the remember choice, refresh and retry once on session_expired, keep tabs in step and use usePersistentSession in React.

`@glinr/theauth-client` and `@glinr/theauth-react` handle the client side of [persistent sessions](https://docs.theauth.dev/persistent-sessions.md). Against a server without the feature, nothing here sends a refresh request, because the server never answers `session_expired`.

## Session store

```typescript theme={"dark"}
import { createSessionStore } from '@glinr/theauth-client';

const store = createSessionStore({ emailPassword: true, storage: localStorage });

await store.signIn('ada@example.com', password, { remember: keepMeSignedIn });

// Refreshes once and retries once when the session has expired.
const response = await store.fetch('/api/projects');
```

| Member | What it does |
| - | - |
| `signIn(identifier, password, { remember })` | Sends `remember` with the sign-in body. Left out, the request is unchanged. `signUp` takes no choice. |
| `refresh()` | Reads `GET /auth/session`. On `session_expired` it refreshes and reads again. |
| `refreshSession()` | Calls `POST /auth/session/refresh` directly. |
| `fetch(input, init)` | `fetch` with one refresh and one retry on `session_expired`. |
| `isResolved()` | `false` until the session is known. Use it to hold back signed-in UI. |

After a refresh the new session lives in the cookie, so the store drops its stored bearer token. Reconnect streams of your own, such as WebSockets or event sources, once a refresh succeeds.

### RefreshSessionResult

```typescript theme={"dark"}
const result = await store.refreshSession();

if (result.success) {
  reconnect(); // result.rotated, result.sessionExpiresAt, result.rememberExpiresAt
} else if (result.sessionEnded) {
  showSignIn();
} else {
  retryLater(); // offline, 429 or 5xx
}
```

`sessionEnded` is `true` only when the server said the device is over (`remember_invalid`, `remember_expired`, `remember_reused` or `refresh_denied`). `status` is 0 when no answer arrived. `refreshSession()` never throws, and the store signs out only if the server also reports no session.

## How the retry behaves

`fetch` clones the request before the first attempt and retries at most once.

* A 401 without the code `session_expired` is returned untouched.
* A request with a `ReadableStream` body is not retried, because the body cannot be sent twice.
* If the refresh gets no answer, `fetch` throws a `TypeError`, like any network failure.
* If the refresh answers 429 or 5xx, you get that status in place of the 401, so an outage never looks like a sign-out.
* If the refresh says the device is over, you get the original 401.

## Without the store

```typescript theme={"dark"}
import { createSessionRefresher, SESSION_EXPIRED_CODE } from '@glinr/theauth-client';

const refresher = createSessionRefresher({ basePath: '/api/theauth' });
const response = await refresher.fetch('/api/projects');
```

`refresher.refresh()` returns the same `RefreshSessionResult`. `SESSION_EXPIRED_CODE` is the string to match if you write the retry yourself.

## Tabs

Only one refresh runs at a time in a tab, and `navigator.locks` serializes tabs. Where `navigator.locks` is missing, outside secure contexts, a best effort storage lease stands in. The server tolerates parallel refreshes inside the grace window either way.

Tabs tell each other about sign in, sign out and rotation through `BroadcastChannel`, or storage events without it. Messages carry no token and no user data.

| Option (`tabs`) | Default | Meaning |
| - | - | - |
| `sync` | `true` | `false` keeps tabs independent. |
| `refreshTimeoutMs` | 15000 | Aborts a refresh so it cannot hold the lock forever. |
| `locks` | `navigator.locks` | `null` forces the storage lease. |
| `createChannel`, `window` | browser globals | Replace the sync transport, mainly in tests. |

The storage lease and the storage event fallback need a `storage` option on the store.

## React

```tsx theme={"dark"}
import { TheAuthProvider, usePersistentSession } from '@glinr/theauth-react';

function App() {
  return (
    <TheAuthProvider managed={{ emailPassword: true }}>
      <SignIn />
    </TheAuthProvider>
  );
}

function SignIn() {
  const { status, user, signIn, signOut } = usePersistentSession();
  const [keep, setKeep] = useState(false);

  if (status === 'loading') return <p>Loading</p>;
  if (status === 'authenticated') return <button onClick={signOut}>Sign out {user?.email}</button>;

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        void signIn(String(data.get('email')), String(data.get('password')), { remember: keep });
      }}
    >
      <input name="email" type="email" />
      <input name="password" type="password" />
      <label>
        <input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} />
        Keep me signed in
      </label>
      <button type="submit">Sign in</button>
    </form>
  );
}
```

While `status` is `loading`, `user` and `session` are `null`, so a cached sign in does not flash before the server confirms it.

`usePersistentSession()` returns `status` (`loading`, `authenticated` or `unauthenticated`), `session`, `user`, `isAuthenticated`, `isLoading`, `signIn`, `isSigningIn`, `error`, `signOut`, `refreshSession` and `fetch`. Use that `fetch` for your own API calls so they refresh and retry like the hooks do.

### External auth

With external auth (`<TheAuthProvider external={...}>`), `signIn(email, password, { remember })` adds `remember=1` or `remember=0` to the login redirect. Set `refreshPath` to your backend's refresh route, `/auth/session/refresh` under the `apiUrl` mount of a theAuth or theauth-go server. When `mePath` then answers `session_expired`, the provider refreshes once and reads it again. A network error or 5xx keeps the user as it was.

`refreshSession` and `authFetch` on the context, and `refreshSession` and `fetch` from `usePersistentSession()`, refresh only when `refreshPath` is set. Without it `refreshSession` reports that it is not available and `fetch` is the plain one. Tabs refresh independently in this mode, which the server's grace window covers.

## Go server client

`createTheAuthGoClient` talks to a [theauth-go](https://docs.theauth.dev/sdk-go.md) server. It needs a server version that supports persistent sessions.

```typescript theme={"dark"}
import { createTheAuthGoClient } from '@glinr/theauth-client';

const client = createTheAuthGoClient({ baseUrl: 'https://auth.example.com' });

await client.login({ email, password, remember: true });
await client.signup({ email, password, remember: true });
await client.passkeys.login({ remember: true });
```

A cookie request that answers `session_expired` refreshes once and retries once. Requests that use `getToken` send a bearer token and never refresh.

| Option | Default | Meaning |
| - | - | - |
| `autoRefresh` | `true` | `false` turns the refresh and retry off. |
| `tabs` | see [tabs](#tabs) | How tabs share one refresh. |
| `storage` | `localStorage` in a browser | Holds the refresh lease where `navigator.locks` is missing. |

The client has no method that only refreshes. To do that by hand, create a refresher for the Go routes:

```typescript theme={"dark"}
import { createSessionRefresher } from '@glinr/theauth-client';

const refresher = createSessionRefresher({ basePath: '/auth', refreshPath: '/session/refresh' });
const result = await refresher.refresh();
```

The TanStack Query hooks in `@glinr/theauth-react/query` use the same client, and `useLogin()` and `usePasskeys().login` take `remember`:

```typescript theme={"dark"}
const login = useLogin();
login.mutate({ email, password, remember: true });
```

## Server rendering

Resolve the session on the server with [`refreshFromRequest`](https://docs.theauth.dev/persistent-sessions#server-rendered-pages), forward its `Set-Cookie` headers, and pass the result as `initialSession` so the client does not start in `loading`. See [React](https://docs.theauth.dev/react.md).

## Native and other non-browser clients

Keep the remember token in the platform's secure storage and call [`persistentSessions.refresh`](https://docs.theauth.dev/persistent-sessions-api#refresh) from your own endpoint, or send both cookies to the refresh route with an `Origin` header that matches `baseUrl` or a trusted origin. Run one refresh at a time and save the new tokens before using them.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.