Skip to content

Library Overview

react-auth owns three concerns and nothing else: session state, the authenticated HTTP client, and the screens that produce a session. It talks to an auth server over HTTP — it never issues, validates or decodes tokens itself.


🧭 What lives where

Concern Module Notes
Session state contexts.tsx AuthProvider, useAuth, AuthServerConfig
Authenticated HTTP client axios.ts createApiClient, attachAuthInterceptors
Token persistence token.ts tokenStore (localStorage, key "token")
Login / register screen AuthPage.tsx AuthPage, AuthMode
Profile screens Profile*.tsx controlled presentational components
User model models.ts AuthUser

The package entry (index.ts) re-exports the public surface; nothing else in the app should import the internals directly.


🔄 Session lifecycle

  1. Bootstrap — AuthProvider seeds its token from tokenStore.get().
  2. Resolve the user — whenever the token changes, mePath is fetched and currentUser is set (or cleared).
  3. Login — login(username, password) posts to loginPath, stores access_token through tokenStore, and takes currentUser from the response user.
  4. Register — register(...) creates the account, then logs in.
  5. Request — every client built by createApiClient attaches Authorization: Bearer <token> from tokenStore.
  6. Expiry — a 401 clears the token and dispatches an auth:unauthorized window event; AuthProvider listens, clears the session, and invokes the optional onUnauthorized callback.
  7. Logout — best-effort call to logoutPath, then local state is always cleared.

One source of truth

tokenStore is the only place the token is written. Reading it from anywhere else will desynchronise the UI from the network layer.


🏗️ Endpoint contract

AuthServerConfig is the complete wiring surface; every path resolves relative to serverUrl:

Field Shape
loginPath POST { username, password } → { access_token, user }
registerPath POST { username, password } to create an account
logoutPath called on logout; failures are ignored
mePath returns the current AuthUser for a valid bearer token
introspectPath token introspection, available to callers that need it

AuthUser is intentionally permissive so it can be spread into application state without loss.