# Introduction (https://session-kit.pages.dev/docs)
Your backend already signs users in: it checks a password and answers with
an access token and a refresh token. Session kit takes those tokens and keeps
the app signed in from there. It saves the session, restores it on reload,
refreshes tokens before they expire, keeps every tab in step, and guards your
routes. It works with plain React, TanStack Router and Start, React Router,
Next.js, Expo Router on iOS and Android, and Effect.
This page shows what Session kit takes care of, what it leaves to you, and
the few terms the rest of the docs use. To start using it, see
[Installation](https://session-kit.pages.dev/docs/installation).
## Why Session kit
Signing in is the easy part. Then the user reloads the page. The access token
expires halfway through a form. They open a second tab, sign out of one, and
switch accounts in the other. The backend goes down for a minute, just as a
refresh was due.
Every app with its own backend has to get these moments right. The code for
them usually ends up spread across an auth context, a fetch wrapper and the
route guards, and one or two cases stay missing until a user finds them.
Session kit is that code, written once and tested with each router and
framework it supports.
### What it does
Here's what Session kit does in each of those moments:
| When… | Session kit… |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| The page reloads | Restores the saved session and checks the user against your schema again. With synchronous storage, such as `localStorage`, and a synchronous schema, that happens before the first paint. |
| The access token is about to expire | Refreshes it early, in the background, so requests don't wait. |
| A request gets a 401 anyway | Refreshes once, however many requests got the 401, then sends the `GET` and `HEAD` requests again. |
| Two tabs need a refresh at the same moment | Lets one tab use the refresh token while the other waits and reuses the tokens it saved, in browsers with Web Locks. |
| The user signs out or switches account in one tab | Follows in every other tab, and remounts the pages under `SessionOutlet` (or `SessionGate` on Expo), so nothing from the previous account stays on screen. |
| The backend rejects the refresh token | Signs out in every tab and clears the saved session. |
| The backend is down when a refresh is due | Keeps the session and reports the error. While the access token still works, the user stays signed in. After it expires, the session waits for a retry. An outage is never a sign-out. |
| A signed-out user opens a private page | Sends them to your sign-in page, and back to where they were going after they sign in. |
| The page renders on the server | Reads the session from an encrypted cookie, so the first response is already signed in. |
### What it doesn't do
Session kit never signs users in. It has no sign-in form, no OAuth flow and
no user database: it starts where your backend's sign-in response ends. If
you need those too, use an auth service or framework such as Auth.js, Better
Auth or Clerk, which manage their own sessions.
## How it works
Session kit sits between your backend and your components. Tokens move
between Session kit and your backend, and only the session's state reaches
your components:
```text
Your backend Session kit Your components
┌───────────────┐ ┌───────────────────┐ ┌──────────────────┐
│ POST /login │ ───▶ │ signIn() │ ───▶ │ useAuth() │
│ POST /refresh │ ◀──▶ │ refresh, on time │ │ route guards │
│ GET /orders │ ◀─── │ authFetch() │ ◀─── │ loaders, queries │
└───────────────┘ └───────────────────┘ └──────────────────┘
issues tokens keeps the session state, never tokens
```
Your backend issues the tokens. Session kit saves them, refreshes them on
time, and adds the access token to your API requests. Your components and
route guards read who is signed in, and never handle a token.
Five terms come up on every page:
- **Tokens** are what your backend issues. The access token goes with each
request and lasts a short time. The refresh token, if there is one, is
exchanged for a new access token when the old one expires.
- **The client**, from `createAuth`, holds the tokens and does the work:
saving, restoring, refreshing and following other tabs. An app usually has
one, named `auth` in these docs.
- **A session** is who is signed in: `{ sessionId, user }`. It holds no
tokens, so it's safe to render and to pass around.
- **State** is what components read: `status`, `user`, `sessionId` and
`error`. It updates as the session changes.
- **Credentials** are the session ID, the access token and when it expires.
`createAuthFetch` reads them to add the token to your requests, and your own
request code can too.
`status` says where the session stands, and checking it tells TypeScript
whether `user` is set:
| `status` | Meaning | `user` |
| ----------------- | -------------------------------------------------------------------------------------------------------- | ------ |
| `initializing` | The saved session hasn't been read yet. | `null` |
| `authenticated` | Signed in, with an access token that hasn't expired or been rejected. | Set |
| `refreshing` | Signed in, and replacing an access token that expired or was rejected. | Set |
| `locked` | Signed in with `locking`, and the tokens wait for `unlock()`. | Set |
| `unauthenticated` | Signed out. | `null` |
| `unavailable` | The access token couldn't be refreshed, or the saved session couldn't be read. `error` usually says why. | `null` |
Where the session is kept depends on where your app renders:
| Where it's kept | In the browser or on the device | On the server |
| ----------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| For | Single-page apps and Expo apps | TanStack Start, Next.js, React Router with server rendering |
| Client | `createAuth` | `createServerAuth`, with `createMirrorAuth` in the browser |
| Saved in | `localStorage`, `sessionStorage`, the iOS keychain, or Android's encrypted storage | An encrypted, `httpOnly` cookie |
| The refresh token | Stays in that storage | Sealed in the cookie, where page scripts can't read it |
The hooks, the route guards and tab sync work the same in both.
[Storage](https://session-kit.pages.dev/docs/configuration/storage) says more about each kind of storage,
and [Server rendering](https://session-kit.pages.dev/docs/server-rendering) about the cookie.
## Next steps
- [Installation](https://session-kit.pages.dev/docs/installation): install the package and find the guide
for your setup.
- [Getting started](https://session-kit.pages.dev/docs/getting-started): build a small app that signs in,
stays signed in, and calls an API.
- [Server rendering](https://session-kit.pages.dev/docs/server-rendering): keep the session on the server
with TanStack Start, Next.js or React Router.
# Installation (https://session-kit.pages.dev/docs/installation)
Your app needs Session kit, a schema library to describe your users, and the
packages your setup already uses, such as React and your router. Install the
first two here, then follow the guide for your setup.
To install Session kit, run the following command:
```npm
npm install @monarcode/session-kit
```
Release candidates are published to the `latest` distribution tag. The API
is frozen for 0.1: later 0.1 releases only add to it. Pin an exact version,
and read the
[release notes](https://github.com/monarcode/session-kit/blob/main/CHANGELOG.md)
before upgrading.
Session kit checks each user against a schema from any
[Standard Schema](https://standardschema.dev) library. The examples use Zod.
To install it, run the following command:
```npm
npm install zod
```
Then install React, and the router or framework your setup uses. Each is an
optional peer dependency, so install only the ones your setup imports.
Session kit needs TypeScript 5.4 or newer, and Effect asks for 5.9 or newer.
[Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) lists the runtimes and the
peer dependency versions it supports.
## Pick your setup
Find your setup in the following table. Each row names the entry point for
your router or framework, and the guide to follow. All but the first also
have a runnable app in
[`examples/`](https://github.com/monarcode/session-kit/tree/main/examples)
that signs in against DummyJSON's public test API:
| Setup | Import | Guide | Example app |
| ------------------------------------------ | -------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| React without a router | `@monarcode/session-kit/react` | [Getting started](https://session-kit.pages.dev/docs/getting-started) | None |
| TanStack Router | `@monarcode/session-kit/tanstack-router` | [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router) | [`tanstack-router`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-router) |
| TanStack Start, SPA mode | `@monarcode/session-kit/tanstack-router` | [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router#tanstack-start-in-spa-mode) | [`tanstack-start-spa`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa), [`tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa-effetch) |
| TanStack Start with server rendering | `@monarcode/session-kit/tanstack-start` | [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start) | [`tanstack-start-ssr`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-ssr) |
| React Router, declarative mode | `@monarcode/session-kit/react-router` | [React Router](https://session-kit.pages.dev/docs/setups/react-router#declarative-mode) | [`react-router-declarative`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-declarative) |
| React Router, data mode | `@monarcode/session-kit/react-router` | [React Router](https://session-kit.pages.dev/docs/setups/react-router#data-mode) | [`react-router-data`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-data) |
| React Router, framework mode, `ssr: false` | `@monarcode/session-kit/react-router` | [React Router](https://session-kit.pages.dev/docs/setups/react-router#framework-mode-with-ssr-false) | [`react-router-framework-spa`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-spa) |
| React Router, framework mode with SSR | `@monarcode/session-kit/react-router/server` | [React Router with SSR](https://session-kit.pages.dev/docs/setups/react-router-ssr) | [`react-router-framework-ssr`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-ssr) |
| Next.js 16, App Router | `@monarcode/session-kit/next` | [Next.js](https://session-kit.pages.dev/docs/setups/next) | [`next-app`](https://github.com/monarcode/session-kit/tree/main/examples/next-app) |
| Expo Router on iOS and Android, SDK 53+ | `@monarcode/session-kit/expo` | [Expo Router](https://session-kit.pages.dev/docs/setups/expo) | [`expo-router`](https://github.com/monarcode/session-kit/tree/main/examples/expo-router) |
Every setup also imports its client from `@monarcode/session-kit`:
`createAuth`, or with server rendering, `createMirrorAuth`. Server-rendered
setups import more on the server, and each guide shows what.
[Entry points](https://session-kit.pages.dev/docs/reference) lists every import path.
Two guides apply to more than one setup:
- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions) covers what the
three server-rendered setups share.
- [Effect and effetch](https://session-kit.pages.dev/docs/effect) works with any setup.
## Docs for coding assistants
These docs are also available as plain Markdown, for AI coding assistants.
Point yours at [`/llms.txt`](https://session-kit.pages.dev/llms.txt), which links every page in reading
order, or at [`/llms-full.txt`](https://session-kit.pages.dev/llms-full.txt), which holds them all in one
file. For one page alone, add `.md` to its URL.
## Next steps
- [Getting started](https://session-kit.pages.dev/docs/getting-started): start here for a setup that
keeps the session in the browser. The web router guides build on its app.
- [Expo Router](https://session-kit.pages.dev/docs/setups/expo): start here for an iOS or Android app. The
guide starts from scratch.
- [Server rendering](https://session-kit.pages.dev/docs/server-rendering): start here for TanStack Start,
Next.js, or React Router with server rendering.
# Getting started (https://session-kit.pages.dev/docs/getting-started)
Your backend signs users in and answers with an access token and a refresh
token. In this tutorial, you build a small React app around those tokens. It
signs in, stays signed in across reloads and tabs, calls an API with the
access token, and signs out.
The code signs in against
[DummyJSON's auth API](https://dummyjson.com/docs/auth), a public test
backend, so it runs as written. The web router guides build on this app. If
your app renders on the server, it creates its client differently: start
from [Server rendering](https://session-kit.pages.dev/docs/server-rendering) instead.
## Before you begin
- A React app. A router is optional: step 6 links to the guide for yours.
- Session kit and Zod, installed as [Installation](https://session-kit.pages.dev/docs/installation)
shows.
## 1. Talk to your backend
Session kit never calls your backend for you, so start with the two requests
you'd write anyway. One signs in, and the other exchanges a refresh
token for new tokens. Nothing in this file imports Session kit:
```ts title="src/backend.ts"
import { z } from "zod";
export const API = "https://dummyjson.com";
export const userSchema = z.object({
id: z.number(),
username: z.string(),
email: z.string(),
firstName: z.string(),
});
const tokensSchema = z.object({
accessToken: z.string(),
refreshToken: z.string(),
});
const post = (path: string, body: unknown, init?: RequestInit) =>
fetch(API + path, {
...init,
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
/** Checks the password, and resolves the tokens and the user. */
export async function login(username: string, password: string) {
const response = await post("/auth/login", { username, password });
if (!response.ok) throw new Error(`Sign-in failed (${response.status})`);
// DummyJSON returns the user's fields beside the tokens.
const body: unknown = await response.json();
return { ...tokensSchema.parse(body), user: userSchema.parse(body) };
}
/**
* Exchanges a refresh token for new tokens. Resolves `null` when the backend
* rejects the token, and throws for any other failure.
*/
export async function refresh(refreshToken: string, signal: AbortSignal) {
const response = await post("/auth/refresh", { refreshToken }, { signal });
// DummyJSON answers 403 for an invalid token and 401 for a missing one.
if (response.status === 401 || response.status === 403) return null;
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return tokensSchema.parse(await response.json());
}
```
The schemas do two jobs. They check what the backend sent, and they give the
rest of the app its types.
DummyJSON's docs add `credentials: "include"` to these requests, to send its
cookies. This file leaves it out: Session kit keeps the tokens in storage,
not in cookies, and in step 5 `authFetch` adds the access token to your API
calls.
## 2. Create the client
The client is the one object that holds the session. Tell it what a user is,
where to save the session, and how to refresh:
```ts title="src/auth.ts"
import { createAuth, webStorage } from "@monarcode/session-kit";
import { login, refresh, userSchema } from "./backend.js";
export const auth = createAuth({
// Keeps this app's saved session apart from any other on the same origin.
name: "my-app",
// Every user is checked against this schema, and typed by it.
user: userSchema,
// Where the session is saved: `localStorage`.
storage: webStorage(),
// How expired access is replaced.
refresh: ({ refreshToken, signal }) => refresh(refreshToken, signal),
});
/** Signs in with the backend, then hands the result to Session kit. */
export async function signInWithPassword(username: string, password: string) {
const tokens = await login(username, password);
await auth.signIn(tokens);
}
export type AppAuth = typeof auth;
```
Create the client one time, at module level, as this file does. If an app has
more than one client, give each its own `name`.
`refresh` tells two failures apart, so an outage doesn't sign anyone out:
- `null` means the backend rejected the refresh token, so the user is signed
out.
- A throw means something else failed, such as the network. The session is
kept, and the error reported.
[Refresh](https://session-kit.pages.dev/docs/configuration/refresh) has the details, and
[Storage](https://session-kit.pages.dev/docs/configuration/storage) lists the other places a session can
be saved.
DummyJSON's tokens are JWTs, so their expiry comes from the `exp` and `iat`
claims. [Expiry](https://session-kit.pages.dev/docs/configuration/expiry) covers backends that say it
another way.
## 3. Add a sign-in form
The form calls `signInWithPassword` from `src/auth.ts`, and has no Session
kit code of its own:
```tsx title="src/sign-in.tsx"
import { useState, type FormEvent } from "react";
import { signInWithPassword } from "./auth.js";
export function SignIn() {
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
async function submit(event: FormEvent) {
event.preventDefault();
const form = new FormData(event.currentTarget);
setError("");
setPending(true);
try {
await signInWithPassword(
String(form.get("username")),
String(form.get("password")),
);
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
} finally {
setPending(false);
}
}
return (
);
}
```
The form doesn't navigate after it signs in. Signing in changes the client's
state, and the next step renders from that state. With a router, the sign-in
page's guard runs again and sends the user on.
## 4. Read the session in React
The hooks come from `@monarcode/session-kit/react`. Register your client's
type one time, in the file that renders `AuthProvider`, and the hooks carry
your user's type.
Then render by `status`. Each case is one of the states in
[How it works](https://session-kit.pages.dev/docs#how-it-works). By the last case, TypeScript has narrowed
`user`, so it's never `null` there:
```tsx title="src/app.tsx"
import {
AuthProvider,
useAuth,
useAuthClient,
} from "@monarcode/session-kit/react";
import { auth } from "./auth.js";
import { SignIn } from "./sign-in.js";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
export function App() {
return (
);
}
function Screen() {
const { status, user } = useAuth();
const client = useAuthClient();
switch (status) {
case "initializing":
return
Restoring your session…
;
case "unauthenticated":
return ;
case "unavailable":
// Access couldn't be restored or refreshed: offer another try.
return (
);
default:
// Signed in: "authenticated", or "refreshing" with the user on screen.
return (
Welcome, {user.firstName}
);
}
}
/** The latest failure, such as a refresh the backend couldn't answer. */
function AuthErrorMessage() {
const error = useAuth((state) => state.error);
return error ?
{error.message}
: null;
}
```
Each part of this file has a job:
- `AuthProvider` mounts the client. It restores the saved session, starts the
refresh timer, and follows other tabs.
- `useAuth()` returns the whole state. `useAuth(selector)` returns a part of
it, and re-renders only when that part changes, as `AuthErrorMessage` does.
- `useAuthClient()` returns the client, for actions such as `retry` and
`signOut`.
- `AuthErrorMessage` shows `state.error`, where failures appear.
The buttons ignore a rejection because `AuthErrorMessage` already shows the
failure. `retry` rejects when it fails, and the failure also appears in
`state.error`. `signOut` signs the user out even when your backend can't
revoke the tokens: that failure only appears in `state.error`. `signOut`
rejects only when it can't clear the saved session.
[Errors](https://session-kit.pages.dev/docs/configuration/errors) covers where each failure appears.
Two more helpers are useful as the app grows:
- `isSignedIn(state)`, from `@monarcode/session-kit`, is `true` while the
status is `authenticated` or `refreshing`. Pass it to `useAuth` to read only
that: `useAuth(isSignedIn)`.
- With more than one client in an app, create hooks for each with
`createAuthHooks()` instead of registering one.
With [`locking`](https://session-kit.pages.dev/docs/client/locking), give `locked` a case of its own. It
has a user too, but no usable access.
That's a working app. To check it:
1. Sign in. The welcome message appears.
2. Reload the page. You're still signed in.
3. Open the app in a second tab, and sign out in one of them. Both tabs show
the sign-in form.
## 5. Call your API
Your API wants the access token on each request. `createAuthFetch` makes a
`fetch` that adds it, and sends it to your API's origin and to no other:
```ts title="src/api.ts"
import { createAuthFetch } from "@monarcode/session-kit/http";
import { auth } from "./auth.js";
import { API, userSchema } from "./backend.js";
export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
/** The signed-in user, fresh from the backend. */
export async function fetchProfile() {
const response = await authFetch("auth/me");
if (!response.ok) throw new Error(`Profile failed (${response.status})`);
return userSchema.parse(await response.json());
}
```
When a request gets a 401, `authFetch` refreshes, then sends a `GET` or
`HEAD` again. It never sends other methods twice.
[Authenticated requests](https://session-kit.pages.dev/docs/client/requests) covers the rest of its
behavior and its options.
To see it work, add a button that loads the profile:
```tsx title="src/profile.tsx"
import { useState } from "react";
import { fetchProfile } from "./api.js";
export function ProfileButton() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
async function load() {
setError("");
try {
setEmail((await fetchProfile()).email);
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not load");
}
}
return (
{email &&
{email}
}
{error &&
{error}
}
);
}
```
Render `` in `Screen`'s signed-in case, under the welcome
message. Sign in, then select **Load my profile**. Emily's email address
appears, from a request that carried the access token.
ky, axios and openapi-fetch can each send their requests through
`authFetch`. [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients) shows
how for each one.
## 6. Protect your routes
The client is the same everywhere. What changes is how each router keeps
signed-out users away from private pages. To continue, follow the guide for
your router:
- [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router), and
[TanStack Start in SPA mode](https://session-kit.pages.dev/docs/setups/tanstack-router#tanstack-start-in-spa-mode).
- [React Router](https://session-kit.pages.dev/docs/setups/react-router), in declarative, data, or
framework mode with `ssr: false`.
- [Expo Router](https://session-kit.pages.dev/docs/setups/expo), for iOS and Android. Its guide starts from
scratch.
- Without a router, you're done. Render by `status`, as `Screen` does.
With Effect, the same client becomes a service: see
[Effect and effetch](https://session-kit.pages.dev/docs/effect).
## Next steps
- [Using the client](https://session-kit.pages.dev/docs/client): what else the client does, such as
updating the user and locking.
- [Configuring the client](https://session-kit.pages.dev/docs/configuration): the rest of its options.
- [Security](https://session-kit.pages.dev/docs/security): what Session kit protects, and what stays your
backend's job.
# TanStack Router (https://session-kit.pages.dev/docs/setups/tanstack-router)
Your app uses TanStack Router, and some of its routes are for signed-in users
only. In this guide, you add Session kit to the app from Getting started: a
sign-in route, private routes that send signed-out users to it, and hooks that
read the client from the Router. The guards run in `beforeLoad`, so a private
route never loads or renders for someone who isn't signed in.
The hooks come from `@monarcode/session-kit/tanstack-router`. They're typed by
the Router you register, and they need no `AuthProvider`. A complete app is in
[`examples/tanstack-router`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-router).
For TanStack Start in SPA mode, follow this guide with
[the changes for Start](#tanstack-start-in-spa-mode). For TanStack Start with
server rendering, follow [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start)
instead.
## Before you begin
- A Vite app with React, using `@vitejs/plugin-react`. Installation adds a
plugin to its `vite.config.ts`.
- The app from [Getting started](https://session-kit.pages.dev/docs/getting-started), through step 3. This
guide uses its client in `src/auth.ts` and its form in `src/sign-in.tsx`.
## Installation
Install Session kit, the Router and Zod, and the Router's Vite plugin as a
dev dependency:
```npm
npm install @monarcode/session-kit @tanstack/react-router zod
npm install -D @tanstack/router-plugin
```
This guide uses file-based routing: the plugin generates
`src/routeTree.gen.ts` from the files under `src/routes`. Add it to
`vite.config.ts`, before the React plugin, or the build fails:
```ts title="vite.config.ts"
import { tanstackRouter } from "@tanstack/router-plugin/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
tanstackRouter({ target: "react", autoCodeSplitting: true }),
react(),
],
});
```
## 1. Type the root route
The root route declares that Router context holds the client, so every guard
gets a typed `context.auth`. It stays mounted while pages come and go, which
makes it the place to show auth errors:
```tsx title="src/routes/__root.tsx"
import { useAuth } from "@monarcode/session-kit/tanstack-router";
import { createRootRouteWithContext, Outlet } from "@tanstack/react-router";
import type { AppAuth } from "../auth.js";
export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({
component: Root,
});
function Root() {
// Shows failures that outlive the page that caused them, such as a sign-out
// that couldn't clear storage.
const error = useAuth((state) => state.error);
return (
<>
{error &&
{error.message}
}
>
);
}
```
`useAuth` reads the client's state from Router context. It's typed with your
user after you register the Router in step 4, and it's typed `never` until
then.
## 2. Add the sign-in route
The sign-in route renders the form from Getting started. Its guard sends a
user who's already signed in on to the page they asked for:
```tsx title="src/routes/login.tsx"
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router";
import { createFileRoute } from "@tanstack/react-router";
import { SignIn } from "../sign-in.js";
export const Route = createFileRoute("/login")({
validateSearch: (search: Record) => ({
redirectTo: safeReturnTo(search.redirectTo),
}),
beforeLoad: ({ context, search }) =>
redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
component: SignIn,
});
```
The form doesn't navigate after it signs in, because this guard does it.
When the session changes, the Router runs the guard again, and it sends the
signed-in user on. Step 4 sets that up.
`redirectTo` is the search param that the private routes' guard sets.
`safeReturnTo` turns it into a path that's safe to send the user to. Anything
that leads out of your app, or back to the sign-in page, becomes `/`, so a
stale `redirectTo` can't loop. `redirectIfSignedIn` checks it the same way.
The [`safeReturnTo` reference](https://session-kit.pages.dev/docs/reference/core#safereturnto) lists every
rule.
## 3. Guard private routes
Guard private routes with a pathless layout route. Its child routes are
guarded without `_authenticated` appearing in their URLs:
```tsx title="src/routes/_authenticated.tsx"
import {
requireSession,
SessionOutlet,
useAuthClient,
} from "@monarcode/session-kit/tanstack-router";
import {
createFileRoute,
type ErrorComponentProps,
} from "@tanstack/react-router";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
requireSession(context.auth, { location }),
errorComponent: SessionError,
component: () => Checking session…
} />,
});
/** Shown after a failed refresh; a repeated failure shows here again. */
function SessionError({ error }: ErrorComponentProps) {
const auth = useAuthClient();
return (
{error instanceof Error ? error.message : "Something went wrong"}
);
}
```
`requireSession` lets a signed-in user through, and puts `{ session }` in
route context. It sends a signed-out user to `/login`, or the `loginPath` you
pass, with `redirectTo` set to where they were going. A signed-out user who
opens `/orders?tab=2` lands on `/login?redirectTo=%2Forders%3Ftab%3D2`, and
returns to `/orders?tab=2` after signing in.
A session that can't be used isn't a sign-out. When the access token has
expired and a refresh fails, such as while your backend is down, the status
is `unavailable`. The saved session is kept, and `auth.retry()` can restore
access. So `requireSession` doesn't redirect: it throws the error to the
route's error component, which offers a retry. If the retry fails too, the
new error shows there again.
`SessionOutlet` renders the child routes while the session the guard accepted
is still the signed-in one. After a sign-out or an account switch, it shows
`pending` until the guard runs again. It also remounts the child routes for
the new account, so nothing from the previous one stays on screen. Profile
updates and token refreshes keep them mounted.
Child routes read the session from route context, where `user` is typed and
never `null`:
```tsx title="src/routes/_authenticated/index.tsx"
import { useAuthClient } from "@monarcode/session-kit/tanstack-router";
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/_authenticated/")({
component: Home,
});
function Home() {
const { session } = Route.useRouteContext();
const auth = useAuthClient();
return (
Welcome, {session.user.firstName}
);
}
```
A sign-out that fails shows in the root route's alert from step 1, so the
button can ignore the rejection.
## 4. Create and connect the Router
Create the Router with the client in its context, then connect the two:
```tsx title="src/router.tsx"
import { connectAuth } from "@monarcode/session-kit/tanstack-router";
import { createRouter } from "@tanstack/react-router";
import { auth } from "./auth.js";
import { routeTree } from "./routeTree.gen.js";
export const router = createRouter({
routeTree,
context: { auth },
defaultPendingComponent: () =>
Loading…
,
});
// Restores the session, runs expiry timers and tab sync, and re-runs guards
// when auth changes. Call it once, beside the Router.
export const disconnectAuth = connectAuth(router);
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
```
`connectAuth` does for the Router what `AuthProvider` does for a plain React
app: it restores the saved session, starts the refresh timer, and follows
other tabs. When the session changes, it does two more things:
- It clears the Router's cached and preloaded route data, so one account's
data never shows for the next.
- It runs the guards again, so a sign-in on the sign-in page sends the user
on, and a sign-out in another tab redirects this one.
Registering the Router types `useAuth` and `useAuthClient` with your client.
## 5. Render the app
Render the Router in `src/main.tsx`:
```tsx title="src/main.tsx" app="vite"
import { StrictMode } from "react";
import { RouterProvider } from "@tanstack/react-router";
import { createRoot } from "react-dom/client";
import { router } from "./router.js";
createRoot(document.getElementById("root")!).render(
,
);
```
To check the app:
1. Signed out, open `/`. The Router sends you to `/login?redirectTo=%2F`.
2. Sign in. You're back on `/`, with the welcome message.
3. Reload the page. You're still signed in.
4. Open a second tab and sign out there. The first tab goes to `/login`.
## Layouts around guarded pages
A guarded route often has UI of its own around its pages, such as a sidebar
and a top bar. Render it in the route's component, with `SessionOutlet` where
the pages go:
```tsx title="src/dashboard.tsx"
import { useState } from "react";
import { SessionOutlet, useAuth } from "@monarcode/session-kit/tanstack-router";
/** The guarded route's component: `component: Dashboard`. */
export function Dashboard() {
// From state, not route context: this stays mounted through a sign-out.
const user = useAuth((state) => state.user);
const sessionId = useAuth((state) => state.sessionId);
return (
{user ? `Signed in as ${user.firstName}` : null}
{/* Keyed by session: one account's choices never show for the next. */}
Checking session…} />
);
}
function Sidebar() {
const [pinned, setPinned] = useState(false);
return (
);
}
```
In the guarded route's component, `SessionOutlet` reads the session that
route's guard accepted. Three things follow from where it sits:
- **It protects only what it renders.** After a sign-out or an account switch,
the pages are swapped for `pending` and remounted, but the layout around
them stays mounted until the guard redirects.
- **Read the user from state there.** In the layout, use
`useAuth((state) => state.user)` and handle `null`. Route context's
`session.user` is the session the guard accepted, which for that moment is
the previous one. Inside the pages, route context's session is always the
signed-in one.
- **Key what belongs to an account.** Layout UI that holds state for one
account, such as a draft or an open panel, takes the session as its `key`,
so the next account starts fresh.
## TanStack Start in SPA mode
TanStack Start's SPA mode is TanStack Router with an HTML shell that the build
prerenders. Start renders the whole document from the root route, and the
browser takes over from there. Steps 2 and 3 apply as they are. In place of
Installation and steps 1, 4 and 5, follow these steps. Complete apps are in
[`examples/tanstack-start-spa`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa)
and, written with Effect and effetch, in
[`examples/tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa-effetch).
### 1. Install Start
Install Session kit, the Router and Zod, and Start in place of the Router's
Vite plugin:
```npm
npm install @monarcode/session-kit @tanstack/react-router zod
npm install @tanstack/react-start
```
### 2. Use Start's Vite plugin
In `vite.config.ts`, use Start's plugin with SPA mode on, in place of the
Router plugin:
```ts title="vite.config.ts" app="start"
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [tanstackStart({ spa: { enabled: true } }), react()],
});
```
### 3. Render the document from the root route
Give the root route a `shellComponent` that renders the document, with
`` and ``. Start renders the app from it, so delete
`src/main.tsx` and `index.html`:
```tsx title="src/routes/__root.tsx" app="start"
import type { ReactNode } from "react";
import { useAuth } from "@monarcode/session-kit/tanstack-router";
import {
createRootRouteWithContext,
HeadContent,
Outlet,
Scripts,
} from "@tanstack/react-router";
import type { AppAuth } from "../auth.js";
export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({
shellComponent: Document,
component: Root,
});
function Document({ children }: { children: ReactNode }) {
return (
{children}
);
}
function Root() {
// Shows failures that outlive the page that caused them.
const error = useAuth((state) => state.error);
return (
<>
{error &&
{error.message}
}
>
);
}
```
### 4. Create the Router in `getRouter`
Start creates the Router itself, by calling `getRouter()` from
`src/router.tsx`. Create the Router and connect auth there:
```tsx title="src/router.tsx" app="start"
import { connectAuth } from "@monarcode/session-kit/tanstack-router";
import { createRouter } from "@tanstack/react-router";
import { auth } from "./auth.js";
import { routeTree } from "./routeTree.gen.js";
export function getRouter() {
const router = createRouter({
routeTree,
context: { auth },
defaultPendingComponent: () =>
Loading…
,
});
// Does nothing while the build prerenders the shell.
connectAuth(router);
return router;
}
declare module "@tanstack/react-router" {
interface Register {
router: ReturnType;
}
}
```
`connectAuth` does nothing while the Router renders on a server, so the shell
that the build prerenders shows your pending component. `getRouter()` doesn't
keep the function that `connectAuth` returns, because the Router lasts as
long as the page.
### 5. Turn off server rendering for routes
Start's own server still answers requests in SPA mode, and it has no saved
session to check. Turn server rendering off for routes in `src/start.ts`, so
the guards run in the browser:
```ts title="src/start.ts" app="start"
import { createStart } from "@tanstack/react-start";
// The session is in browser storage, so guards must run in the browser.
export const startInstance = createStart(() => ({
defaultSsr: false,
}));
```
## Things to know
- **Another sign-in page.** If sign-in isn't at `/login`, pass the same
`loginPath` to `requireSession`, `redirectIfSignedIn` and `safeReturnTo`.
- **The first render.** The guards wait for the saved session, so a signed-in
user never sees the sign-in page. With synchronous storage and a
synchronous schema, the session is restored
[before the first paint](https://session-kit.pages.dev/docs#what-it-does).
- **Stopping.** Call `disconnectAuth` on app teardown or hot-module disposal.
It stops background work without signing out.
- **Locked sessions.** [Locking](https://session-kit.pages.dev/docs/client/locking) is for native apps, so
the guards treat a locked session as signed out.
- **Cached data.** `connectAuth` clears the Router's own cache. Scope your
other private caches, such as TanStack Query results, to `state.sessionId`,
which is new on every sign-in. See [State](https://session-kit.pages.dev/docs/client/state).
## Next steps
- [Call your API](https://session-kit.pages.dev/docs/getting-started#5-call-your-api) with `authFetch`, as
in Getting started, or with
[ky, axios or openapi-fetch](https://session-kit.pages.dev/docs/client/other-http-clients). It works
unchanged with the Router.
- [Using the client](https://session-kit.pages.dev/docs/client): update the user, sign out, and use the
client's other methods.
- [Effect and effetch](https://session-kit.pages.dev/docs/effect): use the same client as an Effect
service.
- [TanStack Router reference](https://session-kit.pages.dev/docs/reference/tanstack-router): every option
of the guards, `SessionOutlet` and `connectAuth`.
# TanStack Start (https://session-kit.pages.dev/docs/setups/tanstack-start)
Your TanStack Start app renders pages on the server, and you want the first
response to show the signed-in page, with no "Checking session…" state and no
flash of signed-out content. To do that, the server has to hold the session.
In this guide, you keep it in an encrypted cookie: the server signs in,
refreshes the tokens before rendering, and sends the signed-in page first.
The browser gets a small client that mirrors the session the server rendered,
and the [TanStack Router hooks and guards](https://session-kit.pages.dev/docs/setups/tanstack-router) work
with it. [Server rendering](https://session-kit.pages.dev/docs/server-rendering) explains how the pieces
fit. A complete app is in
[`examples/tanstack-start-ssr`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-ssr).
If your Start app runs in SPA mode, where the browser keeps the session,
follow
[TanStack Start in SPA mode](https://session-kit.pages.dev/docs/setups/tanstack-router#tanstack-start-in-spa-mode)
instead.
## Before you begin
- Node.js 22.12 or newer, which TanStack Start needs. See
[Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) for the other versions.
- A secret of 32 or more random characters to seal the cookie, such as the
output of `openssl rand -base64 32`, set as `SESSION_SECRET` on the server.
`vite build` doesn't need it.
[The secret](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-secret) says how to
keep and rotate it.
- The code signs in with [DummyJSON](https://dummyjson.com/docs/auth)'s test
backend, as [Getting started](https://session-kit.pages.dev/docs/getting-started) does. Replace its URLs
with your backend's.
## Installation
To install the packages, run the following command:
```npm
npm install @monarcode/session-kit @tanstack/react-start @tanstack/react-router zod
```
## 1. Create the server engine
The server engine keeps the session in a cookie sealed with your secret, and
refreshes the tokens with your backend. `createServerAuth` from
`@monarcode/session-kit/server` makes it, and `startAuth` gives you the session
of the request Start is handling. Create both in a server-only module, so Start
refuses to bundle it for the browser:
```ts title="src/auth/server.ts"
import "@tanstack/react-start/server-only";
import { createServerAuth } from "@monarcode/session-kit/server";
import { startAuth } from "@monarcode/session-kit/tanstack-start/server";
import { z } from "zod";
export const API = "https://dummyjson.com";
const userSchema = z.object({ id: z.number(), firstName: z.string() });
const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() });
export const serverAuth = createServerAuth({
name: "app",
user: userSchema,
secret: process.env.SESSION_SECRET!,
refresh: async ({ refreshToken, signal }) => {
const response = await fetch(`${API}/auth/refresh`, {
method: "POST",
signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
// DummyJSON rejected the refresh token: sign out.
if (response.status === 401 || response.status === 403) return null;
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return tokens.parse(await response.json());
},
});
/** The session of the request Start is handling, found on each call. */
export const session = startAuth(serverAuth);
/** Signs in with your backend, from the server. */
export async function login(username: string, password: string) {
const response = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
// The backend says why, such as wrong credentials, in `message`.
const failure = z.object({ message: z.string() }).safeParse(body);
throw new Error(
failure.success
? failure.data.message
: `Sign-in failed (${response.status})`,
);
}
return { ...tokens.parse(body), user: userSchema.parse(body) };
}
```
`session` finds the request each time it's called, so one object, made at
module level, serves every request. [Server
sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions) covers the engine's other
options, the cookie, and signing out.
## 2. Add the session route and server functions
The browser's client signs out and gets the access token through a session
route: a route in your app that the browser's client calls.
`sessionRoute` from `@monarcode/session-kit/tanstack-start/server` makes its
`GET` and `POST` handlers. Start leaves a route's `server.handlers` out of the
browser bundle, and `serverAuth` with them:
```ts title="src/routes/api/session.ts"
import { sessionRoute } from "@monarcode/session-kit/tanstack-start/server";
import { createFileRoute } from "@tanstack/react-router";
import { serverAuth } from "../../auth/server";
export const Route = createFileRoute("/api/session")({
server: { handlers: sessionRoute(serverAuth) },
});
```
The session route answers your own site's pages only, so another site can't
sign the user out: see [The session route](https://session-kit.pages.dev/docs/security#the-session-route).
Two server functions do the rest. One signs in with your form's input. The
other reads the session, because `loadSession` reads it while Start renders on
the server, where the client can't call a route on its own site:
```ts title="src/auth/functions.ts"
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { login, session } from "./server";
export const getSessionFn = createServerFn().handler(() =>
session.getSession(),
);
export const signInFn = createServerFn({ method: "POST" })
.validator(z.object({ username: z.string(), password: z.string() }))
.handler(async ({ data }) => {
const tokens = await login(data.username, data.password);
return session.signIn(tokens);
});
```
`getSession` and `signIn` resolve `{ sessionId, user }`, never tokens, so
their results are safe to send to the browser. Start's compiler replaces each
handler with a request in the browser bundle, and leaves `session` out of it.
## 3. Refresh before rendering
The server refreshes tokens that are about to expire before any route or
server function reads them, while the response can still set the cookie.
After Start starts streaming a page, a cookie set later is lost, and so are
the new tokens. `refreshSession` from
`@monarcode/session-kit/tanstack-start/server` does the refresh, in Start's
own request middleware:
```ts title="src/start.ts"
import { refreshSession } from "@monarcode/session-kit/tanstack-start/server";
import {
createCsrfMiddleware,
createMiddleware,
createStart,
} from "@tanstack/react-start";
import { serverAuth } from "./auth/server";
const sessionMiddleware = createMiddleware({ type: "request" }).server(
refreshSession(serverAuth),
);
export const startInstance = createStart(() => ({
requestMiddleware: [
createCsrfMiddleware({
filter: ({ handlerType }) => handlerType === "serverFn",
}),
sessionMiddleware,
],
}));
```
Start bundles `src/start.ts` for the browser too, but strips what's inside
`.server()`, so `serverAuth` stays on the server.
`refreshSession` refreshes access tokens that expire within 60 seconds. For
tokens that live a minute or less, pass a smaller `within`, such as
`refreshSession(serverAuth, { within: 15 })`.
[Refresh before rendering](https://session-kit.pages.dev/docs/server-rendering/server-sessions#refresh-before-rendering)
says what happens when a refresh fails.
`createCsrfMiddleware` protects your server functions, because an app that
defines `createStart` has no CSRF check until it adds one. Here's what it
covers:
- Its `filter` limits the check to server-function calls. Without the filter,
it also refuses page loads from links on other sites and from the address
bar.
- Filtered this way, it doesn't check server routes. `sessionRoute` refuses
other sites itself. A server route of your own that changes the session
must check too: see
[Check your own routes](https://session-kit.pages.dev/docs/security#check-your-own-routes).
## 4. Create the browser client
The client that routes and components use comes from `createMirrorAuth`. It
mirrors the session the server read, and calls your server functions and the
session route. Create it in a function, not at module level:
```ts title="src/auth/client.ts"
import { createMirrorAuth } from "@monarcode/session-kit";
import { getSessionFn, signInFn } from "./functions";
export function createAppAuth() {
return createMirrorAuth({
name: "app",
session: null, // filled by loadSession, then by hydration
endpoint: "/api/session",
revalidate: () => getSessionFn(),
signIn: (data: { username: string; password: string }) =>
signInFn({ data }),
});
}
export type AppAuth = ReturnType;
```
Let TypeScript infer the client's types from its options. With
`createMirrorAuth(…)`, `signIn` would be left out.
The Router creates the client in `getRouter`, which Start calls once per
request on the server and once in the browser. `connectSession` sends the
session the server read to the browser with the page, and runs the guards
again when the session changes there:
```tsx title="src/router.tsx"
import { connectSession } from "@monarcode/session-kit/tanstack-start";
import { createRouter } from "@tanstack/react-router";
import { createAppAuth } from "./auth/client";
import { routeTree } from "./routeTree.gen";
export function getRouter() {
const auth = createAppAuth();
const router = createRouter({ routeTree, context: { auth } });
connectSession(router);
return router;
}
declare module "@tanstack/react-router" {
interface Register {
router: ReturnType;
}
}
```
A `dehydrate` and a `hydrate` of your own, such as for a query cache, go to
`createRouter` as usual. `connectSession` keeps them.
## 5. Load the session, then guard routes
The root route's `beforeLoad` reads the request's session into the client
with `loadSession`, before any guard runs. In the browser, the session that
came with the page is already there, so it doesn't call the server. The root
route also renders the document, with `` so the page hydrates, and
an error component for when the session can't be read:
```tsx title="src/routes/__root.tsx"
import type { ReactNode } from "react";
import { loadSession } from "@monarcode/session-kit/tanstack-start";
import {
createRootRouteWithContext,
HeadContent,
Outlet,
Scripts,
useRouter,
type ErrorComponentProps,
} from "@tanstack/react-router";
import type { AppAuth } from "../auth/client";
export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({
beforeLoad: ({ context }) => loadSession(context.auth),
shellComponent: Document,
errorComponent: SessionError,
component: Outlet,
});
function Document({ children }: { children: ReactNode }) {
return (
{children}
);
}
function SessionError({ error }: ErrorComponentProps) {
const router = useRouter();
return (
{error instanceof Error ? error.message : "Something went wrong"}
{/* Runs loadSession again. */}
);
}
```
When the server can't read the session, such as after a failed refresh,
`loadSession` rejects and `SessionError` shows. Its button calls
`router.invalidate()`, which runs `loadSession` again.
Guards are the ones from `@monarcode/session-kit/tanstack-router`. On the
server, a guard's redirect is a real HTTP redirect:
```tsx title="src/routes/_authenticated.tsx"
import {
requireSession,
SessionOutlet,
} from "@monarcode/session-kit/tanstack-router";
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
requireSession(context.auth, { location }),
component: () => Loading…} />,
});
```
A signed-out user who opens a page under `_authenticated`, such as `/orders`,
lands on `/login?redirectTo=%2Forders`.
[Guard private routes](https://session-kit.pages.dev/docs/setups/tanstack-router#3-guard-private-routes)
explains `SessionOutlet`. This route needs no error component of its own:
`loadSession` reports a failed read first, in the root route.
Guards decide what a page shows. A server function that returns private data
must check the session itself, with `session.getSession()` or
`session.credentials.get()`, as `getOrdersFn` does in
[Call your API](#call-your-api).
## 6. Sign in
The client's `signIn` sends what it's given to your `signInFn`, then takes the
session it returns, runs the guards again and tells other tabs. A small helper
turns a failure into the message to show:
```ts title="src/sign-in.ts"
import type { AppAuth } from "./auth/client";
/** Signs in, and resolves the message to show when it fails. */
export async function signIn(
auth: AppAuth,
username: string,
password: string,
): Promise {
try {
await auth.signIn({ username, password });
return null;
} catch (error) {
// What signInFn threw, such as your backend's message for a wrong
// password.
return error instanceof Error ? error.message : "Could not sign in";
}
}
```
The sign-in route has the `redirectIfSignedIn` guard, so a signed-in user goes
on to `redirectTo`. Its form gets the client with `useAuthClient`, from Router
context:
```tsx title="src/routes/login.tsx"
import { useState, type FormEvent } from "react";
import { safeReturnTo } from "@monarcode/session-kit";
import {
redirectIfSignedIn,
useAuthClient,
} from "@monarcode/session-kit/tanstack-router";
import { createFileRoute } from "@tanstack/react-router";
import { signIn } from "../sign-in";
export const Route = createFileRoute("/login")({
validateSearch: (search: Record) => ({
redirectTo: safeReturnTo(search.redirectTo),
}),
beforeLoad: ({ context, search }) =>
redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
component: Login,
});
function Login() {
const auth = useAuthClient();
const [error, setError] = useState(null);
async function submit(event: FormEvent) {
event.preventDefault();
const form = new FormData(event.currentTarget);
const username = String(form.get("username"));
setError(await signIn(auth, username, String(form.get("password"))));
}
return (
);
}
```
The form doesn't navigate after a sign-in. `connectSession` runs the guards
again, and `redirectIfSignedIn` sends the user on. To try it, sign in as
`emilys` with the password `emilyspass`. A wrong password shows DummyJSON's
own message, which `login` threw.
In this guide, the server signs in with your backend, so the user in the
cookie comes from the backend. If the browser has to sign in with the backend
itself, for example through a provider's SDK, have `signInFn` take the tokens
instead, as [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid) shows.
## 7. Sign out
The client's `signOut()` signs out on the server through the session route,
which clears the cookie and calls your `revoke` option, if `createServerAuth`
has one. It then signs out this tab and tells the others. The guards run
again, so `requireSession` sends the user to the sign-in page. Put a button
like this one on any page under `_authenticated`:
```tsx title="src/sign-out.tsx"
import { useAuthClient } from "@monarcode/session-kit/tanstack-router";
export function SignOutButton() {
const auth = useAuthClient();
// A failed sign-out keeps the session, and shows in `state.error`.
return (
);
}
```
Without `revoke`, a copy of the cookie made before sign-out still works: see
[Sign-out](https://session-kit.pages.dev/docs/server-rendering/server-sessions#sign-out).
## Call your API
Your server functions call your API with `createAuthFetch` from
`@monarcode/session-kit/http`. Given `session`, it sends the access token of
the request Start is handling, refreshed first if it has expired. Make it
once, in a server-only module:
```ts title="src/auth/auth-fetch.ts"
import "@tanstack/react-start/server-only";
import { createAuthFetch } from "@monarcode/session-kit/http";
import { API, session } from "./server";
export const authFetch = createAuthFetch(session, { baseUrl: `${API}/` });
```
Then call it in a server function. This one checks the session first, so it
can ask for the signed-in user's orders:
```ts title="src/orders.ts"
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { authFetch } from "./auth/auth-fetch";
import { session } from "./auth/server";
const orders = z.object({ carts: z.array(z.object({ id: z.number() })) });
export const getOrdersFn = createServerFn().handler(async () => {
const current = await session.getSession();
if (!current) throw new Error("Sign in to see your orders");
const response = await authFetch(`auth/carts/user/${current.user.id}`);
if (!response.ok) throw new Error(`Orders failed (${response.status})`);
return orders.parse(await response.json()).carts;
});
```
When the user is signed out, `authFetch` rejects with `UNAUTHENTICATED`. When
your API answers 401, it gets a new access token and saves it in the cookie.
It sends a `GET` or `HEAD` again with the new token, as
[After a 401](https://session-kit.pages.dev/docs/client/requests#after-a-401) explains.
With an HTTP client of your own, such as ky or axios, see
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients). A client without a
`fetch` option reads the token with `session.credentials.get()`.
To call your API from the browser too, turn on `clientCredentials` in
`createServerAuth`: see
[The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser).
The example app does this.
## Things to know
- **One session per request.** Each call to `session` reads the request Start
is handling, and calls during one request share what it read and one
refresh. Outside a request, such as in the browser, its methods reject with
`INVALID_OPTIONS`, and `isCurrent` and `state` throw it.
- **Caching.** `refreshSession` sends `Cache-Control: private, no-store`
with each response that doesn't set its own, so shared caches keep no
user's page: see
[Refresh before rendering](https://session-kit.pages.dev/docs/server-rendering/server-sessions#refresh-before-rendering)
for `cacheControl`.
- **Prerendering.** A prerendered page renders at build time, without a
cookie, so it shows the signed-out state. Don't prerender pages that read
the session.
- **Other tabs.** Signing in or out in one tab reaches the others, which ask
the server for the session and run the guards again: see
[How tabs stay in step](https://session-kit.pages.dev/docs/server-rendering#how-tabs-stay-in-step).
- **Deploying.** Several server instances, the cookie's size, and plain http
during development are covered in
[Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions).
## Next steps
- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): the cookie, the
secret, signing out, and the limits every server-rendered setup shares.
- [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid): sign in from the browser
and call your API there, with the session still on the server.
- [Using the client](https://session-kit.pages.dev/docs/client): what the browser's client can do.
- [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run Effects with a
request's session.
# React Router (https://session-kit.pages.dev/docs/setups/react-router)
Your app uses React Router, and some of its routes are for signed-in users
only. In this guide, you add Session kit to the app from Getting started, in
the mode your app uses. React Router has three modes, and Session kit guards
each one the way that mode works:
| Mode | The guard | Beside it |
| ---------------------------- | -------------------------------------------- | -------------------------------------- |
| Declarative | `SessionOutlet` | Nothing |
| Data | `requireSessionLoader` as the `loader` | `SessionOutlet`, `useAuthRevalidation` |
| Framework, with `ssr: false` | `requireSessionLoader` as the `clientLoader` | `SessionOutlet`, `useAuthRevalidation` |
Each mode has a complete example app. For framework mode with server
rendering, follow
[React Router with server rendering](https://session-kit.pages.dev/docs/setups/react-router-ssr) instead.
## Before you begin
- The app from [Getting started](https://session-kit.pages.dev/docs/getting-started), through step 5. This
guide uses its client in `src/auth.ts`, its form in `src/sign-in.tsx`, and
`fetchProfile` from `src/api.ts`.
- React Router 7 or 8. React Router 8 needs React 19.2.7 or newer, so with
React 18, use React Router 7. [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility)
lists the versions.
## Installation
Install Session kit, React Router and Zod:
```npm
npm install @monarcode/session-kit react-router zod
```
## Add a page to protect
Every mode on this page protects the same page. It reads the user and the
client with the hooks from `@monarcode/session-kit/react`:
```tsx title="src/home.tsx"
import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
export function Home() {
const user = useAuth((state) => state.user);
const auth = useAuthClient();
return (
Welcome, {user?.firstName}
);
}
```
Each mode renders `AuthProvider` and registers the client's type, as step 4
of Getting started does, so these hooks carry your user. A sign-out that
fails shows in an alert that each mode renders outside the private routes, so
the button can ignore the rejection.
`AuthProvider` restores the saved session when it mounts. With `localStorage`
and a synchronous schema, that happens
[before the first paint](https://session-kit.pages.dev/docs#what-it-does).
## Declarative mode
Declarative mode has no loaders, so `SessionOutlet` is the guard. Render it
as a layout route's element, `}>`, and the routes
inside it render only while someone is signed in. `AuthProvider` goes around
the router:
```tsx title="src/main.tsx"
import { StrictMode } from "react";
import {
BrowserRouter,
Navigate,
Route,
Routes,
useSearchParams,
} from "react-router";
import { isSignedIn, safeReturnTo } from "@monarcode/session-kit";
import { AuthProvider, useAuth } from "@monarcode/session-kit/react";
import { SessionOutlet } from "@monarcode/session-kit/react-router";
import { createRoot } from "react-dom/client";
import { auth } from "./auth.js";
import { Home } from "./home.js";
import { SignIn } from "./sign-in.js";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
/** The guard: its child routes render only while someone is signed in. */
function Private() {
return (
Checking session…}
unavailable={({ error, retry }) => (
{error?.message ?? "Can't reach the server."}
)}
/>
);
}
/** Signing in changes the state, which renders this again and redirects. */
function Login() {
const signedIn = useAuth(isSignedIn);
const [search] = useSearchParams();
if (signedIn)
return ;
return ;
}
/**
* Failures that outlive the page that caused them, such as a sign-out that
* couldn't clear storage.
*/
function AuthErrorMessage() {
const error = useAuth((state) => state.error);
return error ?
{error.message}
: null;
}
createRoot(document.getElementById("root")!).render(
} />
}>
} />
,
);
```
`SessionOutlet` shows `pending` while the saved session is restored. It sends
a signed-out user to `/login`, or the `loginPath` you pass, with `redirectTo`
set to where they were going. A signed-out user who opens `/orders?tab=2`
lands on `/login?redirectTo=%2Forders%3Ftab%3D2`, and returns there after
signing in. After a failed refresh, it renders `unavailable`. Without
`unavailable`, it throws the error to the nearest error boundary.
`Login` sends a signed-in user on to `redirectTo`, so the form doesn't
navigate after it signs in. `safeReturnTo` turns `redirectTo` into a path
that's safe to send the user to. Anything that leads out of your app, or back
to the sign-in page, becomes `/`, so a stale `redirectTo` can't loop. The
[`safeReturnTo` reference](https://session-kit.pages.dev/docs/reference/core#safereturnto) lists every
rule.
A complete app is in
[`examples/react-router-declarative`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-declarative).
## Data mode
In data mode, loaders run before a route renders, so the guard goes there. A
signed-out user is redirected before a private route renders. The router
goes in its own file, and `src/main.tsx` renders it.
### 1. Create the router
Guard the private routes with a loader, and keep the guards in step with the
session from the root route:
```tsx title="src/router.tsx" app="data"
import { createBrowserRouter, Outlet, useRouteError } from "react-router";
import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
import {
redirectIfSignedInLoader,
requireSessionLoader,
SessionOutlet,
useAuthRevalidation,
} from "@monarcode/session-kit/react-router";
import { auth } from "./auth.js";
import { Home } from "./home.js";
import { SignIn } from "./sign-in.js";
/** Runs the loaders again when auth changes, and shows auth errors. */
function Root() {
useAuthRevalidation();
const error = useAuth((state) => state.error);
return (
<>
{error &&
{error.message}
}
>
);
}
/** Shown after a failed refresh; a repeated failure shows here again. */
function SessionError() {
const error = useRouteError();
const client = useAuthClient();
return (
{error instanceof Error ? error.message : "Something went wrong"}
,
children: [
{
path: "/login",
loader: redirectIfSignedInLoader(auth),
element: ,
},
{
loader: requireSessionLoader(auth),
errorElement: ,
element: Checking session…} />,
children: [{ index: true, element: }],
},
],
},
]);
```
Three pieces work together:
- **`requireSessionLoader(auth)`** is the route's loader. It returns
`{ session }` as the route's loader data. It sends a signed-out user to
`/login`, or the `loginPath` you pass, with `redirectTo` set to the path
and query they asked for: `/orders?tab=2` lands on
`/login?redirectTo=%2Forders%3Ftab%3D2`. A failed refresh goes to the
route's error element instead, as
[Things to know](#things-to-know) explains. A loader that does more calls
`requireSession`, as [Guards in loaders](#guards-in-loaders) shows.
- **`useAuthRevalidation`** runs the loaders again when the session changes,
such as after a sign-in, a sign-out or an account switch, so the guards
check it again. Call it one time, in the root route.
[Its reference](https://session-kit.pages.dev/docs/reference/react-router#useauthrevalidation) lists
every change it reacts to.
- **`SessionOutlet`**, as the guarded route's element, renders child routes
only while the session the loader accepted is still the signed-in one. When
another account signs in, it shows `pending` until the loader has run for
the new session, so no page shows the previous account's loader data.
The sign-in route's `redirectIfSignedInLoader` runs again after a sign-in,
and sends the user on to `redirectTo`, so the form doesn't navigate. The root
route's `HydrateFallback` shows until the first loaders finish, such as while
the saved session is restored.
### 2. Render the router
Render the router inside `AuthProvider`, in `src/main.tsx`:
```tsx title="src/main.tsx" app="data"
import { StrictMode } from "react";
import { RouterProvider } from "react-router/dom";
import { AuthProvider } from "@monarcode/session-kit/react";
import { createRoot } from "react-dom/client";
import { auth } from "./auth.js";
import { router } from "./router.js";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
createRoot(document.getElementById("root")!).render(
,
);
```
A complete app is in
[`examples/react-router-data`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-data).
## Framework mode with `ssr: false`
Framework mode without a server is data mode with route modules. The guards
are the same, as each route's `clientLoader`. Keep the files from Getting
started, and `home.tsx` from [Add a page to protect](#add-a-page-to-protect),
in `app/`. Framework mode also needs `@react-router/dev`, which a
framework-mode app already has.
### 1. Turn off server rendering
In `react-router.config.ts`, set `ssr` to `false`. The build then prerenders
`index.html` from the root route, and everything else runs in the browser,
where the session is saved:
```ts title="react-router.config.ts"
import type { Config } from "@react-router/dev/config";
export default { ssr: false } satisfies Config;
```
### 2. Provide the client in the root route
In framework mode, `AuthProvider` goes in the root route. The root route also
keeps the guards in step with the session, and shows auth errors:
```tsx title="app/root.tsx"
import type { ReactNode } from "react";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
import { AuthProvider, useAuth } from "@monarcode/session-kit/react";
import { useAuthRevalidation } from "@monarcode/session-kit/react-router";
import { auth } from "./auth.js";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
export function Layout({ children }: { children: ReactNode }) {
return (
{children}
);
}
/** Runs the client loaders again when auth changes, and shows auth errors. */
function Root() {
useAuthRevalidation();
const error = useAuth((state) => state.error);
return (
<>
{error &&
{error.message}
}
>
);
}
export default function App() {
return (
);
}
/** Prerendered into index.html, and shown until the client loaders finish. */
export function HydrateFallback() {
return
Checking session…
;
}
```
`AuthProvider` mounts the client in an effect, so the build-time prerender of
the root route starts nothing, and the browser restores the session.
### 3. Guard a layout route
Guard a layout route with `requireSessionLoader` as its `clientLoader`. The
private routes go under it in step 5:
```tsx title="app/routes/protected.tsx"
import { useRouteError } from "react-router";
import { useAuthClient } from "@monarcode/session-kit/react";
import {
requireSessionLoader,
SessionOutlet,
} from "@monarcode/session-kit/react-router";
import { auth } from "../auth.js";
export const clientLoader = requireSessionLoader(auth);
export default function Protected() {
return Checking session…} />;
}
/** Shown after a failed refresh; a repeated failure shows here again. */
export function ErrorBoundary() {
const error = useRouteError();
const client = useAuthClient();
return (
{error instanceof Error ? error.message : "Something went wrong"}
);
}
```
### 4. Add the sign-in route
The sign-in route sends a signed-in user on to `redirectTo`. Its loader runs
again after a sign-in, so the form doesn't navigate:
```tsx title="app/routes/login.tsx"
import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router";
import { auth } from "../auth.js";
import { SignIn } from "../sign-in.js";
export const clientLoader = redirectIfSignedInLoader(auth);
export default SignIn;
```
### 5. Register the routes
In `app/routes.ts`, nest the private routes under the layout:
```ts title="app/routes.ts"
import {
index,
layout,
route,
type RouteConfig,
} from "@react-router/dev/routes";
export default [
route("login", "routes/login.tsx"),
layout("routes/protected.tsx", [index("routes/home.tsx")]),
] satisfies RouteConfig;
```
`routes/home.tsx` is the page from Add a page to protect, as its default
export: `export { Home as default } from "../home.js";`.
A complete app is in
[`examples/react-router-framework-spa`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-spa).
## Check the app
Whichever mode you chose, check the app:
1. Signed out, open `/`. You land on `/login?redirectTo=%2F`.
2. Sign in. You're back on `/`, with the welcome message.
3. Reload the page. You're still signed in.
4. Open a second tab and sign out there. The first tab goes to `/login`.
## Guards in loaders
Two functions guard a loader, in data mode and in framework mode. Both send a
signed-out user to `/login`, with `redirectTo`, and resolve `{ session }`,
typed with your user:
- **`requireSessionLoader(auth)`** is the whole loader. Use it on a route
that guards and loads nothing else, usually the layout route around your
private pages, as in [Data mode](#data-mode).
- **`requireSession(auth, { request })`** is a call inside a loader of your
own. Use it when the loader loads data too: data that only signed-in users
can load, or data that needs who is signed in.
React Router runs the loaders of nested routes at the same time, so a page's
loader doesn't wait for its layout's guard. A page whose loader calls your
API checks the session itself:
```tsx title="app/routes/profile.tsx"
import { useLoaderData } from "react-router";
import { requireSession } from "@monarcode/session-kit/react-router";
import { fetchProfile } from "../api.js";
import { auth } from "../auth.js";
export async function clientLoader({ request }: { request: Request }) {
const { session } = await requireSession(auth, { request });
return { name: session.user.firstName, profile: await fetchProfile() };
}
export default function Profile() {
const { name, profile } = useLoaderData();
return (
{name}, your email is {profile.email}.
);
}
```
In framework mode, add the page beside the index route in `app/routes.ts`:
`route("profile", "routes/profile.tsx")`. A signed-out user is redirected
before your API is called, rather than after a request that fails. Pass
`requireSession` the same `loginPath` and `basename` as the layout's guard.
The sign-in page has the same pair: `redirectIfSignedInLoader(auth)` as its
loader, or `redirectIfSignedIn(auth, { redirectTo })` in a loader that does
more.
## Layouts around guarded pages
A guarded route often has UI of its own around its pages, such as a sidebar
and a top bar. Render it in the guarded route's element, with `SessionOutlet`
where the pages go:
```tsx title="src/dashboard.tsx"
import { useAuth } from "@monarcode/session-kit/react";
import { SessionOutlet } from "@monarcode/session-kit/react-router";
/** The guarded route's element: `element: `. */
export function Dashboard() {
// From state, not loader data: this stays mounted through a sign-out.
const user = useAuth((state) => state.user);
const sessionId = useAuth((state) => state.sessionId);
return (
{user ? `Signed in as ${user.firstName}` : null}
{/* Keyed by session: one account's choices never show for the next. */}
Checking session…} />
);
}
```
Three things follow from where `SessionOutlet` sits:
- **It protects only what it renders.** After a sign-out it redirects to the
sign-in page. After an account switch it remounts the pages, and in data
and framework mode shows `pending` until the guard runs again. The layout
around it stays mounted meanwhile.
- **Read the user from state there.** In the layout, use
`useAuth((state) => state.user)` and handle `null`. The loader's `session`
is the one the guard accepted, which for that moment is the previous one.
- **Key what belongs to an account.** Layout UI that holds state for one
account, such as a draft or an open panel, takes the session as its `key`,
so the next account starts fresh.
## Things to know
- **Another sign-in page.** If sign-in isn't at `/login`, pass the same
`loginPath` to `SessionOutlet`, `requireSessionLoader` (or
`requireSession`), `redirectIfSignedInLoader` and `safeReturnTo`.
- **A router `basename`.** Pass it to `requireSessionLoader` or
`requireSession` too, so `redirectTo` leaves it out. Redirects add it
again. `SessionOutlet` needs nothing.
- **A failed refresh is not a redirect.** When the access token has expired
and a refresh fails, such as while your backend is down, the status is
`unavailable`. The saved session is kept, and `auth.retry()` can restore
access, so the guards don't redirect. In declarative mode, `SessionOutlet`
renders `unavailable`, or throws to the nearest error boundary without it.
In data and framework mode, the guard rethrows the error for the route's
error element. If the retry fails too, the new error shows there again.
- **A route's own `shouldRevalidate`.** It decides whether that route's
loader runs again, even after the session changes. If it returns `false`,
the guard in that loader doesn't run. Return `defaultShouldRevalidate` for
the cases it doesn't handle.
- **The fragment.** A loader's request leaves out the URL's `#fragment`, so
the loader guards' `redirectTo` doesn't keep it. `SessionOutlet` keeps it.
- **Locked sessions.** [Locking](https://session-kit.pages.dev/docs/client/locking) is for native apps, so
the guards treat a locked session as signed out.
- **Cached data.** Scope private cached data, such as TanStack Query results,
to `state.sessionId`, which is new on every sign-in. See
[State](https://session-kit.pages.dev/docs/client/state).
## Next steps
- [Call your API](https://session-kit.pages.dev/docs/getting-started#5-call-your-api) with `authFetch`, as
in Getting started, or with
[ky, axios or openapi-fetch](https://session-kit.pages.dev/docs/client/other-http-clients). It works
unchanged with the router.
- [Using the client](https://session-kit.pages.dev/docs/client): update the user, sign out, and use the
client's other methods.
- [Effect and effetch](https://session-kit.pages.dev/docs/effect): use the same client as an Effect
service.
- [React Router reference](https://session-kit.pages.dev/docs/reference/react-router): every option of the
guards, `SessionOutlet` and `useAuthRevalidation`.
# React Router with server rendering (https://session-kit.pages.dev/docs/setups/react-router-ssr)
Your React Router app runs in framework mode and renders pages on the server,
and you want the first response to show the signed-in page, with no "Checking
session…" state and no flash of signed-out content. To do that, the server
has to hold the session. In this guide, you keep it in an encrypted cookie:
an action signs in, middleware refreshes the tokens, and loaders read the
session.
Components get a small client that mirrors the session the server rendered,
and the [hooks](https://session-kit.pages.dev/docs/getting-started#4-read-the-session-in-react) work with
it. [Server rendering](https://session-kit.pages.dev/docs/server-rendering) explains how the pieces fit. A
complete app is in
[`examples/react-router-framework-ssr`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-ssr).
If your app uses framework mode with `ssr: false`, follow
[React Router](https://session-kit.pages.dev/docs/setups/react-router#framework-mode-with-ssr-false)
instead.
## Before you begin
- React Router 8, which needs Node.js 22.22 or newer and React 19.2.7 or
newer. See [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) for the other
versions.
- With React 18, use React Router 7, version 7.9 or later, and turn its
middleware on with `future: { v8_middleware: true }` in
`react-router.config.ts`. The code on this page is for React Router 8. On
7.14 and earlier, read the URL with `new URL(request.url)` where the code
uses the `url` argument.
- A secret of 32 or more random characters to seal the cookie, such as the
output of `openssl rand -base64 32`, set as `SESSION_SECRET` on the server.
`react-router build` doesn't need it.
[The secret](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-secret) says how to
keep and rotate it.
- The code signs in with [DummyJSON](https://dummyjson.com/docs/auth)'s test
backend, as [Getting started](https://session-kit.pages.dev/docs/getting-started) does. Replace its URLs
with your backend's.
## Installation
To install the packages, run the following command:
```npm
npm install @monarcode/session-kit react-router zod
```
## 1. Create the server engine
The server engine keeps the session in a cookie sealed with your secret, and
refreshes the tokens with your backend. `createServerAuth` from
`@monarcode/session-kit/server` makes it. From
`@monarcode/session-kit/react-router/server`, `routerAuth` gives you a
request's session by its `context`, and `requireSession` makes the guard
that protects routes in step 4. Create them in a `.server` module, so React
Router refuses to bundle it for the browser:
```ts title="app/auth/session.server.ts"
import {
requireSession,
routerAuth,
} from "@monarcode/session-kit/react-router/server";
import { createServerAuth } from "@monarcode/session-kit/server";
import { z } from "zod";
export const API = "https://dummyjson.com";
const userSchema = z.object({ id: z.number(), firstName: z.string() });
const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() });
export const serverAuth = createServerAuth({
name: "app",
user: userSchema,
secret: process.env.SESSION_SECRET!,
refresh: async ({ refreshToken, signal }) => {
const response = await fetch(`${API}/auth/refresh`, {
method: "POST",
signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
// DummyJSON rejected the refresh token: sign out.
if (response.status === 401 || response.status === 403) return null;
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return tokens.parse(await response.json());
},
});
/** The request's session: `auth(context)` in middleware, loaders, actions. */
export const auth = routerAuth(serverAuth);
/** Lets only signed-in users through to the routes it guards. */
export const signedIn = requireSession(serverAuth);
/** Signs in with your backend, from the server. */
export async function login(username: string, password: string) {
const response = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
// The backend says why, such as wrong credentials, in `message`.
const failure = z.object({ message: z.string() }).safeParse(body);
throw new Error(
failure.success
? failure.data.message
: `Sign-in failed (${response.status})`,
);
}
return { ...tokens.parse(body), user: userSchema.parse(body) };
}
```
`auth(context)` returns the same session for every call with the same
`context`, which React Router makes per request. [Server
sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions) covers the engine's other
options, the cookie, and signing out.
## 2. Add the root route
The root route does three jobs: its middleware refreshes the session, its
loader reads it, and its component gives it to the browser's client. First,
the client, which `createMirrorAuth` makes from the session the root loader
read and the session route that step 3 adds:
```ts title="app/auth/client.ts"
import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit";
// Types only: left out of the browser's bundle.
import type { serverAuth } from "./session.server";
export type AppSession = SessionOf;
export function createAppAuth(session: AppSession | null) {
return createMirrorAuth({
name: "app",
session,
endpoint: "/auth/session",
});
}
export type AppAuth = ReturnType;
```
Then the root route. Register the client's type here, where you render
`AuthProvider`, so the hooks carry your user:
```tsx title="app/root.tsx"
import type { ReactNode } from "react";
import {
Links,
Meta,
Outlet,
Scripts,
useLoaderData,
useRevalidator,
useRouteError,
type LoaderFunctionArgs,
} from "react-router";
import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react";
import { sessionMiddleware } from "@monarcode/session-kit/react-router/server";
import { createAppAuth, type AppAuth } from "./auth/client";
import { auth, serverAuth } from "./auth/session.server";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: AppAuth;
}
}
export const middleware = sessionMiddleware(serverAuth);
export async function loader({ context }: LoaderFunctionArgs) {
return { session: await auth(context).getSession() };
}
export function Layout({ children }: { children: ReactNode }) {
return (
{children}
);
}
export default function App() {
const { session } = useLoaderData();
const { revalidate } = useRevalidator();
const auth = useMirrorAuth({
create: createAppAuth,
session,
onChange: revalidate,
});
return (
);
}
/** Shown when the session can't be read, such as after a failed refresh. */
export function ErrorBoundary() {
const error = useRouteError();
const { revalidate } = useRevalidator();
return (
{error instanceof Error ? error.message : "Something went wrong"}
);
}
```
Here's what each part does:
- **`sessionMiddleware(serverAuth)`** reads each request's cookies and sets
the ones written on the response, redirects included. That's what lets
`auth(context)` work in middleware, loaders and actions. It then refreshes
tokens that are about to expire, before any loader reads them, while the
response can still set the cookie.
- **The loader** returns `getSession()`, which resolves
`{ sessionId, user }`, never tokens, so it's safe to send to the browser.
- **`useMirrorAuth`** from `@monarcode/session-kit/react` creates the client
once per request on the server, never at module level, and keeps it in
step with the server both ways. After an action signs in or out, the loader
reads the new session and the client takes it. When the session changes in
the browser, here or in another tab, it calls `onChange`. Here that's
`revalidate` from `useRevalidator()`, which runs the loaders again, so the
server's redirects run. The client-side guides add `useAuthRevalidation`
for this, and here `useMirrorAuth` does it.
- **`ErrorBoundary`** shows a session that can't be read, such as after a
failed refresh, and its button runs the loaders again.
`sessionMiddleware` refreshes tokens that expire within 60 seconds. For
tokens that live a minute or less, pass a smaller `within`, such as
`sessionMiddleware(serverAuth, { within: 15 })`.
[Refresh before rendering](https://session-kit.pages.dev/docs/server-rendering/server-sessions#refresh-before-rendering)
says what happens when a refresh fails, and how the middleware sets
`Cache-Control`.
## 3. Add the session route
The browser's client reads the session and signs out through a session
route: a resource route in your app that the browser's client calls.
`sessionRoute` from `@monarcode/session-kit/react-router/server` makes its
loader and action:
```ts title="app/routes/auth.session.ts"
import { sessionRoute } from "@monarcode/session-kit/react-router/server";
import { serverAuth } from "../auth/session.server";
const route = sessionRoute(serverAuth);
export const loader = route.loader;
export const action = route.action;
```
Export the loader and action one by one, as this file does. React Router's
build fails on a destructured `export const { loader, action }`.
The session route answers your own site's pages only, so another site can't
sign the user out: see [The session route](https://session-kit.pages.dev/docs/security#the-session-route).
## 4. Protect routes
Guard a layout route with `signedIn`, the middleware `requireSession` made.
It runs on the server before any loader or action nested in it, which
loaders on their own can't promise:
```tsx title="app/routes/protected.tsx"
import { Outlet } from "react-router";
import { signedIn } from "../auth/session.server";
export const middleware = [signedIn];
// So navigation in the browser runs the middleware.
export const loader = () => null;
export default function Protected() {
return ;
}
```
A signed-out user who opens a page in the layout, such as `/orders`, lands on
`/login?redirectTo=%2Forders`.
During navigation in the browser, server middleware runs only when a route
has a loader to fetch. The layout has one in case the routes nested in it
don't.
Pages nested in the layout read the user with the hooks, as any component
does:
```tsx title="app/routes/home.tsx"
import { useAuth } from "@monarcode/session-kit/react";
export default function Home() {
const user = useAuth((state) => state.user);
return
Welcome, {user?.firstName}
;
}
```
A loader nested in the layout gets the session from
`signedIn.session(context)`, which is never `null` there. [Call your
API](#call-your-api) uses it.
## 5. Sign in
The sign-in route's action signs in with your backend and seals the result
into the cookie. Its loader, `redirectIfSignedIn`, sends a user who is
already signed in on to `redirectTo`. The form works before the page's
scripts load:
```tsx title="app/routes/login.tsx"
import {
data,
Form,
redirect,
useActionData,
type ActionFunctionArgs,
} from "react-router";
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server";
import { auth, login, serverAuth } from "../auth/session.server";
export const loader = redirectIfSignedIn(serverAuth);
export async function action({ request, context, url }: ActionFunctionArgs) {
const form = await request.formData();
try {
const tokens = await login(
String(form.get("username")),
String(form.get("password")),
);
await auth(context).signIn(tokens);
} catch (error) {
return data(
{ error: error instanceof Error ? error.message : "Sign-in failed" },
{ status: 400 },
);
}
throw redirect(safeReturnTo(url.searchParams.get("redirectTo")));
}
export default function Login() {
const result = useActionData();
return (
);
}
```
To try it, sign in as `emilys` with the password `emilyspass`. The action
redirects to `redirectTo`, made safe with `safeReturnTo`. A failed sign-in
returns its message with status 400, for the form to show, and React Router
doesn't run the page's loaders again after a 4xx action.
React Router 7.12 and later refuse route actions posted from other sites. On
7.9 to 7.11, refuse them yourself at the start of the action: see
[Check your own routes](https://session-kit.pages.dev/docs/security#check-your-own-routes).
In this guide, the server signs in with your backend, so the user in the
cookie comes from the backend. If the browser has to sign in with the backend
itself, have the action take the tokens instead:
[Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid) shows how.
## 6. Sign out
The client's `signOut()` signs out on the server through the session route,
which clears the cookie and calls your `revoke` option, if `createServerAuth`
has one. It then signs out this tab and tells the others. `useMirrorAuth`
runs the loaders again, so `signedIn` sends the user to the sign-in page.
Put a button like this one on any page under the layout:
```tsx title="app/sign-out-button.tsx"
import { useAuthClient } from "@monarcode/session-kit/react";
export function SignOutButton() {
const auth = useAuthClient();
// A failed sign-out keeps the session, and shows in `state.error`.
return (
);
}
```
Without `revoke`, a copy of the cookie made before sign-out still works: see
[Sign-out](https://session-kit.pages.dev/docs/server-rendering/server-sessions#sign-out).
## 7. Register the routes
Last, add the routes to `app/routes.ts`. The sign-in route sits outside the
layout, and the pages it protects sit inside:
```ts title="app/routes.ts"
import {
index,
layout,
route,
type RouteConfig,
} from "@react-router/dev/routes";
export default [
route("login", "routes/login.tsx"),
layout("routes/protected.tsx", [index("routes/home.tsx")]),
// The session route the browser's client calls.
route("auth/session", "routes/auth.session.ts"),
] satisfies RouteConfig;
```
The sign-in route's path matters: `signedIn` sends signed-out users to
`/login`. To use another path, pass `loginPath` to `requireSession`.
## Call your API
Your loaders and actions call your API with `createAuthFetch` from
`@monarcode/session-kit/http`. Given the request's session, it sends the
access token, refreshed first if it has expired. This page sits inside the
layout, so its loader reads the user from `signedIn`:
```tsx title="app/routes/orders.tsx"
import { useLoaderData, type LoaderFunctionArgs } from "react-router";
import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";
import { API, auth, signedIn } from "../auth/session.server";
const orders = z.object({ carts: z.array(z.object({ id: z.number() })) });
export async function loader({ context }: LoaderFunctionArgs) {
const { user } = signedIn.session(context);
const authFetch = createAuthFetch(auth(context), { baseUrl: `${API}/` });
const response = await authFetch(`auth/carts/user/${user.id}`);
if (!response.ok) throw new Error(`Orders failed (${response.status})`);
return orders.parse(await response.json()).carts;
}
export default function Orders() {
const carts = useLoaderData();
return
{carts.length} orders
;
}
```
Then add it inside the layout in `app/routes.ts`:
```ts title="app/routes.ts" app="orders"
import {
index,
layout,
route,
type RouteConfig,
} from "@react-router/dev/routes";
export default [
route("login", "routes/login.tsx"),
layout("routes/protected.tsx", [
index("routes/home.tsx"),
route("orders", "routes/orders.tsx"),
]),
route("auth/session", "routes/auth.session.ts"),
] satisfies RouteConfig;
```
When your API answers 401, `authFetch` gets a new access token and saves it in
the cookie. It sends a `GET` or `HEAD` again with the new token, as
[After a 401](https://session-kit.pages.dev/docs/client/requests#after-a-401) explains.
A loader outside the layout has no `signedIn` to rely on. It can check
`await auth(context).getSession()` itself, and throw
`redirect(loginHref("/login", "/orders"))` when it's `null`. `loginHref` from
`@monarcode/session-kit` builds `/login?redirectTo=%2Forders`, so the user
comes back after signing in.
With an HTTP client of your own, such as ky or axios, see
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients). A client without a
`fetch` option reads the token with `auth(context).credentials.get()`.
To call your API from the browser too, turn on `clientCredentials` in
`createServerAuth`: see
[The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser).
The example app does this.
## Things to know
- **Deferred data.** The request's session can set cookies until the
response leaves `sessionMiddleware`, which first waits for a refresh under
way. Deferred data that reads the session while the page streams can't
save anything, so the middleware refreshes before that: see
[Requests that can't set cookies](https://session-kit.pages.dev/docs/server-rendering/server-sessions#requests-that-cant-set-cookies).
- **Guards with the same names.** `requireSession` and `redirectIfSignedIn`
on this page come from `@monarcode/session-kit/react-router/server`.
`@monarcode/session-kit/react-router` exports guards with the same names
that take the browser's client, for apps without server rendering: see
[React Router](https://session-kit.pages.dev/docs/setups/react-router).
- **A `basename`.** Pass it to the guard too, as
`requireSession(serverAuth, { basename: "/app" })`. React Router adds it to
loaders' and actions' redirects, but not to middleware's, so the guard adds
it to its own. The client's `endpoint` includes it as well:
`"/app/auth/session"`.
- **Other tabs.** Signing in or out in one tab reaches the others, which ask
the server for the session and run their loaders again: see
[How tabs stay in step](https://session-kit.pages.dev/docs/server-rendering#how-tabs-stay-in-step).
- **Deploying.** Several server instances, the cookie's size, and plain http
during development are covered in
[Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions).
## Next steps
- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): the cookie, the
secret, signing out, and the limits every server-rendered setup shares.
- [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid): sign in from the browser
and call your API there, with the session still on the server.
- [Using the client](https://session-kit.pages.dev/docs/client): what the browser's client can do.
- [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run Effects with a
request's session.
# Next.js (https://session-kit.pages.dev/docs/setups/next)
Your Next.js app uses the App Router, and you want the first response to show
the signed-in page, with no "Checking session…" state and no flash of
signed-out content. To do that, the server has to hold the session. In this
guide, you keep it in an encrypted cookie: a Server Function signs in, Proxy
refreshes the tokens, and Server Components read the session.
Client Components get a small client that mirrors the session the server
rendered, and the [hooks](https://session-kit.pages.dev/docs/getting-started#4-read-the-session-in-react)
work with it. [Server rendering](https://session-kit.pages.dev/docs/server-rendering) explains how the
pieces fit. A complete app is in
[`examples/next-app`](https://github.com/monarcode/session-kit/tree/main/examples/next-app).
## Before you begin
- Next.js 16 with the App Router, which needs Node.js 20.9 or newer. See
[Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) for the other versions.
- A secret of 32 or more random characters to seal the cookie, such as the
output of `openssl rand -base64 32`, set as `SESSION_SECRET` on the server.
`next build` doesn't need it.
[The secret](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-secret) says how to
keep and rotate it.
- The code signs in with [DummyJSON](https://dummyjson.com/docs/auth)'s test
backend, as [Getting started](https://session-kit.pages.dev/docs/getting-started) does. Replace its URLs
with your backend's.
## Installation
To install the packages, run the following command:
```npm
npm install @monarcode/session-kit next zod
```
## 1. Create the server engine
The server engine keeps the session in a cookie sealed with your secret, and
refreshes the tokens with your backend. `createServerAuth` from
`@monarcode/session-kit/server` makes it. Create it in a server-only module,
so Next refuses to bundle it for the browser:
```ts title="lib/auth/server.ts"
import "server-only";
import { createServerAuth } from "@monarcode/session-kit/server";
import { z } from "zod";
export const API = "https://dummyjson.com";
const userSchema = z.object({ id: z.number(), firstName: z.string() });
const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() });
export const serverAuth = createServerAuth({
name: "app",
user: userSchema,
secret: process.env.SESSION_SECRET!,
refresh: async ({ refreshToken, signal }) => {
const response = await fetch(`${API}/auth/refresh`, {
method: "POST",
signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
// DummyJSON rejected the refresh token: sign out.
if (response.status === 401 || response.status === 403) return null;
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return tokens.parse(await response.json());
},
});
/** Signs in with your backend, from the server. */
export async function login(username: string, password: string) {
const response = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
// The backend says why, such as wrong credentials, in `message`.
const failure = z.object({ message: z.string() }).safeParse(body);
throw new Error(
failure.success
? failure.data.message
: `Sign-in failed (${response.status})`,
);
}
return { ...tokens.parse(body), user: userSchema.parse(body) };
}
```
`server-only` comes with Next, so there's nothing to install for it. [Server
sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions) covers the engine's other
options, the cookie, and signing out.
## 2. Read the session in Server Components
`nextSession` from `@monarcode/session-kit/next` gives your app its session
over Next's cookies. Session kit doesn't import `next`, so pass it Next's own
`cookies` and `redirect`. Create it in a server-only module too:
```ts title="lib/auth/session.ts"
import "server-only";
import { nextSession } from "@monarcode/session-kit/next";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { serverAuth } from "./server";
export const session = nextSession(serverAuth, { cookies, redirect });
```
In a Server Component, `await session.get()` resolves `{ sessionId, user }`
or `null`. It holds no tokens, so it's safe to pass to Client Components. It
doesn't set cookies, as Server Components can't, so Proxy refreshes first,
in the next step.
## 3. Refresh in Proxy
Proxy refreshes tokens that are about to expire before any page or Server
Function reads them. `session.refresh(request, response)` sets the new cookie
on the response, and Next passes it on to the Server Components that render
the same request:
```ts title="proxy.ts"
import { NextResponse, type NextRequest } from "next/server";
import { session } from "./lib/auth/session";
export function proxy(request: NextRequest) {
return session.refresh(request, NextResponse.next());
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
```
Here's what to know about the refresh:
- It refreshes tokens that expire within 60 seconds. For tokens that live a
minute or less, pass a smaller `within` to `nextSession`, such as
`nextSession(serverAuth, { cookies, redirect, within: 15 })`.
- If the refresh fails, the page still renders with the cookie as it is.
- Server Functions are `POST` requests to the page that calls them, so keep
the matcher wide enough to include those pages.
[Requests that can't set cookies](https://session-kit.pages.dev/docs/server-rendering/server-sessions#requests-that-cant-set-cookies)
explains why the refresh happens there.
## 4. Add the session route and the sign-in action
The browser's client reads the session and signs out through a session
route: a Route Handler in your app that the browser's client calls.
`sessionRoute` from `@monarcode/session-kit/next` makes its `GET` and `POST`
handlers. Pass it Next's `cookies`:
```ts title="app/api/session/route.ts"
import { sessionRoute } from "@monarcode/session-kit/next";
import { cookies } from "next/headers";
import { serverAuth } from "../../../lib/auth/server";
export const { GET, POST } = sessionRoute(serverAuth, { cookies });
```
The session route answers your own site's pages only, so another site can't
sign the user out: see [The session route](https://session-kit.pages.dev/docs/security#the-session-route).
Signing in is yours, as it takes your form's input. A Server Function signs
in with your backend and sets the cookie with `session.signIn`:
```ts title="app/actions.ts"
"use server";
import { z } from "zod";
import { login } from "../lib/auth/server";
import { session } from "../lib/auth/session";
const credentials = z.object({ username: z.string(), password: z.string() });
export async function signInAction(input: unknown) {
const { username, password } = credentials.parse(input);
try {
const tokens = await login(username, password);
return { session: await session.signIn(tokens) };
} catch (error) {
return {
error: error instanceof Error ? error.message : "Sign-in failed",
};
}
}
```
`signInAction` returns its failure rather than throwing it, as Next advises
for expected errors. In production, Next hides a thrown error's message from
the browser.
## 5. Create the browser client
`createMirrorAuth` makes the client that Client Components use, from the
session the layout read, the session route and your sign-in action:
```ts title="lib/auth/client.ts"
import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit";
import { signInAction } from "../../app/actions";
// Types only: left out of the browser's bundle.
import type { serverAuth } from "./server";
export type AppSession = SessionOf;
export function createAppAuth(session: AppSession | null) {
return createMirrorAuth({
name: "app",
session,
endpoint: "/api/session",
signIn: async (input: { username: string; password: string }) => {
const result = await signInAction(input);
if ("error" in result) throw new Error(result.error);
return result.session;
},
});
}
export type AppAuth = ReturnType;
```
`useMirrorAuth` from `@monarcode/session-kit/react` creates the client in a
Client Component, once per request on the server, never at module level. It
keeps the client and the server in step both ways. When the session changes
in the browser, it calls `onChange`, here `router.refresh()`, which renders
the Server Components again. Register the client's type where you render
`AuthProvider`, so the hooks carry your user:
```tsx title="app/providers.tsx"
"use client";
import type { ReactNode } from "react";
import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react";
import { useRouter } from "next/navigation";
import {
createAppAuth,
type AppAuth,
type AppSession,
} from "../lib/auth/client";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: AppAuth;
}
}
export function Providers(props: {
session: AppSession | null;
children: ReactNode;
}) {
const router = useRouter();
const auth = useMirrorAuth({
create: createAppAuth,
session: props.session,
onChange: () => router.refresh(),
});
return {props.children};
}
```
Render the providers in the root layout, with the session it reads:
```tsx title="app/layout.tsx"
import type { ReactNode } from "react";
import { session } from "../lib/auth/session";
import { Providers } from "./providers";
export default async function RootLayout(props: { children: ReactNode }) {
const current = await session.get();
return (
{props.children}
);
}
```
## 6. Protect pages
Check the session in each page with `session.require`, rather than in a
layout, because layouts don't render again on navigation. A Server Component
can't read its own URL, so `require` takes the page's path, where the sign-in
page sends the user back:
```tsx title="app/page.tsx"
import { session } from "../lib/auth/session";
export default async function Home() {
const { user } = await session.require("/");
return
Welcome, {user.firstName}
;
}
```
A signed-out user who opens `/orders` lands on `/login?redirectTo=%2Forders`.
To use another sign-in path, pass `loginPath` to `nextSession`.
## 7. Sign in
The sign-in page sends a user who is already signed in on to `redirectTo`,
with `session.redirectIfSignedIn`:
```tsx title="app/login/page.tsx"
import { session } from "../../lib/auth/session";
import { SignInForm } from "./sign-in-form";
export default async function Login({
searchParams,
}: {
searchParams: Promise>;
}) {
await session.redirectIfSignedIn((await searchParams).redirectTo);
return ;
}
```
The form is a Client Component that calls the client's `signIn`:
```tsx title="app/login/sign-in-form.tsx"
"use client";
import { useState, type FormEvent } from "react";
import { useAuthClient } from "@monarcode/session-kit/react";
export function SignInForm() {
const auth = useAuthClient();
const [error, setError] = useState("");
async function submit(event: FormEvent) {
event.preventDefault();
const form = new FormData(event.currentTarget);
try {
await auth.signIn({
username: String(form.get("username")),
password: String(form.get("password")),
});
} catch (failure) {
// What the client's signIn option threw, from signInAction's error.
setError(failure instanceof Error ? failure.message : "Sign-in failed");
}
}
return (
);
}
```
The form doesn't navigate after a sign-in. The session changed in the
browser, so `useMirrorAuth` renders the page again on the server, and
`redirectIfSignedIn` sends the user on. To try it, sign in as `emilys` with
the password `emilyspass`.
In this guide, the server signs in with your backend, so the user in the
cookie comes from the backend. If the browser has to sign in with the backend
itself, have `signInAction` take the tokens instead:
[Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid) shows how.
## 8. Sign out
The client's `signOut()` signs out on the server through the session route,
which clears the cookie and calls your `revoke` option, if `createServerAuth`
has one. It then signs out this tab and tells the others. `useMirrorAuth`
calls `router.refresh()`, so `session.require` sends the user to the sign-in
page. Put a button like this one on any protected page:
```tsx title="app/sign-out-button.tsx"
"use client";
import { useAuthClient } from "@monarcode/session-kit/react";
export function SignOutButton() {
const auth = useAuthClient();
// A failed sign-out keeps the session, and shows in `state.error`.
return (
);
}
```
Without `revoke`, a copy of the cookie made before sign-out still works: see
[Sign-out](https://session-kit.pages.dev/docs/server-rendering/server-sessions#sign-out).
## Call your API
Your server code calls your API with `createAuthFetch` from
`@monarcode/session-kit/http`, which sends the request's access token to your
API's origin only. In a Server Component, pass it `session.readOnly()`, the
request's session that doesn't set cookies:
```tsx title="app/orders/page.tsx"
import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";
import { API } from "../../lib/auth/server";
import { session } from "../../lib/auth/session";
const orders = z.object({ carts: z.array(z.object({ id: z.number() })) });
export default async function Orders() {
const { user } = await session.require("/orders");
const authFetch = createAuthFetch(await session.readOnly(), {
baseUrl: `${API}/`,
});
const response = await authFetch(`auth/carts/user/${user.id}`);
if (!response.ok) throw new Error(`Orders failed (${response.status})`);
const { carts } = orders.parse(await response.json());
return
{carts.length} orders
;
}
```
Proxy refreshed the token before the render. A token that expired anyway
rejects with `REFRESH_FAILED`, and so does a 401 from your API, since a
Server Component can't save a new token: see
[Requests that can't set cookies](https://session-kit.pages.dev/docs/server-rendering/server-sessions#requests-that-cant-set-cookies).
In Server Functions and Route Handlers, pass `await session.writable()`
instead, the request's session that can set cookies. When your API answers
401 there, `authFetch` gets a new access token and saves it in the cookie. It
sends a `GET` or `HEAD` again with the new token, as
[After a 401](https://session-kit.pages.dev/docs/client/requests#after-a-401) explains.
With an HTTP client of your own, such as ky or axios, see
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients). A client without a
`fetch` option reads the token with `credentials.get()` on
`await session.readOnly()` or `await session.writable()`.
To call your API from the browser too, turn on `clientCredentials` in
`createServerAuth`: see
[The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser).
The example app does this.
## Things to know
- **Writes only where Next allows them.** Use `signIn`, `signOut`,
`updateUser` and `writable()` in Server Functions and Route Handlers only.
In a Server Component they can't set the cookie, and `writable()` would
refresh and then fail to save the new tokens, which spends a rotating
refresh token.
- **One read per request.** Calls to `session` during one request read the
cookie once, and a sign-in through `signIn` shows in `get()`.
- **Separate instances.** Next builds Proxy, Route Handlers, and pages with
their Server Functions separately, so each has its own `serverAuth`, even
on one server. They share no refresh. A matcher that covers every route
that reads the session lets Proxy refresh first, so Route Handlers and
Server Functions rarely need to.
- **A `basePath`.** Next doesn't add it to `fetch`, so the client's
`endpoint` includes it: `"/app/api/session"`. Nor does Next add it to a
Route Handler's redirects, so a Route Handler reads the session with `get`
and answers 401, rather than calling `require`.
- **Rendering.** Reading cookies makes a page dynamic, and the root layout
reads the session, so every page is dynamic. Next sends such pages with
`Cache-Control: no-store`, and plain `use cache` can't read cookies.
- **The Node.js runtime.** Keep pages that read the session on the Node.js
runtime, the default. Next might not pass Proxy's refreshed cookie on to
Edge runtime pages.
- **Other tabs.** Signing in or out in one tab reaches the others, which ask
the server for the session and render their pages again: see
[How tabs stay in step](https://session-kit.pages.dev/docs/server-rendering#how-tabs-stay-in-step).
- **Deploying.** Several server instances, the cookie's size, and plain http
during development are covered in
[Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions).
## Next steps
- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): the cookie, the
secret, signing out, and the limits every server-rendered setup shares.
- [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid): sign in from the browser
and call your API there, with the session still on the server.
- [Using the client](https://session-kit.pages.dev/docs/client): what the browser's client can do.
- [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run Effects with a
request's session.
# Expo Router (https://session-kit.pages.dev/docs/setups/expo)
People who open your Expo app expect to find themselves still signed in, to
land on the screen a link points to, and not to see the sign-in screen flash
past while the app starts. In this guide, you build an Expo Router app for
iOS and Android that does that. It saves the session in the device's secure
storage, holds the splash screen while the session restores, and keeps a
deep link across sign-in.
The app is a shorter version of the
[`expo-router` example app](https://github.com/monarcode/session-kit/tree/main/examples/expo-router).
It signs in against [DummyJSON's auth API](https://dummyjson.com/docs/auth),
so it runs as written. The example adds a few extras, such as one-minute
tokens so you can watch a refresh, and its links use the scheme `sessionkit`
where this page uses `myapp`. Its `src/auth.ts` takes the place of Getting
started's `backend.ts` and `auth.ts`.
This page covers what differs on Expo. [Using the client](https://session-kit.pages.dev/docs/client),
[Refresh](https://session-kit.pages.dev/docs/configuration/refresh) and
[Errors](https://session-kit.pages.dev/docs/configuration/errors) explain how the client works.
## Before you begin
- Expo SDK 53 to 58, with the Expo Router and React Native versions that come
with your SDK. [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) lists the
versions.
- An app for iOS and Android. Expo web isn't supported. On the web, use a
[web router setup](https://session-kit.pages.dev/docs/installation#pick-your-setup) with `webStorage()`.
- Expo Go, which includes `expo-secure-store` and `expo-file-system`, or a
development build with both installed.
## Installation
Install the package, its Expo peers, the splash screen module and a schema
library. `npx expo install` picks the versions that match your SDK:
```sh
npx expo install @monarcode/session-kit expo-secure-store \
expo-file-system expo-splash-screen zod
```
An Expo Router app already has `expo-router` and `react-native`.
`expo-splash-screen` is what holds the splash screen. Without it, holding
does nothing, and the app shows while the session is still restoring.
Then add the `expo-secure-store` config plugin to `app.json`. It keeps the
session out of Android's Auto Backup, and adds the Face ID permission on
iOS:
```json
{
"expo": {
"scheme": "myapp",
"plugins": ["expo-router", "expo-secure-store"]
}
}
```
`scheme` is what custom-scheme deep links such as `myapp://profile` use.
Expo Go opens its own `exp://` links instead, and doesn't apply config
plugins, so both take effect in a development or release build.
[Reinstalls and Android backups](#reinstalls-and-android-backups) says more
about the backup rules.
## 1. Create the client
`secureStorage()` replaces `webStorage()`. The rest of the client is the same
as on the web:
```ts title="src/auth.ts"
import { createAuth } from "@monarcode/session-kit";
import { secureStorage } from "@monarcode/session-kit/expo";
import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";
const API = "https://dummyjson.com";
export const userSchema = z.object({
id: z.number(),
username: z.string(),
email: z.string(),
firstName: z.string(),
});
const tokensSchema = z.object({
accessToken: z.string(),
refreshToken: z.string(),
});
const loginResponseSchema = tokensSchema.extend(userSchema.shape);
export const auth = createAuth({
name: "my-app",
user: userSchema,
storage: secureStorage(),
// Logs what Session kit does to Metro, in development only.
debug: __DEV__,
refresh: async ({ refreshToken, signal }) => {
const response = await fetch(`${API}/auth/refresh`, {
method: "POST",
signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
// DummyJSON answers 401 or 403 when the refresh token is no good.
if (response.status === 401 || response.status === 403) return null;
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return tokensSchema.parse(await response.json());
},
});
export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
export async function signInWithPassword(username: string, password: string) {
const response = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (!response.ok) throw new Error(`Sign-in failed (${response.status})`);
const { accessToken, refreshToken, ...user } = loginResponseSchema.parse(
await response.json(),
);
await auth.signIn({ accessToken, refreshToken, user });
}
```
[Turn on debug logs](#debugging) says what `debug` adds on Expo.
## 2. Add the unavailable screen
Sometimes there's a saved session that can't be used: a refresh failed,
often because the device is offline, or the keychain couldn't be read. Access
is then `unavailable`, and the gate you add in the next step shows this
screen in place of the app. It receives the error and a `retry` function:
```tsx title="src/unavailable.tsx"
import { Button, Text, View } from "react-native";
import type { UnavailableProps } from "@monarcode/session-kit/expo";
import { auth } from "./auth";
export function Unavailable({ error, retry }: UnavailableProps) {
return (
Can't reach your account{error?.message ?? "Check your connection and try again."}
{/* Works offline: it clears the session on this device. */}
);
}
```
Without an `unavailable` screen, the gate hides the splash screen and throws
the error to the root layout's `ErrorBoundary` instead. That boundary's
`retry` only renders again, so have it call `auth.retry()` too, as
[`SessionGateProps`](https://session-kit.pages.dev/docs/reference/expo#sessiongateprops) explains.
## 3. Gate the root layout
`SessionGate` goes inside `AuthProvider`, around the root navigator. Guard the
screens with `Stack.Protected`: signed-in users see the `(app)` group, and
everyone else sees `login`. Register the client's type here too, so the hooks
from `@monarcode/session-kit/react` carry your user:
```tsx title="app/_layout.tsx"
import { isSignedIn } from "@monarcode/session-kit";
import { SessionGate } from "@monarcode/session-kit/expo";
import { AuthProvider, useAuth } from "@monarcode/session-kit/react";
import { SplashScreen, Stack } from "expo-router";
import { auth } from "../src/auth";
import { Unavailable } from "../src/unavailable";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
// Keeps the splash screen up until SessionGate hides it.
void SplashScreen.preventAutoHideAsync();
export default function RootLayout() {
return (
}>
);
}
function RootStack() {
// Not signed in while locked, though a locked session keeps its user.
const signedIn = useAuth(isSignedIn);
return (
);
}
```
`RootStack` is its own component so that `useAuth` runs inside
`AuthProvider`. `SessionGate` mounts the navigator only after the session is
restored, so the guards never see `initializing`.
If the first screen needs more than the session, such as fonts, pass `ready`
as well. The splash screen then stays up until both are done. Count a failed
load as done, or the splash screen never hides: with Expo Font's `useFonts`,
pass `ready={fontsLoaded || fontError !== null}`.
[`SessionGateProps`](https://session-kit.pages.dev/docs/reference/expo#sessiongateprops) describes `ready`.
## 4. Keep deep links
`Stack.Protected` sends a link to a guarded screen to the first screen the
user may see. So a signed-out user who opens `myapp://profile` lands on the
sign-in screen, and the link is lost. `deepLinkHandler` keeps the link, and
`SessionGate` opens it after the sign-in. Expo Router calls
`redirectSystemPath` with every URL that opens the app, before routing:
```tsx title="app/+native-intent.tsx"
import { deepLinkHandler } from "@monarcode/session-kit/expo";
import { auth } from "../src/auth";
export const redirectSystemPath = deepLinkHandler(auth);
```
It returns the path unchanged, so the link still goes to Expo Router, which
shows it right away when the user is signed in. If your `redirectSystemPath`
does more, such as rewriting old links, call `rememberDeepLink(auth, path)`
in it instead. [How deep links are kept](#how-deep-links-are-kept) has the
rules.
## 5. Add the sign-in screen
The sign-in screen calls `signInWithPassword` from `src/auth.ts`:
```tsx title="app/login.tsx"
import { useState } from "react";
import { Button, Text, TextInput, View } from "react-native";
import { signInWithPassword } from "../src/auth";
export default function Login() {
// DummyJSON's documented test user.
const [username, setUsername] = useState("emilys");
const [password, setPassword] = useState("emilyspass");
const [error, setError] = useState("");
async function submit() {
setError("");
try {
await signInWithPassword(username, password);
// No navigation: Stack.Protected leaves this screen, and
// SessionGate opens the deep link the user was headed to.
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
}
}
return (
{error ? {error} : null}
);
}
```
The guards already decide where a signed-in user belongs, so the screen
doesn't navigate after `signIn`. After the user signs in, `Stack.Protected`
removes the sign-in screen. A `router.replace` of your own would race the
deep link that `SessionGate` opens.
## 6. Add the signed-in screens
Screens inside the guarded group read the user with `useAuth`. They call the
API with `authFetch`, which adds the access token and refreshes after a 401.
To use axios or another HTTP client instead, see
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients). The group's layout is a
plain stack:
```tsx title="app/(app)/_layout.tsx"
import { Stack } from "expo-router";
export default function AppLayout() {
return ;
}
```
Its first screen shows the user's name, links to the profile, and signs out:
```tsx title="app/(app)/index.tsx"
import { Button, Text, View } from "react-native";
import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
import { Link } from "expo-router";
export default function Home() {
const firstName = useAuth((state) => state.user?.firstName);
const auth = useAuthClient();
return (
Welcome, {firstName}
Profile
{/* No navigation: Stack.Protected then shows the sign-in screen. */}
);
}
```
The profile screen fetches the user from the API. It's also where a deep
link such as `myapp://profile` goes:
```tsx title="app/(app)/profile.tsx"
import { useEffect, useState } from "react";
import { Text, View } from "react-native";
import { z } from "zod";
import { authFetch, userSchema } from "../../src/auth";
const profileSchema = userSchema.extend({
lastName: z.string(),
gender: z.string(),
});
export default function Profile() {
const [profile, setProfile] = useState>();
const [error, setError] = useState("");
useEffect(function loadProfile() {
const controller = new AbortController();
authFetch("auth/me", { signal: controller.signal })
.then(async (response) => {
if (!response.ok)
throw new Error(`Profile failed (${response.status})`);
setProfile(profileSchema.parse(await response.json()));
})
.catch((cause: unknown) => {
if (controller.signal.aborted) return;
setError(cause instanceof Error ? cause.message : "Could not load");
});
return function cancelLoad() {
controller.abort();
};
}, []);
if (error) return {error};
if (!profile) return Loading…;
return (
{profile.firstName} {profile.lastName}
{profile.email}{profile.gender}
);
}
```
## 7. Check the app
Run the app, and check each part of the session:
1. Sign in. The home screen shows your name. Open the profile to see your
email.
2. Close the app and open it again. The splash screen stays up until the
session is restored, then the home screen shows.
3. Sign out. The sign-in screen shows.
4. While signed out, open `myapp://profile`. On the iOS Simulator, run
`xcrun simctl openurl booted myapp://profile`. In Expo Go, open
`exp://HOST:8081/--/profile` instead, and replace `HOST` with the address
Expo CLI prints for Metro. Sign in. The profile screen opens.
That's the whole app. The rest of this page explains what `secureStorage()`,
`SessionGate` and the deep link handler do on the device.
## Secure storage
[`secureStorage()`](https://session-kit.pages.dev/docs/reference/expo#securestorage) saves the session
with `expo-secure-store`: in the iOS keychain, and in storage encrypted with
an Android Keystore key on Android. A session too large for one SecureStore
value is split across several keys, up to 128 KB, as its reference explains.
Its options are in
[`SecureStorageOptions`](https://session-kit.pages.dev/docs/reference/expo#securestorageoptions).
### Reinstalls and Android backups
iOS keeps keychain items after the app is deleted. So by default,
`secureStorage()` removes a session that an earlier install left, and a
reinstalled app starts signed out. To restore that session instead, pass
`secureStorage({ clearOnReinstall: false })`.
On Android, Auto Backup can restore the app's data onto another device. The
session can't be decrypted there, so the app starts signed out, and the
unreadable session is removed. The `expo-secure-store` config plugin from
[Installation](#installation) keeps the session out of backups, with two
conditions:
- It applies in a development or release build. Expo Go doesn't apply config
plugins.
- If your app already has its own backup rules, the plugin leaves them as
they are and prints a warning. Exclude SecureStore's data in your rules
yourself, as
[Expo's SecureStore docs](https://docs.expo.dev/versions/latest/sdk/securestore/)
explain.
### Keychain access on iOS
By default, iOS lets the app read the keychain only while the device is
unlocked. What happens when the keychain is locked depends on what's
reading it:
- **When the app starts**, a keychain that can't be read leaves the session
`unavailable`, not signed out. `SessionGate` tries again when the app
returns to the foreground.
- **When a refresh runs**, it can't save the new tokens to a locked keychain,
and that signs the user out.
An app that refreshes in a background task while the device is locked needs
`secureStorage({ keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK })`,
with `SecureStore` imported from `expo-secure-store`.
## What SessionGate does
[`SessionGate`](https://session-kit.pages.dev/docs/reference/expo#sessiongate) adds what `Stack.Protected`
lacks:
- It holds the splash screen while the session is restored, and until
`ready`.
- It shows `unavailable` when access can't be used.
- It checks the session again when the app returns to the foreground, since
timers don't run while iOS suspends the app.
- It opens the deep link kept for after the sign-in.
While the session is locked, it renders the navigator, so your guards can
show an unlock screen. When one account replaces another without a sign-out
between them, it remounts the navigator, so no screen keeps the previous
account's state.
## How deep links are kept
[`deepLinkHandler`](https://session-kit.pages.dev/docs/reference/expo#deeplinkhandler) keeps one link at a
time, and `SessionGate` opens it after the next sign-in or unlock. Some links
aren't kept, or are dropped before then:
- A link to the root or the sign-in screen is ignored, as is one that could
leave the app.
- A link that arrives while the user is signed in is dropped, since Expo
Router opens it as usual.
- A link to a screen anyone may see is dropped when that screen shows. If the
app launched with such a link, it's dropped at the sign-in instead,
unopened.
If your sign-in screen isn't `/login`, pass
`deepLinkHandler(auth, { loginPath: "/sign-in" })`.
Where `Stack.Protected` takes a `redirectTo`, as in Expo SDK 58, it only
chooses the screen a turned-away link goes to, such as `/login`. It doesn't
keep the link, so `deepLinkHandler` is still what opens it after the
sign-in.
There's no `?redirectTo=` parameter on Expo. The link waits in memory, not in
the URL, and an app restart forgets it.
## Turn on debug logs
The client in [step 1](#1-create-the-client) sets `debug: __DEV__`, so in
development the app logs what Session kit does to Metro. `SessionGate` and the
deep link handler report through the same option. They log why the splash
screen is held (restoring, or waiting for `ready`), when it hides, and what
happened to a remembered link. `secureStorage()` adds what only it can see,
such as removing a session an earlier install left.
[Debugging](https://session-kit.pages.dev/docs/configuration/debugging) covers what the logs leave out,
and how to send them somewhere other than the console.
## Locking
A returning user can be asked to unlock before the app opens: a "Welcome
back" screen with Face ID, Touch ID or a fingerprint, and the password as a
fallback. [Unlock with biometrics](https://session-kit.pages.dev/docs/setups/expo-locking) adds that to
this guide's app, step by step. [Locking](https://session-kit.pages.dev/docs/client/locking) explains how
a locked session behaves.
## Not supported
- **Expo web.** `secureStorage()` and `SessionGate` are for iOS and Android.
- **`requireAuthentication`.** `secureStorage()` doesn't use SecureStore's
biometric prompt. A session that refreshes on its own can't ask for a face
or fingerprint on every read and write. Keep a key behind the prompt
instead, and seal the session with it, as
[Unlock with biometrics](https://session-kit.pages.dev/docs/setups/expo-locking) shows.
- **Network status.** Session kit doesn't watch connectivity. When your app
learns the device is back online, for example from
`@react-native-community/netinfo`, call `auth.retry()`, or the `retry` that
`unavailable` receives.
## Next steps
- [Unlock with biometrics](https://session-kit.pages.dev/docs/setups/expo-locking): ask a returning user
for Face ID or a fingerprint before the app opens.
- [Using the client](https://session-kit.pages.dev/docs/client): update the user, sign out, and the
client's other methods.
- [Expo reference](https://session-kit.pages.dev/docs/reference/expo): every option of `secureStorage`,
`SessionGate` and the deep link handler.
- [Effect and effetch](https://session-kit.pages.dev/docs/effect): the same client as an Effect service.
# Unlock with biometrics (https://session-kit.pages.dev/docs/setups/expo-locking)
A saved session keeps your app signed in for weeks, so anyone who picks up
the unlocked phone can open it. Some apps ask the returning user to confirm
it's them first: a "Welcome back" screen with Face ID, Touch ID or a
fingerprint, and the password as a fallback.
This page adds that screen to the app from the
[Expo Router guide](https://session-kit.pages.dev/docs/setups/expo). With the client's `locking` option, a
saved session restores as `locked`. The app can greet the user by name, but
the tokens stay sealed until the user unlocks them.
[Locking](https://session-kit.pages.dev/docs/client/locking) explains how a locked session behaves. This
page is the Expo side.
Here's how the pieces fit together. A random key is kept in a SecureStore
item that needs biometrics to read, so reading it shows the biometric prompt.
The client seals the tokens with that key, using AES-GCM, each time it saves
them, and opens them when the user unlocks.
## Before you begin
- The app from the [Expo Router guide](https://session-kit.pages.dev/docs/setups/expo), with the
`expo-secure-store` config plugin in `app.json`. On iOS, the plugin adds
the Face ID permission that the prompt needs.
- A development build on a real device. Expo Go doesn't support SecureStore's
biometric prompt where biometrics are available, and simulators don't ask for
biometrics.
## 1. Install the packages
This page makes the key with `expo-crypto`, and seals the tokens with
`@noble/ciphers`. They're your app's dependencies, not Session kit's:
```sh
npx expo install expo-crypto @noble/ciphers
```
## 2. Keep a key behind biometrics
This file makes the key, saves it behind the device's biometrics, reads it
back to unlock, and seals the tokens with it:
```ts title="src/session-key.ts"
import { Platform } from "react-native";
import type { AuthLocking } from "@monarcode/session-kit";
import { gcm } from "@noble/ciphers/aes.js";
import {
bytesToHex,
bytesToUtf8,
hexToBytes,
utf8ToBytes,
} from "@noble/ciphers/utils.js";
import { getRandomBytes } from "expo-crypto";
import * as SecureStore from "expo-secure-store";
const KEY_ITEM = "session-key";
// Whether the key was saved behind biometrics, so it's read the same way.
const BIOMETRIC_ITEM = "session-key-biometric";
function keyOptions(biometric: boolean): SecureStore.SecureStoreOptions {
return biometric
? {
requireAuthentication: true,
authenticationPrompt: "Unlock your account",
}
: {};
}
// In memory from an unlock or a password sign-in until the app locks.
let key: Uint8Array | undefined;
/**
* Saves the key behind the device's biometrics, or, on a device with none
* enrolled, without them. On Android, saving shows the prompt.
*/
async function saveKey(next: Uint8Array): Promise {
const biometric = SecureStore.canUseBiometricAuthentication();
// On iOS, replacing an item that needs biometrics shows the prompt, and
// saving a new one doesn't. So a password sign-in asks for nothing more.
await SecureStore.deleteItemAsync(KEY_ITEM);
await SecureStore.setItemAsync(
KEY_ITEM,
bytesToHex(next),
keyOptions(biometric),
);
await SecureStore.setItemAsync(BIOMETRIC_ITEM, String(biometric));
}
/**
* Reads the key, which shows the prompt when it needs biometrics. Resolves
* `null` when no key was saved yet.
*/
async function readKey(): Promise {
const biometric = await SecureStore.getItemAsync(BIOMETRIC_ITEM);
if (biometric === null) return null;
const saved = await SecureStore.getItemAsync(
KEY_ITEM,
keyOptions(biometric === "true"),
);
// SecureStore reads `null` for a key that a change to the device's
// biometrics made unreadable.
if (saved === null) throw new Error("The session key can't be read");
return saved;
}
/**
* Loads the key to unlock. Throws when the user cancels the prompt, or when
* the device's biometrics changed and the key can't be read.
*/
export async function loadKey(): Promise {
const saved = await readKey();
if (saved) {
key = hexToBytes(saved);
return;
}
// A session saved before locking was added has no key yet. Make one: on
// iOS, saving doesn't prompt, so read it back to show the prompt.
const next = getRandomBytes(32);
await saveKey(next);
if (Platform.OS === "ios") await readKey();
key = next;
}
/**
* Signs in with a new key, and saves it only after the sign-in succeeds: a
* failed sign-in keeps the key that the saved session is sealed with.
*/
export async function withNewKey(signIn: () => Promise): Promise {
const previous = key;
const next = getRandomBytes(32);
key = next;
let result: T;
try {
result = await signIn();
} catch (error) {
if (key === next) key = previous;
throw error;
}
try {
await saveKey(next);
} catch (error) {
// The session works until the app closes; then the password unlocks it.
console.warn("Could not save the session key", error);
}
return result;
}
/** Forgets the key in memory, after `auth.lock()` has settled. */
export function dropKey(): void {
key = undefined;
}
function loadedKey(): Uint8Array {
if (!key) throw new Error("The session key isn't loaded");
return key;
}
/** AES-256-GCM: a random 12-byte nonce, then the ciphertext, as hex. */
export const sessionLocking: AuthLocking = {
seal(payload) {
const nonce = getRandomBytes(12);
const sealed = gcm(loadedKey(), nonce).encrypt(utf8ToBytes(payload));
return bytesToHex(nonce) + bytesToHex(sealed);
},
open(sealed) {
const bytes = hexToBytes(sealed);
const nonce = bytes.subarray(0, 12);
return bytesToUtf8(gcm(loadedKey(), nonce).decrypt(bytes.subarray(12)));
},
};
```
The rest of the app uses four of its exports:
- `loadKey()` reads the key before an unlock, which shows the prompt.
- `withNewKey()` wraps a password sign-in, so the new session is sealed with
a new key.
- `dropKey()` forgets the key when the app locks or signs out.
- `sessionLocking` is the client's `locking` option.
A device with no biometrics enrolled can't save an item that needs them. So
on those devices the key is saved without them, and unlocking asks for
nothing beyond the device's own lock screen. If your app needs more there,
sign out instead of locking.
Users who signed in before you added locking need no migration. Their saved
session restores as `locked` too, and has no key yet, so `loadKey()` makes
one at their first unlock.
## 3. Seal the session with the key
Pass `sessionLocking` to the client as `locking`. Then sign in through
`withNewKey()`, and add a `signOut()` that forgets the key. The changed lines
are marked:
```ts title="src/auth.ts"
import { createAuth } from "@monarcode/session-kit";
import { secureStorage } from "@monarcode/session-kit/expo";
import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";
import { dropKey, sessionLocking, withNewKey } from "./session-key";
const API = "https://dummyjson.com";
export const userSchema = z.object({
id: z.number(),
username: z.string(),
email: z.string(),
firstName: z.string(),
});
const tokensSchema = z.object({
accessToken: z.string(),
refreshToken: z.string(),
});
const loginResponseSchema = tokensSchema.extend(userSchema.shape);
export const auth = createAuth({
name: "my-app",
user: userSchema,
storage: secureStorage(),
debug: __DEV__,
// Changed: seals the saved tokens with the key.
locking: sessionLocking,
refresh: async ({ refreshToken, signal }) => {
const response = await fetch(`${API}/auth/refresh`, {
method: "POST",
signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
// DummyJSON answers 401 or 403 when the refresh token is no good.
if (response.status === 401 || response.status === 403) return null;
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return tokensSchema.parse(await response.json());
},
});
export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
export async function signInWithPassword(username: string, password: string) {
const response = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (!response.ok) throw new Error(`Sign-in failed (${response.status})`);
const { accessToken, refreshToken, ...user } = loginResponseSchema.parse(
await response.json(),
);
// Changed: the new session is sealed with a new key.
await withNewKey(() => auth.signIn({ accessToken, refreshToken, user }));
}
/** Changed: signs out, and forgets the key. It works offline. */
export async function signOut(): Promise {
await auth.signOut().catch(() => {});
dropKey();
}
```
Saving a session seals it, a sign-in's too, and `seal` throws while no key
is loaded. That's why every sign-in goes through `withNewKey()`. Without a
key, the sign-in would fail with `PERSISTENCE_FAILED`.
## 4. Guard the unlock screen
A locked session isn't signed in, but it keeps its user. So the stack needs
a third screen, and a guard for each state that's true in that state only:
```tsx title="app/_layout.tsx"
import { isSignedIn } from "@monarcode/session-kit";
import { SessionGate } from "@monarcode/session-kit/expo";
import { AuthProvider, useAuth } from "@monarcode/session-kit/react";
import { SplashScreen, Stack } from "expo-router";
import { auth } from "../src/auth";
import { Unavailable } from "../src/unavailable";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
// Keeps the splash screen up until SessionGate hides it.
void SplashScreen.preventAutoHideAsync();
export default function RootLayout() {
return (
}>
);
}
function RootStack() {
const signedIn = useAuth(isSignedIn);
const locked = useAuth((state) => state.status === "locked");
return (
{/* Not while locked, so a locked app opens on welcome-back. */}
);
}
```
Each state needs exactly one screen open to it. When a guard turns the user
away, Expo Router sends them to the first screen they may see, in its own
order of routes, not in the order of your JSX. If the sign-in screen were
open to a locked user too, a locked app could open on it rather than on the
welcome-back screen.
## 5. Add the welcome-back screen
The welcome-back screen greets the user, reads the key, which shows the
biometric prompt, and unlocks. A user who can't unlock signs in with their
password on the same screen:
```tsx title="app/welcome-back.tsx"
import { useState } from "react";
import { Button, Text, View } from "react-native";
import { useAuth } from "@monarcode/session-kit/react";
import { auth } from "../src/auth";
import { loadKey } from "../src/session-key";
import Login from "./login";
export default function WelcomeBack() {
const name = useAuth((state) => state.user?.firstName);
const [failed, setFailed] = useState(false);
const [withPassword, setWithPassword] = useState(false);
async function unlock() {
setFailed(false);
try {
await loadKey();
await auth.unlock();
// No navigation: Stack.Protected leaves this screen, and
// SessionGate opens the deep link the user was headed to.
} catch {
// Cancelled, or the biometrics changed: offer the password. A refresh
// that failed after unlocking leaves the session `unavailable`, which
// SessionGate shows instead.
if (auth.state.get().status === "locked") setFailed(true);
}
}
// The sign-in form. Signing in replaces the locked session.
if (withPassword) return ;
return (
Welcome back{name ? `, ${name}` : ""}
);
}
```
A password sign-in works while the session is locked, and replaces it. It
goes through `withNewKey()`, so the new session gets a new key. A failed
unlock doesn't always leave the session locked, which is why the screen
checks `status` after a rejection.
[Locking](https://session-kit.pages.dev/docs/client/locking) explains both.
## 6. Forget the key on sign-out
After a sign-out, nothing needs the key. Both Sign out buttons call the
`signOut()` from `src/auth.ts`, which forgets it. On the home screen:
```tsx title="app/(app)/index.tsx"
import { Button, Text, View } from "react-native";
import { useAuth } from "@monarcode/session-kit/react";
import { Link } from "expo-router";
import { signOut } from "../../src/auth";
export default function Home() {
const firstName = useAuth((state) => state.user?.firstName);
return (
Welcome, {firstName}
Profile
{/* No navigation: Stack.Protected then shows the sign-in screen. */}
void signOut()} />
);
}
```
And on the unavailable screen:
```tsx title="src/unavailable.tsx"
import { Button, Text, View } from "react-native";
import type { UnavailableProps } from "@monarcode/session-kit/expo";
import { signOut } from "./auth";
export function Unavailable({ error, retry }: UnavailableProps) {
return (
Can't reach your account{error?.message ?? "Check your connection and try again."} void signOut()} />
);
}
```
## 7. Lock after time in the background
To ask again after the app has been away for a while, lock it when it
returns to the foreground, then forget the key:
```ts title="src/auto-lock.ts"
import { AppState } from "react-native";
import { auth } from "./auth";
import { dropKey } from "./session-key";
/** How long the app may stay in the background before it locks. */
const LOCK_AFTER = 5 * 60_000;
/** Locks the session when the app returns after `LOCK_AFTER` away. */
export function watchAutoLock(): () => void {
let backgroundedAt: number | undefined;
const subscription = AppState.addEventListener("change", (next) => {
if (next === "background") backgroundedAt = Date.now();
else if (next === "active" && backgroundedAt !== undefined) {
if (Date.now() - backgroundedAt > LOCK_AFTER)
void auth.lock().then(() => {
// An unlock or sign-in can land before the lock finishes.
if (auth.state.get().status === "locked") dropKey();
});
backgroundedAt = undefined;
}
});
return function stopAutoLock() {
subscription.remove();
};
}
```
`lock()` locks at once, and resolves after a refresh that's still running
has saved its tokens. That save seals them with the key, so `dropKey()` waits
for it. If the user unlocks or signs in before then, the session isn't locked
any more, and the key stays for the next save.
Start the watcher in the signed-in group's layout. That layout is mounted
only while the user is signed in, so the watcher starts after a sign-in or an
unlock, and stops when the app locks or signs out:
```tsx title="app/(app)/_layout.tsx"
import { useEffect } from "react";
import { Stack } from "expo-router";
import { watchAutoLock } from "../../src/auto-lock";
export default function AppLayout() {
useEffect(function lockAfterTimeAway() {
return watchAutoLock();
}, []);
return ;
}
```
While the session is locked, `SessionGate` checks nothing when the app
returns to the foreground. Requests through `authFetch` reject with `LOCKED`
until the user unlocks.
## 8. Check the app
Build the app for a device that has Face ID, Touch ID or a fingerprint set
up, and check each path:
1. Sign in with your password. On Android, saving the key shows the
biometric prompt.
2. Close the app and open it again. The welcome-back screen greets you by
name.
3. Tap **Unlock**, and pass the prompt. The home screen shows.
4. Put the app in the background for more than five minutes, then return to
it. The welcome-back screen shows. To check this sooner, lower
`LOCK_AFTER` while you test.
5. Tap **Use your password**, and sign in. The home screen shows.
6. Close the app, then open `myapp://profile`, for example from a link in
Notes. The welcome-back screen shows. Unlock, and the profile screen
opens.
## Next steps
- [Locking](https://session-kit.pages.dev/docs/client/locking): how a locked session behaves, and which
methods reject while it's locked.
- [Expo Router](https://session-kit.pages.dev/docs/setups/expo): the app this page builds on, and how
`secureStorage()` and `SessionGate` work.
- [`AuthLocking` reference](https://session-kit.pages.dev/docs/reference/core#authlocking): what `seal`
and `open` receive and return.
# Using the client (https://session-kit.pages.dev/docs/client)
Your components read the session with hooks, but some of your code runs
outside React: a route loader, a click handler, the code that calls your API.
That code talks to the client that `createAuth` returned, which these docs
call `auth`.
This section covers the client itself: the methods that code outside React
calls, and two `createAuth` options that change how the client holds the
user, reading it from the access token and locking. The examples build on the
app from [Getting started](https://session-kit.pages.dev/docs/getting-started), where `auth` is the client
and `authFetch` its `fetch`.
## The client's methods
Here's what each method does:
| Call | What it does |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `auth.state.get()`, `.subscribe()` | Reads the [state](https://session-kit.pages.dev/docs/client/state), or follows its changes. |
| `auth.getSession()` | Resolves who is signed in, or `null`. It reads the saved session first if needed, and refreshes an access token that expired. |
| `auth.signIn({ ...tokens, user })` | Saves a new session, replacing any current one. |
| `auth.signOut()` | Ends the session and clears the saved one. Other tabs sign out too, when the storage reports changes and `locking` is off. |
| `auth.updateUser(user)` | Replaces the user and keeps the session. A client that reads the user from the access token doesn't have it. |
| `auth.refresh()` | Refreshes now, even while the access token still works. |
| `auth.retry()` | Tries again after a refresh failed. |
| `auth.isCurrent(session)` | Checks whether a session is still the signed-in one. |
| `auth.credentials.get()`, `.renew()`, `.reject()` | Resolves the access token, and replaces it or ends the session after a 401, for code that sends requests. |
| `auth.lock()`, `auth.unlock()` | Locks and unlocks a saved session, with the [`locking`](https://session-kit.pages.dev/docs/client/locking) option. |
| `auth.mount()` | Starts the expiry timers and following other tabs. `AuthProvider`, TanStack Router's `connectAuth`, React Router's `SessionOutlet` and Expo's `SessionGate` call it for you. |
Each method's JSDoc says what it resolves and which `AuthError` it rejects
with, so your editor shows the details where you call it. The
[`AuthClient` reference](https://session-kit.pages.dev/docs/reference/core#authclient) has the same
text.
## With server rendering
When the session lives on the server, the browser's client comes from
`createMirrorAuth` instead. It reads the state and the session the same way,
but it has no `lock`, `unlock` or `updateUser`, and its `signIn` and
`credentials` need options of their own.
[Server rendering](https://session-kit.pages.dev/docs/server-rendering) covers what it can do.
## In this section
Each page covers one job:
- [State](https://session-kit.pages.dev/docs/client/state): Read the state outside React, scope cached data to the session, and know what each field holds.
- [Sessions and credentials](https://session-kit.pages.dev/docs/client/sessions): Ask who is signed in, and keep the access token apart from code that only needs the user.
- [Signing in and out](https://session-kit.pages.dev/docs/client/signing-in-and-out): Save a new session, end it in every tab, and revoke its tokens.
- [Updating the user](https://session-kit.pages.dev/docs/client/updating-the-user): Replace the user without ending the session, and handle each way it can fail.
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): A fetch that sends the access token to one API, and refreshes after a 401.
- [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients): Send the access token with ky, axios, openapi-fetch or any other client.
- [Users from the access token](https://session-kit.pages.dev/docs/client/users-from-tokens): Read the user from a JWT's claims instead of the sign-in response.
- [Locking](https://session-kit.pages.dev/docs/client/locking): Ask a returning user to unlock, for example with biometrics, in native apps.
## Next steps
- [Sessions and credentials](https://session-kit.pages.dev/docs/client/sessions): ask who is signed in
from a loader or an event handler.
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): call your API with the
access token.
- [Configuring the client](https://session-kit.pages.dev/docs/configuration): change how the client saves,
refreshes and reports errors.
# State (https://session-kit.pages.dev/docs/client/state)
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`:
```ts title="src/status-log.ts"
import { auth } from "./auth.js";
/** Logs each change of status. Returns a function that stops it. */
export function logStatus() {
let last = auth.state.get().status;
const { unsubscribe } = auth.state.subscribe(({ status }) => {
if (status === last) return;
last = status;
console.info(`Auth is ${status}`);
});
return unsubscribe;
}
```
`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:
| Field | Holds |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | Where the session stands, such as `authenticated` or `unavailable`. [How it works](https://session-kit.pages.dev/docs#how-it-works) lists each one. |
| `user` | The signed-in user, or `null`. Checking `status` tells TypeScript whether it's set. |
| `sessionId` | The 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. |
| `error` | The latest failure, as an [`AuthError`](https://session-kit.pages.dev/docs/configuration/errors), or `null`. The next successful change clears it. |
| `version` | A 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:
```ts title="src/orders-cache.ts"
import { authFetch } from "./api.js";
import { auth } from "./auth.js";
const cache = new Map>();
// After a sign-out or an account switch, drop the old session's entries.
auth.state.subscribe(({ sessionId }) => {
for (const id of cache.keys()) if (id !== sessionId) cache.delete(id);
});
async function fetchOrders(userId: number): Promise {
const response = await authFetch(`auth/carts/user/${userId}`);
if (!response.ok) throw new Error(`Orders failed (${response.status})`);
return response.json();
}
export async function cachedOrders(): Promise {
const session = await auth.getSession();
if (!session) return null;
let orders = cache.get(session.sessionId);
if (!orders) {
orders = fetchOrders(session.user.id);
cache.set(session.sessionId, orders);
// A failed load isn't kept, so the next call tries again.
orders.catch(() => cache.delete(session.sessionId));
}
return orders;
}
```
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](https://session-kit.pages.dev/docs/setups/tanstack-router) 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](https://session-kit.pages.dev/docs/client/sessions).
## Check `status`, not `user`
`user` is set while the session is `authenticated` or `refreshing`, and also
while it's [locked](https://session-kit.pages.dev/docs/client/locking). 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:
```ts title="src/greeting.ts"
import { isSignedIn } from "@monarcode/session-kit";
import { auth } from "./auth.js";
export function greeting(): string {
const state = auth.state.get();
return isSignedIn(state) ? `Hi, ${state.user.firstName}` : "Please sign in";
}
```
In a component, `useAuth(isSignedIn)` reads the same check.
## Next steps
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show `state.error` to the user, and
know which failures appear there.
- [Sessions and credentials](https://session-kit.pages.dev/docs/client/sessions): ask who is signed in
from a loader, and wait for the saved session to be read.
- [Core reference](https://session-kit.pages.dev/docs/reference/core#authstate): the `AuthState` type and
each status.
# Sessions and credentials (https://session-kit.pages.dev/docs/client/sessions)
A route loader or an event handler often needs to know who is signed in
before it does anything. Reading the state isn't always enough: right after a
reload, the saved session might not have been read yet, and the access token
might have expired. `auth.getSession()` takes care of both, then answers.
This page shows how to ask for the session, what to do when that fails, and
how the access token is kept apart from code that only needs the user.
## Ask who is signed in
A **session** is who is signed in: `{ sessionId, user }`. It holds no tokens,
so it's safe to keep in route context or pass around. Ask for it with
`getSession()`, which resolves `null` when no one is signed in:
```ts title="src/cart.ts"
import { authFetch } from "./api.js";
import { auth } from "./auth.js";
/** A loader: it runs outside React, so it asks the client. */
export async function loadCart(): Promise {
const session = await auth.getSession();
if (!session) return null;
const response = await authFetch(`auth/carts/user/${session.user.id}`);
if (!response.ok) throw new Error(`Cart failed (${response.status})`);
return response.json();
}
```
`getSession()` waits for the saved session to be read. If the access token
has expired, it refreshes it first, or waits for the refresh that's already
running. While the token still works, it answers at once, even if an early
refresh is running in the background.
## When `getSession` rejects
`getSession()` rejects rather than answer with a session it can't vouch for.
Here's when it rejects, and with what:
| When… | `getSession()` rejects with… |
| --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| The saved session can't be read | `PERSISTENCE_FAILED` |
| The access token expired, and the refresh failed | That failure, such as `REFRESH_FAILED`, until a retry, a refresh, new tokens from another tab, or a sign-in or sign-out |
| The session is [locked](https://session-kit.pages.dev/docs/client/locking) | `LOCKED` |
| The session changes while it waits, such as a new sign-in | `SESSION_CHANGED` |
When the refresh of an expired access token fails, the session is
`unavailable`, and `getSession()` rejects with the same failure without
trying again. `auth.retry()` resolves
the session as `getSession()` does, but tries the refresh again first. Use it
for a "Try again" button. [Errors](https://session-kit.pages.dev/docs/configuration/errors) shows how to
present these failures.
## Keep the access token apart
**Credentials** are the access token, with the session it belongs to:
`{ sessionId, accessToken, expiresAt }`. The client keeps them apart from the
session, so code that only needs the user never holds a token.
Most code never reads credentials itself:
- [`createAuthFetch`](https://session-kit.pages.dev/docs/client/requests) reads them for every request.
- An HTTP client that takes `authFetch` as its `fetch` gets them the same
way.
- Code that sends requests another way uses `auth.credentials`, as
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients#clients-without-a-fetch-option)
shows.
## Check the session after slow work
The user can sign out, or switch account in another tab, while your code
waits. `auth.isCurrent(session)` checks whether a session you're holding, or
the credentials a request was sent with, is still the signed-in one. Check it
before you show the result of work that took a while, so one account's
result never appears for another. `authFetch` makes that check for its own
requests.
## Next steps
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): call your API with the
access token, and refresh after a 401.
- [State](https://session-kit.pages.dev/docs/client/state): scope cached data to `sessionId`.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show a failed refresh, and offer
`retry()`.
# Signing in and out (https://session-kit.pages.dev/docs/client/signing-in-and-out)
Your backend signs the user in and answers with tokens. From there, the
client takes over: `auth.signIn` saves the session, and `auth.signOut` ends
it, in this tab and the others. Session kit never checks a password itself.
This page shows what each call does, when it rejects, and how to revoke the
ended tokens on your backend.
## Sign in
Pass `auth.signIn` the tokens your backend issued and the user, as
`signInWithPassword` does in
[Getting started](https://session-kit.pages.dev/docs/getting-started#2-create-the-client):
```ts title="src/switch-account.ts"
import { auth } from "./auth.js";
import { login } from "./backend.js";
/** Signs in as another user, replacing the current session. */
export async function switchAccount(username: string, password: string) {
const { accessToken, refreshToken, user } = await login(username, password);
await auth.signIn({ accessToken, refreshToken, user });
}
```
`signIn` checks the tokens and the user first, then saves the new session in
place of any current one, even a [locked](https://session-kit.pages.dev/docs/client/locking) one. With
[`fromAccessToken`](https://session-kit.pages.dev/docs/client/users-from-tokens), leave out `user`: the
client reads it from the access token. [Expiry](https://session-kit.pages.dev/docs/configuration/expiry)
covers how the client finds out when the access token expires.
`signIn` doesn't navigate. The state changes, and your guards or your
components render from it, so a sign-in page has nothing to do when it
succeeds.
## When `signIn` rejects
A failed check leaves the current session as it was, so a mistake in a
sign-in never signs anyone out. A failed save is different. Here's when
`signIn` rejects, and what happens to the session:
| When… | `signIn` rejects with… | The session afterwards |
| ------------------------------------------------------------------ | ------------------------ | ---------------------- |
| The tokens can't be used, such as an access token that has expired | `INVALID_SESSION` | Unchanged |
| The user schema rejects the user | `USER_VALIDATION_FAILED` | Unchanged |
| Another `signIn` or a `signOut()` starts while it checks the user | `SESSION_CHANGED` | The latest call's |
| The session can't be saved | `PERSISTENCE_FAILED` | Signed out |
The latest call wins: a newer `signIn` or `signOut()` makes a pending sign-in
reject, so an earlier, slower sign-in never replaces a later one.
With a [`locking`](https://session-kit.pages.dev/docs/client/locking) option that has `seal`, every save
seals the tokens. If your `seal` throws, as it does without its key, the save fails with
`PERSISTENCE_FAILED` and no one is signed in.
## Sign out
`auth.signOut()` signs the user out at once, then clears the saved session:
```ts title="src/sign-out.ts"
import { auth } from "./auth.js";
export async function signOutAndLeave() {
// Resolves after `revoke`, if you set it, has finished.
await auth.signOut();
window.location.assign("/login");
}
```
Other tabs that share the storage sign out too, when the storage reports
changes, as `webStorage()` does, and `locking` is off.
[Tabs](https://session-kit.pages.dev/docs/configuration/tabs) explains how tabs follow each other.
If the saved session can't be cleared, `signOut()` rejects with
`PERSISTENCE_FAILED`. The app is signed out anyway, but the next load would
restore the session, so call `signOut()` again later.
## Revoke tokens on your backend
Signing out in the app doesn't end the tokens on your backend: until they
expire, anyone holding them can still use them. If your backend can revoke
tokens, give `createAuth` a `revoke` option. It receives the ended tokens
after the user is signed out:
```ts title="src/revoke.ts"
import type { RevokeFn } from "@monarcode/session-kit";
/** Pass as `createAuth`'s `revoke` option. */
export const revoke: RevokeFn = async ({ refreshToken, signal }) => {
if (!refreshToken) return;
const response = await fetch("https://api.example.com/auth/revoke", {
method: "POST",
signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
if (!response.ok) throw new Error(`Revoke failed (${response.status})`);
};
```
The user is signed out before `revoke` runs, so a UI that follows the state
never waits for it. `signOut()` itself resolves after `revoke` settles, or
after 15 seconds, when `signal` aborts. Await it before a full-page redirect,
which would cancel the request.
A failed revocation shows in `state.error` as `REVOKE_FAILED`, and
`signOut()` still resolves. The sign-out stands: the user asked to leave, and
has.
`revoke` isn't called in two cases:
- **The backend already ended the session,** such as by rejecting the
refresh token.
- **The session is locked,** whether it was restored locked or locked by a
`lock()` that has resolved. Its tokens aren't in memory.
A sign-out before the saved session has been read still revokes that saved
session, unless `locking` is on.
## Next steps
- [Tabs](https://session-kit.pages.dev/docs/configuration/tabs): how a sign-in or sign-out reaches every
tab.
- [Updating the user](https://session-kit.pages.dev/docs/client/updating-the-user): change the user
without signing in again.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show `REVOKE_FAILED` and other
failures.
# Updating the user (https://session-kit.pages.dev/docs/client/updating-the-user)
After a profile edit, the signed-in user has changed but the session hasn't.
Signing in again would be wrong: the tokens are still good. `auth.updateUser`
replaces the user, saves it and keeps the session, so every component that
reads the user shows the change.
This page shows the two ways to call it, what happens when calls overlap, and
each way it can fail.
## Pass the new user
When you already have the new user, such as after your backend saved a
profile form, pass it to `updateUser`:
```ts title="src/rename.ts"
import { authFetch } from "./api.js";
import { auth } from "./auth.js";
/** Saves a new first name, then shows it without signing in again. */
export async function rename(firstName: string) {
const session = await auth.getSession();
if (!session) return;
const response = await authFetch(`users/${session.user.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ firstName }),
});
if (!response.ok) throw new Error(`Rename failed (${response.status})`);
await auth.updateUser({ ...session.user, firstName });
}
```
The user is checked against your user schema, as on sign-in. The session ID
stays the same, so data you [cached under it](https://session-kit.pages.dev/docs/client/state) stays
valid.
## Fetch the new user
When the new user comes from a request, pass a function that fetches it
instead. `fetchProfile` is the request from
[Getting started](https://session-kit.pages.dev/docs/getting-started#5-call-your-api):
```ts title="src/profile.ts"
import { fetchProfile } from "./api.js";
import { auth } from "./auth.js";
export const reloadProfile = () => auth.updateUser(fetchProfile);
```
The client notes the session before the function runs. If the user signs
out or switches account while it runs, `updateUser` rejects with
`SESSION_CHANGED`, and the user it fetched never lands on another account.
The function has 15 seconds to finish.
## Overlapping calls
When `updateUser` calls overlap, such as two quick saves of a form, the latest
call wins. The earlier ones reject with `SESSION_CHANGED`, so an older user
never replaces a newer one.
A token refresh that runs at the same time keeps the updated user, even when
your refresh callback returns a user of its own.
## When `updateUser` rejects
`updateUser` rejects rather than save a user to the wrong session. Here's
when, and with what:
| When… | `updateUser` rejects with… |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| No one is signed in | `UNAUTHENTICATED` |
| The session is [locked](https://session-kit.pages.dev/docs/client/locking) | `LOCKED` |
| The access token expired, and refreshing it failed | That failure, such as `REFRESH_FAILED` |
| The saved session can't be read | `PERSISTENCE_FAILED` |
| The user schema rejects the user | `USER_VALIDATION_FAILED` |
| The function rejects, or takes more than 15 seconds | `USER_VALIDATION_FAILED`, with the cause |
| The user signs out or switches account, or the access token expires, while the function runs | `SESSION_CHANGED` |
| A newer `updateUser` call starts | `SESSION_CHANGED` |
| The new user can't be saved | `PERSISTENCE_FAILED`, and the user is signed out |
Only the last case changes the session. In the others, `updateUser` leaves
the user as it was.
A function that rejects with an `AuthError` keeps its code. If the
`authFetch` call in `fetchProfile` rejects with `LOCKED`, for example, so
does `updateUser`.
## With users from the access token
A client that reads the user from the access token, with
[`fromAccessToken`](https://session-kit.pages.dev/docs/client/users-from-tokens), has no `updateUser`. The
token is the only source of the user there, so call `auth.refresh()` to pick
up a change.
## Next steps
- [State](https://session-kit.pages.dev/docs/client/state): scope cached data to `sessionId`, which an
update keeps.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show a failure to the user.
- [`AuthClient` reference](https://session-kit.pages.dev/docs/reference/core#authclient): `updateUser`
and the client's other methods.
# Authenticated requests (https://session-kit.pages.dev/docs/client/requests)
Your API wants the access token on every request, and it answers 401 when the
token has expired or been revoked. `createAuthFetch` gives you a `fetch` that
adds the token, gets a new one after a 401, and sends the token only to your
API, so your request code doesn't have to.
This page shows how to send requests with it, what happens after a 401, and
when it rejects. It builds on the `authFetch` from
[Getting started](https://session-kit.pages.dev/docs/getting-started#5-call-your-api).
## Send a request
`authFetch` takes the same arguments as `fetch`. Pass a path, and it's
resolved against `baseUrl`, the way a link is resolved against a page's
address:
```ts title="src/orders.ts"
import { authFetch } from "./api.js";
export async function loadOrders(userId: number) {
// https://dummyjson.com/auth/carts/user/1, with the access token.
const response = await authFetch(`auth/carts/user/${userId}`);
if (!response.ok) throw new Error(`Orders failed (${response.status})`);
return response.json();
}
```
Here's what to know about the URL and the headers:
- `baseUrl` must be an absolute URL. End it with `/`, so that
`authFetch("orders")` lands under it rather than beside it.
- `authFetch` also takes a `URL` or a `Request`, so an HTTP client with a
`fetch` option can send its requests through it. See
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients).
- While the user is signed in, `authFetch` sets `Authorization: Bearer …`. It
replaces any `Authorization` header the request already has.
- A `Request` with a body can be sent only one time, as with `fetch`. To send
a write again, keep a clone.
## After a 401
When your API answers 401, `authFetch` gets a new access token and sends the
request again. It does that only for `GET` and `HEAD`, which are safe to send
twice. A `POST` or any other method comes back with its 401, for you to
decide.
The rest of the 401 handling:
- Requests that get a 401 at the same time share one refresh. If another
request or another tab has already replaced the token, `authFetch` uses the
new one without a refresh.
- If the request sent again gets a 401 too, your API has rejected the new
token as well, so the user is signed out. If your API also answers 401 for
other reasons, set `signOutOnRepeated401` to `false`, as
[below](#keep-users-signed-in-after-a-second-401).
- Without a refresh token or a `refresh` option, there's nothing to refresh
with, so the first 401 signs the user out, whatever `signOutOnRepeated401`
is.
- If your backend rejects the refresh token, the user is signed out, and
`authFetch` resolves the original 401. If the user signs out or switches
account while the refresh runs, it rejects with `SESSION_CHANGED`.
## Retry a write
Because `authFetch` never sends a write twice, retry it yourself where
sending it twice is safe. After the 401, the token has already been
refreshed:
```ts title="src/add-to-cart.ts"
import { authFetch } from "./api.js";
export async function addToCart(userId: number, productId: number) {
const send = () =>
authFetch("auth/carts/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId,
products: [{ id: productId, quantity: 1 }],
}),
});
let response = await send();
// The 401 refreshed the token, so one more try uses the new one.
if (response.status === 401) response = await send();
if (!response.ok) throw new Error(`Add to cart failed (${response.status})`);
}
```
## When it rejects
`authFetch` rejects rather than send the token somewhere it shouldn't go, or
resolve a response meant for another account. Here's when it rejects, and
with what:
| When… | `authFetch` rejects with… |
| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| The URL is on another origin, has a username or password in it, or isn't a valid URL | `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. |
| The `Request` comes from a polyfill or another realm, such as an iframe | `INVALID_OPTIONS` |
| The user is signed out | `UNAUTHENTICATED`, unless `optional` is `true` |
| The session is locked | `LOCKED`, even when `optional` is `true` |
| The saved session can't be read | `PERSISTENCE_FAILED` |
| A refresh fails | That failure, such as `REFRESH_FAILED`, until a retry, a refresh, new tokens from another tab, or a sign-in or sign-out |
| The user signs out or switches account while the request runs | `SESSION_CHANGED` |
| The response is a redirect | A `TypeError`, as `fetch` gives when it refuses a redirect |
| The network fails | `fetch`'s own error, usually a `TypeError` |
The last two aren't `AuthError`s, so code that matches on `code` doesn't
catch them. To show these failures, see [Errors](https://session-kit.pages.dev/docs/configuration/errors).
A redirect isn't followed, so the token never reaches a server your API
redirects to. On React Native before Expo SDK 58, `fetch` follows a redirect
whatever it's told. `authFetch` still refuses the response, but the
redirected request has already gone out. Don't let your API
redirect requests that carry a token.
## Send requests while signed out
Some apps call one API for public and private endpoints alike. With
`optional: true`, a signed-out request goes out without a token instead of
rejecting:
```ts title="src/public-api.ts"
import { createAuthFetch } from "@monarcode/session-kit/http";
import { auth } from "./auth.js";
import { API } from "./backend.js";
export const publicFetch = createAuthFetch(auth, {
baseUrl: `${API}/`,
optional: true,
});
```
A request sent without a token keeps its own `Authorization` header, if it
has one. A 401 to it comes back as it is, with no refresh and no sign-out.
## Keep users signed in after a second 401
Some APIs answer 401 for reasons other than a rejected token, such as a
resource the user can't see. With `signOutOnRepeated401: false`, a second
401 to the same request comes back as it is, and the user stays signed in:
```ts title="src/reports-api.ts"
import { createAuthFetch } from "@monarcode/session-kit/http";
import { auth } from "./auth.js";
import { API } from "./backend.js";
export const reportsFetch = createAuthFetch(auth, {
baseUrl: `${API}/`,
signOutOnRepeated401: false,
});
```
## Next steps
- [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients): send ky, axios or
openapi-fetch requests through `authFetch`, or add the token yourself.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show a failed refresh or an outage to
the user.
- [`createAuthFetch` reference](https://session-kit.pages.dev/docs/reference/http#createauthfetch): every
option and error.
# Other HTTP clients (https://session-kit.pages.dev/docs/client/other-http-clients)
Your app might already call its API through an HTTP client such as ky, axios
or openapi-fetch. You don't have to replace it to send the access token. Most
clients let you choose the `fetch` they call, and `authFetch` can be that
`fetch`. A client with its own transport can use the three calls `authFetch`
is built on.
This page shows both ways, and what each one leaves to you.
## Clients that take a `fetch`
[`authFetch`](https://session-kit.pages.dev/docs/client/requests) takes a `URL` or a `Request` as well as
a path, as `fetch` does. A client that sends its requests through it gets
everything `authFetch` does: the token goes only to your API's origin, a 401
refreshes the token one time, and only a `GET` or `HEAD` is sent again.
With [ky](https://github.com/sindresorhus/ky), pass `authFetch` as `fetch`:
```ts title="src/ky.ts"
import ky from "ky";
import { authFetch } from "./api.js";
import { API } from "./backend.js";
export const api = ky.create({ baseUrl: `${API}/`, fetch: authFetch });
export async function fetchCarts(userId: number): Promise {
return api.get(`auth/carts/user/${userId}`).json();
}
```
With [axios](https://axios-http.com), choose its `fetch` adapter, and pass
`authFetch` as `env.fetch`:
```ts title="src/axios.ts"
import axios from "axios";
import { authFetch } from "./api.js";
import { API } from "./backend.js";
export const http = axios.create({
baseURL: API,
adapter: "fetch",
env: { fetch: authFetch },
});
```
With [openapi-fetch](https://openapi-ts.dev/openapi-fetch/), pass `authFetch`
as the `fetch` option of `createClient`, with your API as its `baseUrl`, the
same way as with ky.
Here's what changes for the client's calls:
- **Give the client the same API.** Its base URL must be on the origin that
`authFetch` was created for. A request for another origin rejects with
`INVALID_OPTIONS`, and the token isn't sent.
- **Signed out, every call rejects** with `UNAUTHENTICATED`. If the client
also calls public endpoints, such as your sign-in, create `authFetch` with
[`optional: true`](https://session-kit.pages.dev/docs/client/requests#send-requests-while-signed-out).
Those requests then go out without a token.
- **A 401 reaches the client after the refresh.** For a `GET` or `HEAD`, the
client gets the answer to the request that was sent again. For a write, it
gets the 401, as ky's `HTTPError` or axios's `AxiosError`. Retry it where
sending it twice is safe.
- **Session kit's errors keep their code.** ky rejects with the `AuthError`
itself. axios wraps it in an `AxiosError` with the same `code`, and the
`AuthError` as its `cause`. Match on `error.code`, which works with both,
rather than on `instanceof AuthError`.
- **`authFetch` sets the `Authorization` header,** in place of one the client
set itself. [Authenticated requests](https://session-kit.pages.dev/docs/client/requests) has the rest of
its rules.
- **Only what a `Request` holds is sent.** ky passes `fetch` the options it
doesn't use itself, such as Next.js's `next`. `authFetch` doesn't pass
those on.
## Clients without a `fetch` option
`createAuthFetch` and effetch's [`sessionBearer` plugin](https://session-kit.pages.dev/docs/effect#how-sessionbearer-differs-from-createauthfetch) are
built on three calls, and a client with its own transport can use the same
ones:
1. **Before a request,** `auth.credentials.get()` resolves the credentials to
send. It waits for the saved session to be read, and refreshes an access
token that has expired first. It resolves `null` when no one is signed in.
2. **After a 401,** `auth.credentials.renew(credentials)` takes the
credentials that request was sent with, and resolves new ones. Requests
that fail at the same time share one refresh. It resolves `null` when the
user was signed out instead.
3. **After a second 401,** `auth.credentials.reject(credentials)` ends the
session, unless newer credentials have replaced the ones you pass.
`get` and `renew` reject in these cases:
- **`LOCKED`** while the session is [locked](https://session-kit.pages.dev/docs/client/locking).
- **The refresh's failure,** such as `REFRESH_FAILED`, when a refresh fails.
- **`SESSION_CHANGED`** when another session replaces the one they're working
for.
- **`PERSISTENCE_FAILED`** when the saved session can't be read, or the new
tokens can't be saved.
Thrown from an axios interceptor, these errors reach your code as the
`AuthError` itself, not as an `AxiosError`.
An axios instance that keeps its default adapter does it with two
interceptors:
```ts title="src/axios-interceptors.ts"
import type { Credentials } from "@monarcode/session-kit";
import axios, { type InternalAxiosRequestConfig } from "axios";
import { auth } from "./auth.js";
import { API } from "./backend.js";
type Config = InternalAxiosRequestConfig & { replayed?: boolean };
// One instance for one API, so the token goes nowhere else.
export const http = axios.create({ baseURL: API });
/** The credentials each request was sent with. */
const sent = new WeakMap();
http.interceptors.request.use(async (config) => {
const credentials = await auth.credentials.get();
// Signed out, the request goes without a token, as a public one would.
if (credentials) {
config.headers.set("Authorization", `Bearer ${credentials.accessToken}`);
sent.set(config, credentials);
}
return config;
});
http.interceptors.response.use(undefined, async (error: unknown) => {
if (!axios.isAxiosError(error) || error.response?.status !== 401) throw error;
const config: Config | undefined = error.config;
const used = config && sent.get(config);
if (!config || !used) throw error;
if (config.replayed) {
// The new token was refused too: end the session.
await auth.credentials.reject(used);
throw error;
}
const fresh = await auth.credentials.renew(used);
// As with authFetch, only a GET or HEAD is sent twice. For anything else
// the caller decides.
if (!fresh || !["get", "head"].includes(config.method ?? "")) throw error;
const replay: Config = { ...config, replayed: true };
return http.request(replay);
});
```
## What's left to you
Without `authFetch`, a few things it does for you are yours to do:
- **Keep the token on one origin.** Give the client one base URL, and don't
pass it absolute URLs to other hosts.
- **Don't read the token early.** Ask for credentials in the request hook,
never once at startup. A token saved in a variable goes stale at the
next refresh.
- **Check the account after slow work.** `auth.isCurrent(credentials)`
checks whether the session that sent a request is still the signed-in one,
before you show its answer.
- **Don't follow redirects with the token.** `authFetch` refuses a redirect,
as [Authenticated requests](https://session-kit.pages.dev/docs/client/requests#when-it-rejects)
explains. axios's default adapters follow it, so don't let your API
redirect requests that carry a token.
- **Decide about signed-out requests.** `authFetch` rejects them with
`UNAUTHENTICATED`, unless it was created with `optional: true`. The
interceptor above sends them without a token instead. Throw in the request
interceptor if your API should never get one.
## Next steps
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): what `authFetch` does
after a 401, and when it rejects.
- [Effect and effetch](https://session-kit.pages.dev/docs/effect): send the token from Effect code with
`sessionBearer`.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show a failed refresh to the user.
# Users from the access token (https://session-kit.pages.dev/docs/client/users-from-tokens)
Some backends answer a sign-in with tokens only, and put the user in the
access token: a JWT whose claims hold the user's ID, email and roles. Then
there's no user object to pass to `signIn`, and the user can change on every
refresh. `fromAccessToken` reads the user from the token's claims instead.
This page shows how to set it up, what changes for the client, and how to
verify the token on a server.
## Read the user from the token
Pass `fromAccessToken` as the `user` option. Its first argument is a schema
for the claims, and its second turns them into the user your app sees:
```ts title="src/token-auth.ts"
import {
createAuth,
fromAccessToken,
webStorage,
} from "@monarcode/session-kit";
import { z } from "zod";
const claimsSchema = z.object({ sub: z.string(), email: z.string() });
export const tokenAuth = createAuth({
name: "my-token-app",
// The claims are validated, then mapped to the user the app sees.
user: fromAccessToken(claimsSchema, (claims) => ({
id: claims.sub,
email: claims.email,
})),
storage: webStorage(),
});
export const signInWithTokens = (tokens: {
accessToken: string;
refreshToken: string;
}) => tokenAuth.signIn(tokens);
```
`signIn` takes tokens only, and your refresh callback returns tokens only.
Without the second argument, the claims are the user.
## What changes
Reading the user from the token changes a few things:
- **The user is read from every token:** on sign-in, on each refresh, from
tokens another tab saved, and on every load. Only the tokens are saved, so
the user is read again each time the session is restored.
- **No `updateUser`.** The token is the only source of the user, so call
`auth.refresh()` to pick up a change.
- **Locking isn't available.** A locked session shows its user without
opening its tokens, so [locking](https://session-kit.pages.dev/docs/client/locking) needs a user schema.
`createAuth` throws `INVALID_OPTIONS` when you pass both.
- **For backends you control.** OAuth providers can change their access token
format without notice.
## Keep the mapping stable
The mapping runs every time a token is read, so it has to give the same user
for the same claims:
- **Keep it pure and synchronous.** Don't fetch or read the clock in it.
- **Leave out claims that change on every refresh,** such as `exp`, `iat` or
`jti`. Then the user stays the same object across refreshes, and
components that compare users don't re-render.
## When the token can't be read
A token that isn't a readable JWT, or whose claims the schema rejects, fails
with `USER_VALIDATION_FAILED`. What happens next depends on where the token
came from:
| The token came from… | What happens |
| -------------------------- | ---------------------------------------------------------------------------------------- |
| `signIn` | `signIn` rejects, and the current session stays. |
| The saved session, on load | The user is signed out, and `state.error` shows the error. |
| Another tab | The user is signed out, and `state.error` shows the error. |
| A refresh | The refresh fails with that error, and the session is kept, as after any failed refresh. |
## Verify the token on a server
By default, the claims are read without checking the token's signature. That
suits a browser, which trusts a user object in a JSON response from its own
backend just as much. On a server, such as with
[server sessions](https://session-kit.pages.dev/docs/server-rendering), verify the token: pass a `decode`
function as the third argument:
```ts title="src/verified-user.ts"
import { fromAccessToken } from "@monarcode/session-kit";
import { z } from "zod";
// Your own check, with your JWT library: it throws for a bad signature.
declare function verifyJwt(accessToken: string): Promise;
export const verifiedUser = fromAccessToken(
z.object({ sub: z.string(), email: z.string() }),
(claims) => ({ id: claims.sub, email: claims.email }),
{ decode: verifyJwt },
);
```
`decode` returns the claims, and the schema checks them as before. It may
return a promise, as `verifyJwt` does. In a browser, that stops a saved
session from showing before the first render.
The
[`tanstack-start-spa`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa)
and
[`react-router-data`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-data)
examples read their user from the access token.
## Next steps
- [Signing in and out](https://session-kit.pages.dev/docs/client/signing-in-and-out): what `signIn` does
with the tokens.
- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh): return tokens from your refresh
callback, and handle a failed refresh.
- [`fromAccessToken` reference](https://session-kit.pages.dev/docs/reference/core#fromaccesstoken): its
arguments and options.
# Locking (https://session-kit.pages.dev/docs/client/locking)
A banking or health app often asks a returning user to unlock it, with Face
ID, a fingerprint or a passcode, before it shows anything. The user is still
signed in, but the app shouldn't use their tokens until they prove it's
them. Locking gives you that: a saved session restores as **locked**, with
the user known and the tokens sealed until your app unlocks them.
This page explains what locked means, what you provide, and how unlocking
and locking again behave. For the Expo how-to, with a key behind the
device's biometrics, see [Unlock with biometrics](https://session-kit.pages.dev/docs/setups/expo-locking).
## Turn on locking
Pass a `locking` option to `createAuth`, with a `seal` function that encrypts
the tokens and an `open` function that decrypts them:
```ts title="src/locked-auth.ts"
import { createAuth, type AuthStorage } from "@monarcode/session-kit";
import { userSchema } from "./backend.js";
// Your app's own: a native secure store, and encryption with a key it loads
// when the user unlocks.
declare const storage: AuthStorage;
declare const key: CryptoKey;
declare function encrypt(key: CryptoKey, plain: string): Promise;
declare function decrypt(key: CryptoKey, sealed: string): Promise;
export const lockedAuth = createAuth({
name: "my-native-app",
user: userSchema,
storage,
locking: {
// Runs whenever the tokens are saved.
seal: (payload) => encrypt(key, payload),
// Runs only from `unlock()`.
open: (sealed) => decrypt(key, sealed),
},
});
/** After the app has its key: resolves the session, `authenticated`. */
export const unlockApp = () => lockedAuth.unlock();
/** `locked` again. The saved session stays, and the tokens leave memory. */
export const lockApp = () => lockedAuth.lock();
```
Sealing is yours: Session kit depends on no crypto or biometrics library.
The user and the session ID are saved beside the sealed tokens, where they
can be read while locked. `locking: true` saves the tokens as they are, for
a lock screen in front of an otherwise ordinary session.
## What locked means
A saved session restores as `locked`. `user` and `sessionId` are set, so a
"Welcome back" screen can greet the user by name, but the tokens stay sealed
until `auth.unlock()`.
While the session is locked, nothing waits for an unlock that might never
come:
- `getSession`, `retry`, `refresh`, `updateUser`, `credentials.get` and
`credentials.renew` reject with `LOCKED`. So does
[`authFetch`](https://session-kit.pages.dev/docs/client/requests#when-it-rejects).
- Nothing refreshes, and the expiry timers are off.
- The router adapters treat a locked session as signed out.
- `user` is still set, so check `status`, not `user`, to know whether the
app has access. [State](https://session-kit.pages.dev/docs/client/state#check-status-not-user) shows
how.
Two calls still work while locked:
- **`signIn`** replaces the locked session, so a user who can't unlock can
sign in again.
- **`signOut`** ends it, without calling your `revoke` option: the tokens
aren't in memory to revoke. A session that `lock()` is still locking, while
a refresh finishes, is revoked as usual.
## Seal with a key
With `seal` and `open` in `locking`, every save calls `seal`: a sign-in's, a
refresh's and a profile update's. If `seal` throws, as it does when your app
doesn't have the key, the save fails with `PERSISTENCE_FAILED`, and no one is
signed in. The one exception is a session saved before locking was turned
on: unlocking seals it, and if that `seal` fails, the user stays signed in
and the saved session stays as it was until the next save.
So your app needs the key whenever it saves, not only when it unlocks:
- **On a password sign-in,** make a new key before you call `signIn`, as
`withNewKey` does in [Unlock with biometrics](https://session-kit.pages.dev/docs/setups/expo-locking).
- **While locking,** keep the key until `lock()` settles. A refresh already
running when you call `lock()` still saves its tokens, and saving seals
them.
## Unlock
`auth.unlock()` reads the saved tokens, opens them with your `open` function,
and resolves the session, `authenticated` again. If the access token has
expired, it refreshes it first. Overlapping calls share one unlock, and when
the session isn't locked, `unlock()` acts like `getSession()`.
A failed unlock doesn't always leave the session locked. Here's what each
outcome does, so you can check `status` after a rejection:
| When… | `unlock()`… | The session afterwards |
| ------------------------------------------------- | --------------------------------- | ------------------------------------------- |
| `open` throws, or doesn't return a string | Rejects with `UNLOCK_FAILED` | Still locked |
| Storage can't be read | Rejects with `PERSISTENCE_FAILED` | Still locked |
| What `open` returns isn't this session's tokens | Rejects with `INVALID_SESSION` | Signed out |
| The saved session is gone, or older than `maxAge` | Resolves `null` | Signed out |
| The backend rejects the refresh token | Resolves `null` | Signed out |
| The refresh fails for another reason | Rejects with `REFRESH_FAILED` | Unlocked, and `unavailable` until `retry()` |
| The user signs in or out while it runs | Rejects with `SESSION_CHANGED` | The new session, or signed out |
## Lock again
`auth.lock()` locks a session that's in use, such as when the app goes to
the background. `status` turns `locked` at once, and the timers stop. The
saved session and `user` stay.
The tokens leave memory when `lock()` resolves. If a refresh is running,
`lock()` waits for it to save its tokens first: cancelling it could lose a
refresh token your backend has already replaced.
`lock()` does nothing when no one is signed in or the session is already
locked.
`lock()` and `unlock()` reject with `INVALID_OPTIONS` on a client created
without `locking`.
## Limits
- **Native apps only.** Locking is built for one JavaScript context. With
`locking`, tabs don't follow each other, and the client doesn't check for
changes that another context saved.
- **It needs a user schema.** A user read from the access token can't be
shown without its token, so `createAuth` throws `INVALID_OPTIONS` for
`locking` with
[`fromAccessToken`](https://session-kit.pages.dev/docs/client/users-from-tokens).
- **Not with server rendering.** The browser's client for a session kept on
the server has no `lock` or `unlock`.
- **Turning it on later** works: a session saved before `locking` was added
restores as `locked` too, and is sealed when it's unlocked.
- **Turning it off later** makes sealed sessions unreadable. Those users are
signed out, with `INVALID_SESSION` in `state.error`.
## Next steps
- [Unlock with biometrics](https://session-kit.pages.dev/docs/setups/expo-locking): a key behind the
device's biometrics, AES-GCM sealing, and a welcome-back screen in Expo.
- [Expo Router](https://session-kit.pages.dev/docs/setups/expo): set up the app the lock screen sits in.
- [`AuthLocking` reference](https://session-kit.pages.dev/docs/reference/core#authlocking): `seal` and
`open`.
# Configuring the client (https://session-kit.pages.dev/docs/configuration)
The client from [Getting started](https://session-kit.pages.dev/docs/getting-started) sets a few
options and leaves the rest to their defaults. When your app outgrows them,
because your backend sends tokens differently, sessions must last longer, or
you need to see why a user was signed out, the options passed to
`createAuth` are where you change it.
This page lists every option, and the pages in this section explain each
part of the client in turn.
## Options
`createAuth` takes three required options and five optional ones:
| Option | Required | What it sets |
| --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Yes | Names the saved session and the refresh lock: letters, digits, `_` or `-`, up to 64 characters. Keeps two apps on one origin apart. |
| `user` | Yes | A [user schema](https://session-kit.pages.dev/docs/configuration/user-schemas), or [`fromAccessToken`](https://session-kit.pages.dev/docs/client/users-from-tokens). |
| `storage` | Yes | [Where the session is saved](https://session-kit.pages.dev/docs/configuration/storage). |
| `refresh` | No | [How to get new tokens](https://session-kit.pages.dev/docs/configuration/refresh). Without it, the user is signed out when the access token expires or your API rejects it. |
| `revoke` | No | [Revokes the ended tokens](https://session-kit.pages.dev/docs/client/signing-in-and-out) on your backend after a sign-out. |
| `maxAge` | No | [How long a saved session lasts](https://session-kit.pages.dev/docs/configuration/storage#how-long-a-saved-session-lasts), in seconds. Default: 30 days, counted from each save. |
| `debug` | No | [Reports what the client does](https://session-kit.pages.dev/docs/configuration/debugging). Default: off. |
| `locking` | No | [Restores a saved session as `locked`](https://session-kit.pages.dev/docs/client/locking), for native apps. Default: off. |
`createAuth` throws an `AuthError` with the code `INVALID_OPTIONS` when it
can't use an option, such as a `name` with other characters, or a `maxAge`
that isn't a positive whole number.
## Pages in this section
Each page covers one part of the client: how it checks users, gets new
tokens, saves the session, follows other tabs, and reports what happens.
- [User schemas](https://session-kit.pages.dev/docs/configuration/user-schemas): When the schema checks users, and what restoring a session asks of it.
- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh): What the refresh callback returns, when a refresh runs, and what happens when it fails.
- [Expiry](https://session-kit.pages.dev/docs/configuration/expiry): How the client finds out when the access token expires.
- [Storage](https://session-kit.pages.dev/docs/configuration/storage): Where the session is saved, how long it lasts, and how to write your own store.
- [Tabs](https://session-kit.pages.dev/docs/configuration/tabs): How tabs follow each other's sign-ins, and take turns to refresh.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): Where errors appear, how to show them, and the failures that need a decision from you.
- [Debugging](https://session-kit.pages.dev/docs/configuration/debugging): Log what the client does, or send it to your error reporting.
## Next steps
- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh): check that your refresh callback
tells a rejected token from an outage.
- [Storage](https://session-kit.pages.dev/docs/configuration/storage): choose where the session is saved,
and for how long.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show failed refreshes and storage
problems to your users.
# User schemas (https://session-kit.pages.dev/docs/configuration/user-schemas)
Your backend answers a sign-in with the user's fields, and your components
render them. The schema you pass as `createAuth`'s `user` option sits
between the two: it checks each user the client accepts, and gives the user
its type in your code.
This page shows when the schema runs, the two rules it must follow so that a
saved session can be restored, and how to change it without signing anyone
out.
Any [Standard Schema](https://standardschema.dev) library works, such as Zod,
Valibot or ArkType. If your backend puts the user in the access token
instead, see [Users from the access token](https://session-kit.pages.dev/docs/client/users-from-tokens).
## The user's type
`createAuth` infers the user's type from the schema's output. With the
schema from [Getting started](https://session-kit.pages.dev/docs/getting-started#2-create-the-client),
hover `user` to see it:
```ts title="src/user-type.ts"
import type { SessionOf, UserOf } from "@monarcode/session-kit";
import { auth } from "./auth.js";
const { user } = auth.state.get();
// ^?
// The same types, named for the rest of your code.
export type AppUser = UserOf;
export type AppSession = SessionOf;
```
`user` is `null` unless the session is `authenticated`, `refreshing` or
`locked`, and checking `status` narrows it. To type the hooks from `@monarcode/session-kit/react`, register the
client one time, as
[Getting started](https://session-kit.pages.dev/docs/getting-started#4-read-the-session-in-react) shows.
## When the schema runs
The client runs the schema on every user it accepts:
- At sign-in.
- When `updateUser` replaces the user.
- After a refresh that returns a user.
- When it restores a saved session.
- When another tab saves a session.
It keeps a frozen copy of each user it accepts. To change the user, call
[`updateUser`](https://session-kit.pages.dev/docs/client/updating-the-user).
An asynchronous schema, such as one with an async refinement, has 15 seconds
to answer each check, and a check that takes longer fails. During a refresh,
the check shares the refresh's 15 seconds. It also means a
saved session can't be restored before the first render, as the
[Introduction](https://session-kit.pages.dev/docs) explains: the app shows `initializing` first.
## Rules for restoring
The client saves the user beside the tokens, and runs the schema on it again
when it restores the session. That sets two rules for the schema:
- **Its output is a plain JSON object.** Dates, `Map`s and class instances
can't be saved.
- **It accepts its own output and returns it unchanged.** A one-way
transform, such as one that renames a field, breaks this rule.
A schema that breaks either rule is rejected with `USER_VALIDATION_FAILED`
the first time it accepts a user, usually at sign-in. That way the problem
shows up right away, not as users being signed out on their next reload.
## Change the schema safely
A deploy can change the schema so that it rejects users saved before it.
When the client restores such a user, it signs them out and clears the saved
session, with `USER_VALIDATION_FAILED` in `state.error`. The user then signs
in again.
To add a field without signing anyone out, make it optional or give it a
default. A saved user without the field still passes, and a default fills
it in on restore.
A user that another tab saved, and that this tab's schema rejects, signs
every tab out the same way. That can happen while two versions of your app
are open in different tabs. [Errors](https://session-kit.pages.dev/docs/configuration/errors) covers this
and the other saved sessions the client can't use.
## Next steps
- [Users from the access token](https://session-kit.pages.dev/docs/client/users-from-tokens): read the
user from a JWT instead of a schema.
- [Updating the user](https://session-kit.pages.dev/docs/client/updating-the-user): change the signed-in
user's fields after sign-in.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show `USER_VALIDATION_FAILED` and
the other errors to your users.
# Refresh (https://session-kit.pages.dev/docs/configuration/refresh)
Access tokens last minutes, and users stay for hours. `createAuth`'s
`refresh` option is a callback that exchanges the refresh token for new
tokens, so the user stays signed in when the access token expires.
This page shows what the callback should return, when the client calls it,
and what happens when it fails. The callback in
[Getting started](https://session-kit.pages.dev/docs/getting-started#1-talk-to-your-backend) is a good
place to start.
## What the callback returns
The callback tells the client one of three things: here are new tokens, the
backend rejected the refresh token, or the backend couldn't answer. For
example, against DummyJSON:
```ts title="src/refresh.ts"
import type { RefreshFn } from "@monarcode/session-kit";
import { API } from "./backend.js";
type RefreshBody = { accessToken: string; refreshToken: string };
export const refresh: RefreshFn = async ({ refreshToken, signal }) => {
const response = await fetch(`${API}/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
signal,
});
// The backend rejected the refresh token: sign the user out.
if (response.status === 401 || response.status === 403) return null;
// Anything else is an outage: keep the session.
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
const body = (await response.json()) as RefreshBody;
return { accessToken: body.accessToken, refreshToken: body.refreshToken };
};
```
Pass it as `refresh` when you create the client. Here's what the client does
with each result:
| The callback | What the client does |
| -------------- | -------------------------------------------------------------------------------------------------------------------------- |
| Returns tokens | Saves them. A refresh token or user it leaves out keeps the current one. |
| Returns `null` | Treats the refresh token as rejected: signs the user out and clears the saved session. |
| Throws | Treats it as an outage: keeps the session and reports `REFRESH_FAILED`. See [When a refresh fails](#when-a-refresh-fails). |
Return `null` only when your backend rejected the refresh token, such as with
a 401. Throw for anything else, such as a network error or a 500, so that an
outage doesn't sign anyone out. To sign the user out on every failure, return
`null` instead of throwing. An `AuthError` you throw keeps its own code.
The client also checks the tokens and the user you return. It refuses them
in these cases, and counts the refresh as failed, with the session kept:
- When the client can tell
[when the new access token expires](https://session-kit.pages.dev/docs/configuration/expiry), the token
must last at least five seconds. A shorter one, or one that has already
expired, fails with `INVALID_SESSION`.
- Tokens with both `expiresIn` and `expiresAt` fail with `INVALID_SESSION`.
- The access token your API rejected, returned again, fails with
`INVALID_SESSION`.
- A user that the [user schema](https://session-kit.pages.dev/docs/configuration/user-schemas) rejects
fails with `USER_VALIDATION_FAILED`.
These keep their own code in `state.error`, rather than `REFRESH_FAILED`.
## When a refresh runs
The client refreshes at one of three moments:
- **Early.** While the client is mounted, it refreshes 60 seconds before the
access token expires. When less than two minutes are left, it refreshes
halfway through the time that's left instead. It tries once per token.
- **At expiry, or after a 401.** `status` is `refreshing` while it runs, and
the user stays on screen.
- **On request.** `auth.refresh()` runs one straight away. It rejects with
`REFRESH_FAILED` when there's nothing to refresh with: no `refresh` option,
or no refresh token.
Only one refresh runs at a time. A request that needs one while it runs
waits for it, and tabs take turns, as [Tabs](https://session-kit.pages.dev/docs/configuration/tabs)
explains.
Without a `refresh` option or a refresh token, there's nothing to refresh
with. The user is signed out, with no error, when the access token expires
or your API rejects it.
## When a refresh fails
What a failure means depends on whether the access token still works.
If an early refresh fails, the access token stays usable until it expires.
The user stays `authenticated`, and `state.error` shows the failure, usually
`REFRESH_FAILED`. When the token expires, the client refreshes again.
If a refresh the session needed fails, because the access token expired or
was rejected, `status` becomes `unavailable`. The saved session is kept, so
access can come back without a new sign-in. `getSession()` rejects with the
same error until one of these happens:
- You call `auth.retry()` or `auth.refresh()`.
- The user signs in or out.
- Another tab saves new tokens.
Guards that run again therefore can't start a refresh loop. To offer the
user a way out, show a **Try again** button that calls `auth.retry()`, as
[Errors](https://session-kit.pages.dev/docs/configuration/errors) shows.
## Deadlines
The client gives each refresh 15 seconds. The callback's `signal` aborts
when that time runs out, or when the session changes, such as on sign-out.
Pass it to `fetch`, as the example does. A refresh that runs out of time
fails like an outage, with `REFRESH_FAILED`.
## Next steps
- [Expiry](https://session-kit.pages.dev/docs/configuration/expiry): make sure the client can tell when the
access token expires, so it can refresh early.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show a failed refresh to the user,
and let them try again.
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): see how `authFetch`
refreshes after a 401.
# Expiry (https://session-kit.pages.dev/docs/configuration/expiry)
The client refreshes the access token before it expires, so it reads when
that is from your tokens. Your backend can say so in a few ways: a lifetime
in the sign-in response, a fixed time, or claims inside a JWT.
This page shows where the client reads the expiry from, which field to send,
and what happens when there's none.
## Send the token's lifetime
Most backends answer with a lifetime, such as OAuth's `expires_in`. Pass it
as `expiresIn`, in seconds:
```ts title="src/tokens.ts"
import type { Tokens } from "@monarcode/session-kit";
type TokenResponse = {
access_token: string;
refresh_token: string;
expires_in: number;
};
export const toTokens = (body: TokenResponse): Tokens => ({
accessToken: body.access_token,
refreshToken: body.refresh_token,
expiresIn: body.expires_in,
});
```
The client counts `expiresIn` from when it receives the tokens, so a wrong
device clock doesn't matter. Send `expiresAt`, in Unix milliseconds, only
when your backend gives no lifetime.
Pass `expiresIn` or `expiresAt`, not both. Tokens with both are an
`INVALID_SESSION` error. See [`Tokens`](https://session-kit.pages.dev/docs/reference/core#tokens) for
each field.
## Where the expiry comes from
When your tokens hold more than one of these, the client uses the first it
finds:
1. `expiresIn` or `expiresAt`.
2. A JWT access token's `exp` and `iat` claims, as a lifetime, when `exp` is
later than `iat`.
3. A JWT access token's `exp` claim alone, as a time.
A JWT with `iat` works like `expiresIn`: the client counts the lifetime from
when it receives the token. So if your access token is a JWT with both
claims, you don't need to send an expiry at all.
## Fixed times and device clocks
`expiresAt` and a JWT's `exp` alone are fixed times, which the client
compares with the device's clock. Device clocks can be minutes off. A clock
that runs fast makes the token look already expired, and `signIn` rejects
it with `INVALID_SESSION`.
## Tokens without an expiry
When the client can't tell when the token expires, it uses the token until
your API rejects it. [`authFetch`](https://session-kit.pages.dev/docs/client/requests) then refreshes after
the 401. There's no early refresh, since there's nothing to count down to.
## Next steps
- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh): see when the client refreshes, and
what it does when a refresh fails.
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): send the access token
with each request, and refresh after a 401.
- [`Tokens` reference](https://session-kit.pages.dev/docs/reference/core#tokens): every field `signIn`
and your refresh callback take.
# Storage (https://session-kit.pages.dev/docs/configuration/storage)
A user who reloads the page, or opens your app the next day, expects to
still be signed in. That works because the client saves the session, and
`createAuth`'s `storage` option chooses where.
This page helps you pick a built-in store, set how long a saved session
lasts, or write a store of your own.
## Pick a store
The `storage` option takes one of Session kit's stores, or any object that
implements `AuthStorage`:
| Storage | Saved in | Use it for |
| --------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------- |
| `webStorage()` | `localStorage` | Browsers. One session, shared by every tab. |
| `webStorage({ area: "session" })` | `sessionStorage` | One session per tab, ending with the tab. |
| `secureStorage()` | The iOS keychain, or encrypted with an Android Keystore key | Expo apps. From `@monarcode/session-kit/expo`. |
| `memoryStorage()` | Memory | Tests, and sessions that shouldn't outlive the page. |
| Your own `AuthStorage` | Anywhere | Another store. Its operations can return promises. |
`secureStorage()` splits a large session across several keys, since some
iOS releases refuse long values. Its
[reference](https://session-kit.pages.dev/docs/reference/expo#securestorage) has the details.
### Use localStorage with rotating refresh tokens
If your backend rotates refresh tokens, issuing a new one with each refresh,
use `localStorage`, not `sessionStorage`.
A browser copies `sessionStorage` into a duplicated tab, and into a window
opened with `window.open`. Both then start with the same refresh token but
never see each other's saves. The second to refresh sends a spent token and
is signed out. With reuse detection on the backend, both are.
## How long a saved session lasts
A saved session lasts 30 days from the last time it was saved. To change
that, pass `maxAge` to `createAuth`, in whole seconds: `7 * 24 * 60 * 60` for
a week.
Every save starts the count again, and the client saves at each sign-in,
refresh and profile update. A user who comes back within `maxAge` finds the
session restored, and one who's been away longer signs in again.
The client checks `maxAge` when it restores a saved session, such as on a
reload. Each save records its expiry, so a lower `maxAge` applies to a saved
session from its next save. A session saved longer ago isn't restored: the client clears it, and
the user is signed out without an error. So is a session saved in another
format by an older or newer version of Session kit.
`maxAge` must be a positive whole number. Anything else makes `createAuth`
throw `INVALID_OPTIONS`.
## Write your own store
To save the session somewhere else, write an `AuthStorage`. For example, to
save it in a key-value store your app already has, which removes each entry
when it expires:
```ts title="src/storage.ts"
import type { AuthStorage } from "@monarcode/session-kit";
declare const store: {
get(key: string): Promise;
put(
key: string,
value: string,
options: { expiresAt: number },
): Promise;
delete(key: string): Promise;
};
export const kvStorage: AuthStorage = {
get: async (key) => (await store.get(key)) ?? null,
// The store drops the session itself when it's no longer valid.
set: (key, value, { expiresAt }) => store.put(key, value, { expiresAt }),
remove: (key) => store.delete(key),
};
```
An `AuthStorage` needs three operations: `get`, `set` and `remove`. Here's
what to know about them:
- Each can return a promise. A `get` that answers synchronously lets a saved
session restore before the first render.
- `set` also receives `expiresAt`: when the saved session stops being valid,
`maxAge` after this save, in Unix milliseconds.
- The client runs your store's operations one at a time, in the order it
issued them, so a store that answers out of order is still safe.
- To report a failure, throw or reject. The client turns it into a
`PERSISTENCE_FAILED` error, and
[Handle storage failures](https://session-kit.pages.dev/docs/configuration/errors#handle-storage-failures)
explains what happens next.
A store that several tabs share needs two more members, as `webStorage()`
has. `subscribe` tells the client when another tab changes the session, so
that [tabs follow each other](https://session-kit.pages.dev/docs/configuration/tabs). `lock` lets the tabs
take turns to refresh. An optional `debug` member adds your store's own
events to the [debug log](https://session-kit.pages.dev/docs/configuration/debugging). See
[`AuthStorage`](https://session-kit.pages.dev/docs/reference/core#authstorage) for each member.
## What the client saves
The client saves the tokens and the user in one `:auth:session` entry.
Each save is then a single write, which other tabs see whole. A
[user read from the access token](https://session-kit.pages.dev/docs/client/users-from-tokens) isn't
saved. The client reads it from the token again on restore.
## Next steps
- [Tabs](https://session-kit.pages.dev/docs/configuration/tabs): see how tabs that share `localStorage`
stay in step.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors#handle-storage-failures): decide what
to show when storage can't be read, written or cleared.
- [Security](https://session-kit.pages.dev/docs/security): compare how each place protects the tokens.
# Tabs (https://session-kit.pages.dev/docs/configuration/tabs)
Users open your app in several tabs, then sign out in one and expect the
others to follow. In a browser with `webStorage()`, which saves the session
in `localStorage`, each open tab runs its own client over the same saved
session, and the tabs keep each other in step.
This page shows what tabs share, how they take turns to refresh, and the
setups where tabs don't follow each other.
## How tabs stay in step
While the client is [mounted](https://session-kit.pages.dev/docs/client), each tab follows the changes
the others save:
- A sign-out in one tab signs out every tab.
- A sign-in or an account switch switches every tab.
- A profile update or a refresh shows in every tab.
A tab hears about these through the browser's `storage` events, which the
store's `subscribe` member listens to. A tab that mounts again checks the
saved session, so it catches up on anything it missed while unmounted.
Tabs share a session only when they share the store:
- **`webStorage({ area: "session" })`** gives each tab its own
`sessionStorage`, so each tab has its own session and nothing to follow.
- **`memoryStorage()`** keeps the session in one page, and no other tab can
read it.
- **Your own store** needs a `subscribe` member that reports other tabs'
changes, as [Storage](https://session-kit.pages.dev/docs/configuration/storage#write-your-own-store)
explains.
## One refresh at a time
Tabs that share a session also share its refresh token. The client refreshes
under the `:auth:refresh`
[Web Lock](https://developer.mozilla.org/docs/Web/API/Web_Locks_API), through
the store's `lock` member. One tab at a time spends the refresh token, and
the others reuse the tokens it saved. Rotating refresh tokens therefore work
with several tabs open.
Without Web Locks, two tabs that refresh at the same instant can both spend
the token. A short reuse window on your backend covers that case.
## Server rendering
With server rendering, the session lives in a cookie, and the browser's
`createMirrorAuth` clients don't use storage events. When one tab signs in or
out, it tells the others over a `BroadcastChannel`, and they ask the server
for the session again. [Server rendering](https://session-kit.pages.dev/docs/server-rendering) has the
rest.
## Locking
With [`locking`](https://session-kit.pages.dev/docs/client/locking), tabs stop following each other. A
sign-in, sign-out or lock in one tab doesn't reach the others. With rotating
refresh tokens, two tabs that refresh the same session can sign one of them
out. Locking is meant for native apps, which have no tabs.
## Expo apps
An Expo app has one JavaScript context, so it has no tabs to follow and
needs no lock. `secureStorage()` has no `subscribe` or `lock` member for
that reason.
## Next steps
- [Storage](https://session-kit.pages.dev/docs/configuration/storage): choose a store, or write one that
several tabs can share.
- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh): see when a refresh runs, and what
happens when it fails.
- [Server rendering](https://session-kit.pages.dev/docs/server-rendering): keep the session on the server
instead.
# Errors (https://session-kit.pages.dev/docs/configuration/errors)
Sooner or later a refresh fails because your backend is down, or the browser
refuses to save the session. Your app needs to notice, and tell the user
something useful. Every error from Session kit's own logic is an
`AuthError`, with a `code` you can match on.
This page shows where errors appear, how to turn them into messages, and the
failures that need a decision from you.
## Where errors appear
A failure shows up in one of two places, or in both:
- **The call rejects** when you asked for something the client couldn't do,
such as `signIn` with a user your schema rejects.
- **`state.error` shows it** when the session itself is affected, such as a
refresh that failed. Your components read it with `useAuth`, so it reaches
the screen even when no call of yours was waiting.
Here's where each common failure appears:
| When… | The call rejects | `state.error` shows it |
| ------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------- |
| `signIn` or `updateUser` gets a user the schema rejects | Yes | No |
| `unlock()` fails with `UNLOCK_FAILED` | Yes | No |
| An early refresh fails in the background | No call is waiting | Yes |
| A refresh the session needed fails | Yes, every call waiting for it, such as `getSession()` or `authFetch` | Yes |
| The saved session can't be read | Yes, every call that needs it, such as `getSession()` or `retry()` | Yes |
| The session can't be saved | Yes, the call that saved it, such as `signIn` | Yes |
| The saved session can't be cleared on sign-out | Yes, `signOut()` | Yes |
| `revoke` fails after a sign-out | No: `signOut()` resolves | Yes, `REVOKE_FAILED` |
| Another tab saves a user this tab's schema rejects | No call is waiting | Yes |
`state.error` holds the latest failure. The next successful change clears
it, such as a refresh that works, a sign-in or a sign-out. While a retry
runs, the error stays until the retry succeeds.
## Show errors to users
Match on an error's `code`, not its message, which can change in any
release. [Error codes](https://session-kit.pages.dev/docs/reference/error-codes) lists every code and what
it means. To keep wording out of your components, map codes to your own
messages:
```ts title="src/error-message.ts"
import { AuthError, type AuthErrorCode } from "@monarcode/session-kit";
const messages: Partial> = {
REFRESH_FAILED: "We can't reach the server. Check your connection.",
PERSISTENCE_FAILED: "We couldn't save or clear your session.",
UNAUTHENTICATED: "Sign in to continue.",
};
export function errorMessage(error: unknown): string {
if (error instanceof AuthError) return messages[error.code] ?? error.message;
return error instanceof Error ? error.message : "Something went wrong";
}
```
Then show `state.error` near the top of your app, with a way to try again
when access is `unavailable`:
```tsx title="src/session-alert.tsx"
import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
import { errorMessage } from "./error-message.js";
export function SessionAlert() {
const { status, error } = useAuth();
const client = useAuthClient();
if (!error) return null;
return (
);
}
```
`retry()` rejects again if it fails, and the new failure shows in
`state.error`, so the button can ignore the rejection.
An error's `cause` holds whatever failed underneath, such as the error your
refresh callback threw. Log it, or send it to your error reporting.
A few failures pass through unchanged, so they usually aren't `AuthError`s,
and `errorMessage` shows their own message:
- `authFetch` passes on the failures of `fetch` and `Request`, such as a
network error.
- With server rendering, the browser client's `signIn` passes on what your
sign-in function threw.
## Handle storage failures
Storage can fail: a full disk, a browser that blocks storage, or an iOS
keychain that's locked. Each of these three failures needs a decision from
you:
- **Storage can't be read.** `status` becomes `unavailable`, with the error
in `state.error`. The saved session stays as it is, and the next
`getSession()` or `retry()` reads it again. Show a **Try again** button
that calls `retry()`, as `SessionAlert` does.
- **Storage can't be written.** The client signs the user out, clears the
saved session, and publishes the error. That way, no one stays signed in
to a session that would vanish on reload. This happens on a refresh too,
when its new tokens can't be saved: on iOS, a refresh while the keychain is
locked signs the user out. Show the error, and let the user sign in again.
- **Storage can't be cleared.** Sign-out still takes effect in this tab, but
`signOut()` rejects and `state.error` keeps the error. The saved
credentials could restore the session on reload, so call `signOut()` again
after storage works again.
## Saved sessions the client can't use
Sometimes storage works, but the session it holds can't be used. When the
client restores such a session, it signs the user out and clears it:
- **A malformed saved session**, such as one edited by hand, gives
`INVALID_SESSION` in `state.error`.
- **A saved user your schema rejects**, such as after a deploy that changed
the schema, gives `USER_VALIDATION_FAILED` in `state.error`. See
[User schemas](https://session-kit.pages.dev/docs/configuration/user-schemas#change-the-schema-safely)
to avoid it.
- **A session past `maxAge`**, or saved in another format by an older or
newer version of Session kit, signs out with no error. Running out is
routine, as
[Storage](https://session-kit.pages.dev/docs/configuration/storage#how-long-a-saved-session-lasts)
explains.
In each case, the user signs in again.
## Next steps
- [Error codes](https://session-kit.pages.dev/docs/reference/error-codes): what each code means, and
which calls give it.
- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh#when-a-refresh-fails): what happens
when a refresh fails, and how long the failure lasts.
- [Debugging](https://session-kit.pages.dev/docs/configuration/debugging): log what the client did before
an error appeared.
# Debugging (https://session-kit.pages.dev/docs/configuration/debugging)
A user was signed out and you don't know why, or a refresh ran when you
didn't expect one. `createAuth`'s `debug` option reports what the client
does, so you can follow it step by step:
- restores, and refreshes with the reason they ran;
- timers;
- storage operations, and how long they took;
- other tabs' changes;
- state changes, and what ended a session.
This page shows how to log these events, send them to your error reporting,
and keep tokens out of them.
## Log to the console
To log each event as one `console.info` line, pass `debug: true`. To keep
logging out of production, pass a development flag instead, such as Vite's
`import.meta.env.DEV` or Expo's `__DEV__`.
Each line starts with `[session-kit:] : `, where
`` is your client's `name`. Any details follow as an object, which the
console formats. For example, a sign-in followed by an early refresh logs
lines like these in Node.js, among others:
```text
[session-kit:my-app] sign-in: signed in { sessionId: '54940f07-…' }
[session-kit:my-app] timer: early refresh fired
[session-kit:my-app] refresh: started (proactive) {
sessionId: '54940f07-…',
reason: 'proactive'
}
[session-kit:my-app] refresh: saved new tokens {
sessionId: '54940f07-…',
durationMs: 3,
expiresInMs: 900000
}
```
A browser console shows the same lines, with each object ready to expand.
## Send events to your error reporting
To receive each event instead of logging it, pass a function. For example,
to leave breadcrumbs in your error reporting:
```ts title="src/debug.ts"
import type { AuthDebug } from "@monarcode/session-kit";
declare function addBreadcrumb(crumb: {
category: string;
message: string;
data: object;
}): void;
/** Pass as `createAuth`'s `debug` option. */
export const debug: AuthDebug = (event) =>
addBreadcrumb({
category: `auth.${event.type}`,
message: event.message,
data: { ...event.data, code: event.error?.code },
});
```
## Keep tokens and user data out
By default, events leave out tokens, saved values and the user's fields. A
session appears as its `sessionId`, and an error as its code and message,
without its `cause` or `issues`.
To include them, pass `{ sensitive: true }`. Anyone who reads such logs can
act as the user, so keep it to development builds. To set both, pass
`{ log, sensitive }`, where `log` is your function.
## Filter on the event type
An event's `type` is one of a fixed set, such as `"refresh"` or `"storage"`,
so you can filter on it. [`AuthDebugType`](https://session-kit.pages.dev/docs/reference/core#authdebugtype)
lists them all. The wording of `message` and the fields in `data` can change
in any release, so read them, but don't match on them.
A store can add its own events through the optional `debug` member of
[`AuthStorage`](https://session-kit.pages.dev/docs/reference/core#authstorage). They arrive with the type
`"storage"`, beside the client's own storage events. `secureStorage()` uses
it to report, for example, a saved session it removed after a reinstall, as
the [Expo guide](https://session-kit.pages.dev/docs/setups/expo#debugging) shows.
## Next steps
- [Errors](https://session-kit.pages.dev/docs/configuration/errors): show the failures the log reports to
your users.
- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh): see when each kind of refresh runs.
- [`AuthDebugEvent` reference](https://session-kit.pages.dev/docs/reference/core#authdebugevent): every
field an event carries.
# Overview (https://session-kit.pages.dev/docs/server-rendering)
When your app renders pages on the server, with TanStack Start, Next.js or
React Router's framework mode, the first page should already show who is
signed in. Session kit does that by keeping the session on the server. Both
tokens and the user sit in a sealed cookie: it's encrypted with your secret,
so only your server can read or change it. These docs call this server
custody: the server holds the tokens, and by default the browser holds only
who is signed in.
The cookie is `httpOnly`, so page scripts can't read it, and they never see
the refresh token. The server reads the session before rendering, and the
browser's client starts from it, so pages never show a "Checking session…"
state. This page shows how the pieces fit, then sends you to your
framework's guide.
## How the pieces fit
Three pieces work together:
- **The server engine.** `createServerAuth` from
`@monarcode/session-kit/server` seals the cookie with your secret and
refreshes the tokens with your backend. It's the same call in every
framework.
[Create the server engine](https://session-kit.pages.dev/docs/setups/tanstack-start#1-create-the-server-engine)
on the TanStack Start page shows one.
- **A request's session.** Each framework's adapter gives your server code
the session of the request it's handling, and middleware that refreshes
the tokens before rendering. Your server code signs in with your backend
and calls your API through it. It's shaped like a client, so code written
for one, such as `createAuthFetch` or Effect's `Auth`, takes it.
- **The browser's client.** `createMirrorAuth` makes a client that mirrors
the session the server rendered. `AuthProvider`, the hooks and the route
guards work with it.
The browser's client reaches your server in three ways:
1. It reads the session with a `GET` to the session route: a route in your
app that the browser's client calls to read the session, sign out and get
the access token. Each adapter's `sessionRoute` makes it. In TanStack
Start, a server function reads the session instead, because the server
render reads it too, and a route can't be called from there.
2. It signs out, and gets the access token, with a `POST` to the session
route.
3. It signs in through your own server function or action, as in
[Create the browser client](https://session-kit.pages.dev/docs/setups/tanstack-start#4-create-the-browser-client).
Your server code calls your API with the request's access token. To call
your API from the browser too, opt in with `clientCredentials`, as
[The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser)
explains.
## Frameworks
What differs between frameworks is how server code gets a request's
session, which guards protect pages, and how the session reaches the
browser:
| Framework | On the server | Guards | In the browser | Guide |
| ------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- |
| TanStack Start | `startAuth(serverAuth)`, with `refreshSession` in request middleware | `requireSession` and `redirectIfSignedIn` from `@monarcode/session-kit/tanstack-router` | `connectSession` and `loadSession` | [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start) |
| Next.js 16, App Router | `nextSession(serverAuth, { cookies, redirect })`, with its `refresh` in Proxy | `session.require` and `session.redirectIfSignedIn`, from `nextSession` | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](https://session-kit.pages.dev/docs/setups/next) |
| React Router framework mode, with SSR | `routerAuth(serverAuth)`, with `sessionMiddleware` in the root route | `requireSession` and `redirectIfSignedIn` from `@monarcode/session-kit/react-router/server` | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](https://session-kit.pages.dev/docs/setups/react-router-ssr) |
For a server or framework without an adapter, see
[Servers without an adapter](https://session-kit.pages.dev/docs/server-rendering/server-sessions#servers-without-an-adapter).
## The browser's client
The client from `createMirrorAuth` is a mirror client: it follows the
session your server keeps, and holds no tokens of its own. It has the same
`state`, `getSession`, `isCurrent`, `signOut` and `credentials` as a client
from `createAuth`. `AuthProvider`, the hooks, the route guards,
`createAuthFetch` and effetch's `sessionBearer` all take it.
It differs from a `createAuth` client in a few ways:
- **Two statuses.** Its `status` is only ever `authenticated` or
`unauthenticated`. It starts from the rendered session, and the server
does the refreshing. When asking the server fails, the error shows in
`state.error`, and the session stays as it was.
- **`retry()` and `refresh()` ask the server again.** They read the session
from your server, which refreshes the tokens itself.
- **`signIn` only with the `signIn` option.** The option calls your own
server function. Without it, call your function, then pass the session it
returns to `adopt`.
- **No `lock`, `unlock` or `updateUser`.**
[Locking isn't available](https://session-kit.pages.dev/docs/server-rendering/server-sessions#limits)
with server rendering.
### Change the signed-in user
To change the user, such as after a profile edit, call the request's
`updateUser` on the server, in a server function or an action. Then pass the
session it resolves to the browser client's `adopt`. The client takes it,
runs the route guards again and tells other tabs.
With `useMirrorAuth`, a new server render brings the session too, such as
when React Router runs the loaders again after an action, or
`router.refresh()` renders a Next.js page again. The client takes the new
session. With `fromAccessToken`, there's no `updateUser`: the user comes from
the access token. [Updating the user](https://session-kit.pages.dev/docs/client/updating-the-user) covers
what `updateUser` takes.
### How tabs stay in step
Every tab sends the same cookie, so they all share one session on the
server. What each tab needs is to show the latest one. When a tab signs in,
signs out or adopts a changed session, its client tells the other tabs over a
`BroadcastChannel` named `:auth`. Each of them then asks your server
for the session.
A tab that comes back into view asks your server again too, unless the
server answered it in the last 10 seconds. When the answer differs, the tab
follows it:
- **TanStack Start:** `connectSession` runs the route guards again.
- **Next.js and React Router:** `useMirrorAuth` calls `onChange`, which
renders on the server again, with `router.refresh()` or `revalidate`.
The client listens while it's mounted. `AuthProvider` and the router
adapters mount it for you. [Tabs](https://session-kit.pages.dev/docs/configuration/tabs) covers tabs for
sessions saved in the browser.
## Next steps
- Follow the guide for your framework in the table, from installation to
calling your API.
- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): the cookie and
its secret, refreshing before rendering, signing out and limits.
- [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid): sign in with your backend
from the browser and call your API there, with the session still on the
server.
# Server sessions (https://session-kit.pages.dev/docs/server-rendering/server-sessions)
Your server-rendered app signs in and renders the signed-in page. Before you
deploy it, you need to know where the session lives, how to keep and rotate
its secret, what happens when a page can't set cookies, and what signing out
ends. Those answers are the same in TanStack Start, Next.js and React
Router, so they live on this page.
Read it after your app works. The setup guides show the code:
[TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start), [Next.js](https://session-kit.pages.dev/docs/setups/next)
and [React Router with server rendering](https://session-kit.pages.dev/docs/setups/react-router-ssr).
## The cookie
`createServerAuth` from `@monarcode/session-kit/server` keeps both tokens
and the user in a sealed cookie: it's encrypted with AES-256-GCM through Web
Crypto, with a key derived from your secret, so only your server can read or
change it.
The cookie is named after the `name` option: `app.session` in these docs.
A session too large for one cookie is split across `app.session.0` and
`app.session.1`, and `app.session` then only marks the split. If a proxy or
CDN passes on only the cookies it knows, give it all three names.
The cookie is `httpOnly`, so page scripts can't read it. It's also `Secure`,
`SameSite=Lax` and sent to every path, unless you pass other `cookie`
options.
It lasts for `maxAge` seconds, 30 days by default. Each save starts that
again: a sign-in, a refresh or an `updateUser`. When it runs out, the browser
drops the cookie, and the user is signed out.
`createServerAuth` takes the options `createAuth` does, except `storage` and
`locking`, plus `secret`, `cookie` and `clientCredentials`. Keep the module
that creates it on the server. Each setup guide shows how its framework keeps
such a module out of the browser bundle.
## The secret
The secret is the key that seals the cookie. Use 32 or more random
characters, kept in an environment variable such as `SESSION_SECRET`. To make
one, run `openssl rand -base64 32`.
`createServerAuth` checks the secret when a method first runs, not when the
module loads. So build steps that import the module without the secret, such
as `next build`, still work. Your module still reads
`process.env.SESSION_SECRET` when it loads. On Cloudflare Workers,
`process.env` holds the secret at that point when Node.js compatibility is on
and the compatibility date is 2025-04-01 or later. Otherwise, read it with
`import { env } from "cloudflare:workers"`, which also works at the top of a
module.
A missing or wrong secret shows up on the first request:
- **Without a valid secret,** every method rejects with `INVALID_OPTIONS`,
and a request's `state` is `unavailable`. The session route (the route in
your app that the browser's client calls to read the session and sign
out) answers 500 with `INVALID_OPTIONS`, so your monitoring sees it.
- **A cookie that no secret opens** reads as signed out. Where the request
can set cookies, the cookie is also deleted. So putting back a secret you
removed doesn't bring back the sessions it sealed.
### Rotate the secret
To change the secret without signing everyone out, pass a list. The first
secret seals new cookies, and any of them opens one. For example, to read the
old secret from `OLD_SESSION_SECRET` only while it's set:
```ts title="src/auth/server.ts"
import { createServerAuth } from "@monarcode/session-kit/server";
import { z } from "zod";
const secrets = [process.env.SESSION_SECRET, process.env.OLD_SESSION_SECRET];
export const serverAuth = createServerAuth({
name: "app",
user: z.object({ id: z.number(), firstName: z.string() }),
// A secret that isn't set is left out, so rotating only changes the env.
secret: secrets.filter((secret) => secret !== undefined),
});
```
Then rotate in four steps:
1. Set `OLD_SESSION_SECRET` to the current secret.
2. Set `SESSION_SECRET` to a new one, made with `openssl rand -base64 32`.
3. Deploy. New cookies are sealed with the new secret, and each save moves a
session onto it. Cookies sealed with the old secret still open.
4. After `maxAge` has passed since the deploy, 30 days by default, remove
`OLD_SESSION_SECRET`. By then, every cookie it sealed has expired.
## A request's session
Your server code reads and changes the session through one request's
session (`RequestAuth`). It has every `serverAuth` method, without the
request's cookies to pass. Each adapter gives it to you:
- **TanStack Start:** `startAuth(serverAuth)`, made once at module level.
Each call finds the request Start is handling.
- **React Router:** `routerAuth(serverAuth)` makes a function you call with
a loader's, action's or middleware's `context`.
- **Next.js:** `nextSession(serverAuth, { cookies, redirect })`. Its
`writable()` gives the request's session in Server Functions and Route
Handlers, and `readOnly()` in Server Components.
- **Servers without an adapter:** `serverAuth.forRequest(jar)`, over the
request's cookie jar. See
[Servers without an adapter](#servers-without-an-adapter).
It's shaped like a client, so code written for one works on the server with
it. `createAuthFetch(session, { baseUrl })` sends the cookie's access token,
and saves a renewed one after a 401. Effect's `Auth.layer` takes it too: see
[Use Effect on the server](https://session-kit.pages.dev/docs/effect/server).
## Requests that can't set cookies
Some requests can't change the cookie:
- **Next.js:** a Server Component rendering.
- **React Router:** a loader after its response has left the middleware,
such as deferred data that reads the session while the page streams.
- **TanStack Start:** a page that has started streaming. Start gives no
sign of it, so a cookie set then is lost. A refresh at that point would
spend the refresh token and drop the new one.
In Next.js and React Router, where Session kit can tell, the request's
session saves nothing:
- `signIn`, `signOut`, `updateUser` and `refreshIfDue` reject with
`INVALID_OPTIONS`.
- `getSession` still resolves, with the session as the cookie holds it.
- `credentials.get` rejects with `REFRESH_FAILED` after the access token has
expired, since a refreshed one couldn't be saved.
The way around all three cases is to refresh first, while the response can
still set the cookie.
## Refresh before rendering
Each setup refreshes in middleware that runs before any route reads the
session. Here's the middleware for each:
| Setup | Refreshes with |
| -------------------------- | ----------------------------------------------------------------- |
| TanStack Start | `refreshSession(serverAuth)`, in request middleware |
| React Router | `sessionMiddleware(serverAuth)`, in the root route |
| Next.js | `session.refresh(request, response)` from `nextSession`, in Proxy |
| Servers without an adapter | `serverAuth.refreshIfDue(jar)`, before rendering |
The middleware refreshes when the access token expires within 60 seconds, so
it lasts through the request. A token that lives a minute or less would be
refreshed on every request, so pass a smaller `within` for it, such as
`refreshSession(serverAuth, { within: 15 })`. `sessionMiddleware` takes
`within` the same way, and `nextSession` in its options.
What else the middleware does:
- **It refreshes at most once per request.** Calls during the request share
that refresh.
- **A failed refresh doesn't fail the request.** While the access token
still works, the failure is ignored. After it expires, routes read the
session as usual, and the error reaches the route's error component or
error boundary.
- **It keeps shared caches out.** A page that reads the session differs per
user. `refreshSession` and `sessionMiddleware` send
`Cache-Control: private, no-store` with each response that doesn't set its
own, so a CDN or proxy doesn't cache it. Pass `cacheControl` for another
value, or `{ cacheControl: false }` to leave every response as it is.
`nextSession`'s `refresh` doesn't set the header: the
[Next.js](https://session-kit.pages.dev/docs/setups/next) guide says how Next caches pages that read the
session.
## Refreshes across requests and servers
Parallel requests to one instance that carry the same cookie share one
refresh. For 10 seconds afterwards, a request that still carries the old
cookie gets the new tokens rather than refreshing again. A refresh that
fails at your backend is shared too: for 10 seconds, requests that carry that
cookie reject with its error rather than call your backend again.
An instance is one `createServerAuth` call, and instances share nothing. A
framework may make several on one server, one per bundle. Separate
processes, servers and serverless functions are separate instances too. With
rotating refresh tokens, give your backend a short reuse window, so that two
instances that refresh the same session don't sign it out.
## Sign-out
A request's `signOut` clears the cookie in this browser, then calls your
`revoke` and waits for it. A failed `revoke` doesn't make `signOut` reject.
The browser's client signs out through the session route, which calls it for
you.
The cookie holds the whole session, and the server keeps no list of
sessions. So a copy of the cookie made before sign-out still reads as signed
in. For 10 seconds, the instance that signed out treats such a copy as signed
out, as it treats an old cookie after a refresh. After that, the copy works
for as long as its tokens do.
`revoke` is what ends the session. Have your backend revoke the refresh token
there, so a copy can't refresh. Keep access tokens short-lived too: your
backend accepts one until it expires, unless it checks for revocation.
## The access token in the browser
Server code calls your API with a request's `credentials`. To call your API
from the browser too, with `createAuthFetch` or effetch's `sessionBearer`,
pass `clientCredentials: true` to `createServerAuth`. The session route then
serves the access token, and the browser's client gets it there.
Here's how the token behaves in the browser:
- Page scripts hold the access token in memory, never the refresh token.
The client asks for a new one shortly before it expires.
- After a 401, the client asks the session route for a new token, and the
server refreshes with the cookie's refresh token.
- Without `clientCredentials`, the session route answers 500, and the
client's `credentials.get()` rejects with `INVALID_OPTIONS`.
- Without a session route, such as when your client calls server functions,
pass `createMirrorAuth`'s `credentials` option: two functions that call a
request's `clientCredentials.get` and `clientCredentials.renew` on the
server.
A script injected into your page can then use your API while the page is
open, as it could with any token the browser holds. The session route
answers your own site's pages only: see
[The session route](https://session-kit.pages.dev/docs/security#the-session-route).
## Servers without an adapter
On a server with no adapter, such as a plain `fetch` handler that takes a
`Request` and returns a `Response`, you wire the same pieces yourself. Every
`serverAuth` method also takes the request's cookie jar
([`CookieJar`](https://session-kit.pages.dev/docs/reference/server#cookiejar)) first.
`serverAuth.getSession(jar)` does what a request's `getSession()` does, and
`serverAuth.forRequest(jar)` gives that request's session.
### 1. Build a cookie jar for each request
The jar reads the request's `Cookie` header and collects the `Set-Cookie`
lines for the response:
```ts title="src/server/cookie-jar.ts"
import type { CookieJar, CookieOptions } from "@monarcode/session-kit/server";
function setCookie(name: string, value: string, options: CookieOptions) {
return [
`${name}=${value}`,
`Path=${options.path}`,
`Max-Age=${options.maxAge ?? 0}`,
`SameSite=${options.sameSite}`,
...(options.domain ? [`Domain=${options.domain}`] : []),
...(options.secure ? ["Secure"] : []),
"HttpOnly",
].join("; ");
}
/** One request's cookie jar, and a function that answers with its cookies. */
export function cookieJar(request: Request) {
const cookies = new Map();
for (const pair of request.headers.get("Cookie")?.split(";") ?? []) {
const equals = pair.indexOf("=");
const name = pair.slice(0, equals).trim();
if (equals > 0 && !cookies.has(name))
cookies.set(name, pair.slice(equals + 1).trim());
}
const written = new Map();
let answered = false;
const jar: CookieJar = {
get writable() {
return !answered;
},
get: (name) => cookies.get(name),
set: (name, value, options) =>
written.set(name, setCookie(name, value, options)),
delete: (name, options) =>
written.set(name, setCookie(name, "", { ...options, maxAge: 0 })),
};
function respond(response: Response) {
answered = true;
for (const line of written.values())
response.headers.append("Set-Cookie", line);
return response;
}
return { jar, respond };
}
```
Make a new jar for each request. Calls with the same jar share what it read
and wrote, and one refresh, so a jar kept at module level would show one
request's session to the next. After `respond`, the jar's `writable` is
`false`, which tells Session kit that the request can't set cookies any more.
### 2. Answer the session route, then render
`sessionHandler(serverAuth)` answers the session route. For a page, refresh
first, then read the session and render with it:
```ts title="src/server/handle.ts"
import { sessionHandler } from "@monarcode/session-kit/server";
import { serverAuth } from "../auth/server.js";
import { cookieJar } from "./cookie-jar.js";
import { renderPage } from "./render.js";
const handleSession = sessionHandler(serverAuth);
export async function handle(request: Request): Promise {
const { jar, respond } = cookieJar(request);
if (new URL(request.url).pathname === "/api/session")
return respond(await handleSession(request, jar));
// While the response can still set the cookie. A failure is ignored
// here: getSession rejects if the access token has expired.
await serverAuth.refreshIfDue(jar).catch(() => {});
const session = await serverAuth.getSession(jar);
const page = await renderPage(session);
// The page differs per user, so no shared cache may keep it.
if (!page.headers.has("Cache-Control"))
page.headers.set("Cache-Control", "private, no-store");
return respond(page);
}
```
Without an adapter, nothing marks the response as private, so set
`Cache-Control` yourself, as the adapters' middleware does
([Refresh before rendering](#refresh-before-rendering)).
`renderPage` is your app's own server render. It puts the session in the
page, as frameworks do with a loader's data, so the browser's client can
start from it.
### 3. Create the browser's client
In the browser, create the client from the session the page was rendered
with, once per page load:
```ts title="src/auth/client.ts"
import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit";
// Types only: left out of the browser's bundle.
import type { serverAuth } from "./server.js";
export type AppSession = SessionOf;
export function createAppAuth(session: AppSession | null) {
return createMirrorAuth({ name: "app", session, endpoint: "/api/session" });
}
```
With React, create it with `useMirrorAuth` from
`@monarcode/session-kit/react`, and render `AuthProvider` with it. Its
`onChange` runs when the session changes in the browser, so you can render
the page on the server again.
## Limits
- **Size.** The cookie can take about 7.5 KB across its two parts, since
servers and proxies refuse larger request headers (nginx: 8 KB for the
`Cookie` line, shared with the site's other cookies), and go on refusing
every page until the cookie is cleared. That holds about 5.5 KB of tokens
and user before encryption. A larger session rejects at sign-in with
`PERSISTENCE_FAILED`, so keep the user small. An `updateUser` or a refresh
that outgrows the cookie rejects the same way, and signs the user out.
- **Plain http.** The cookie is `Secure` by default. Browsers accept that on
`http://localhost`, except Safari: pass `cookie: { secure: false }` for
local development there, never in production.
- **Locking.** `locking` isn't available. The server keeps the tokens, so
there's nothing on the device to lock.
## Next steps
- [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid): sign in with your backend
from the browser, and call your API there.
- [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run Effects with a
request's session.
- [Security](https://session-kit.pages.dev/docs/security): what Session kit protects, and what stays your
backend's job.
- [`createServerAuth` reference](https://session-kit.pages.dev/docs/reference/server#createserverauth):
every option and method.
# Hybrid setup (https://session-kit.pages.dev/docs/server-rendering/hybrid)
Sometimes your backend's sign-in has to run in the browser, such as through
a provider's SDK, or your pages call your API themselves. A hybrid setup
lets the browser do both, while the server still keeps the session in its
sealed cookie (encrypted with your secret, so only your server can read
it), refreshes it, and renders who is signed in.
Two things change from a server-rendered setup:
- **Signing in.** The browser gets the tokens from your backend and sends
them to a server function, which seals them into the cookie with
`session.signIn`.
- **Calling your API.** The session route (the route in your app that the
browser's client calls to read the session and sign out) gives the browser
the access token, and `createAuthFetch` sends it. The refresh token stays
in the cookie.
This page builds on the [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start) guide.
[Other frameworks](#other-frameworks) lists what changes with Next.js and
React Router.
## Before you begin
- Follow the [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start) guide through
step 7. This page replaces four of its files: `src/auth/server.ts`,
`src/auth/functions.ts`, `src/auth/client.ts` and `src/sign-in.ts`. The
rest stays as it is, including the sign-in route, which calls
`src/sign-in.ts`.
- Your backend must allow requests from your site (CORS) for its sign-in
and for the API calls the browser makes. Session kit's own requests go to
your session route, on your site.
## 1. Let the session route serve the access token
`clientCredentials: true` lets the session route give the access token to
your own pages. Here's the guide's `src/auth/server.ts` with that option,
and without its `login`, which moves to the browser in the next step:
```ts title="src/auth/server.ts"
import "@tanstack/react-start/server-only";
import { createServerAuth } from "@monarcode/session-kit/server";
import { startAuth } from "@monarcode/session-kit/tanstack-start/server";
import { z } from "zod";
export const API = "https://dummyjson.com";
const userSchema = z.object({ id: z.number(), firstName: z.string() });
const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() });
export const serverAuth = createServerAuth({
name: "app",
user: userSchema,
secret: process.env.SESSION_SECRET!,
// The session route gives the access token to your own pages.
clientCredentials: true,
refresh: async ({ refreshToken, signal }) => {
const response = await fetch(`${API}/auth/refresh`, {
method: "POST",
signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
// DummyJSON rejected the refresh token: sign out.
if (response.status === 401 || response.status === 403) return null;
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return tokens.parse(await response.json());
},
});
/** The session of the request Start is handling, found on each call. */
export const session = startAuth(serverAuth);
```
## 2. Sign in with your backend in the browser
The browser calls your backend's sign-in, and gets the tokens and the user:
```ts title="src/backend.ts"
import { z } from "zod";
export const API = "https://dummyjson.com";
const tokensSchema = z.object({
accessToken: z.string(),
refreshToken: z.string(),
});
export const userSchema = z.object({ id: z.number(), firstName: z.string() });
export type LoginResult = Awaited>;
/** Signs in with your backend, from the browser. */
export async function login(username: string, password: string) {
const response = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (!response.ok) throw new Error(`Sign-in failed (${response.status})`);
const body: unknown = await response.json();
return { ...tokensSchema.parse(body), user: userSchema.parse(body) };
}
```
## 3. Send the tokens to the server
`session.signIn` seals what it's given, and never asks your backend. So the
server function decides what to trust. Check the tokens first, unless the
cookie's user is only ever shown.
### Check the tokens first
The server function takes the tokens only, and asks your backend whose they
are. A forged or expired access token is refused, and the cookie's user
comes from your backend, not from the browser. The refresh token isn't
checked until the first refresh:
```ts title="src/auth/functions.ts"
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { API, userSchema } from "../backend";
import { session } from "./server";
export const getSessionFn = createServerFn().handler(() =>
session.getSession(),
);
export const signInFn = createServerFn({ method: "POST" })
.validator(z.object({ accessToken: z.string(), refreshToken: z.string() }))
.handler(async ({ data }) => {
// Your backend proves the access token is real, and says whose it is.
const response = await fetch(`${API}/auth/me`, {
headers: { Authorization: `Bearer ${data.accessToken}` },
});
if (!response.ok) throw new Error("Your backend refused the token");
const user = userSchema.parse(await response.json());
return session.signIn({ ...data, user });
});
```
The client's `signIn` takes what your backend's sign-in returned, and sends
only the tokens to `signInFn`:
```ts title="src/auth/client.ts"
import { createMirrorAuth } from "@monarcode/session-kit";
import type { LoginResult } from "../backend";
import { getSessionFn, signInFn } from "./functions";
export function createAppAuth() {
return createMirrorAuth({
name: "app",
session: null, // filled by loadSession, then by hydration
endpoint: "/api/session",
revalidate: () => getSessionFn(),
signIn: ({ accessToken, refreshToken }: LoginResult) =>
signInFn({ data: { accessToken, refreshToken } }),
});
}
export type AppAuth = ReturnType;
```
The form signs in with your backend, then with the client. The sign-in
page's guard sends the user on, so the form doesn't navigate:
```ts title="src/sign-in.ts"
import type { AppAuth } from "./auth/client";
import { login } from "./backend";
/** Signs in, and resolves the message to show when it fails. */
export async function signIn(
auth: AppAuth,
username: string,
password: string,
): Promise {
try {
await auth.signIn(await login(username, password));
return null;
} catch (error) {
return error instanceof Error ? error.message : "Could not sign in";
}
}
```
With `fromAccessToken` as the server's `user` option, the server reads the
user from the access token instead. Give it a `decode` that verifies the
token's signature, and that's the check: see
[Verify the token on a server](https://session-kit.pages.dev/docs/client/users-from-tokens#verify-the-token-on-a-server).
### Pass the tokens without a check
If the cookie's user is only ever shown, the server function can take the
tokens and the user the browser sends, and seal them as they are:
```ts title="src/auth/functions.ts" app="trusting"
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { userSchema } from "../backend";
import { session } from "./server";
export const getSessionFn = createServerFn().handler(() =>
session.getSession(),
);
export const signInFn = createServerFn({ method: "POST" })
.validator(
z.object({
accessToken: z.string(),
refreshToken: z.string(),
user: userSchema,
}),
)
.handler(({ data }) => session.signIn(data));
```
The client's `signIn` then sends everything your backend's sign-in
returned. `src/sign-in.ts` stays as it is:
```ts title="src/auth/client.ts" app="trusting"
import { createMirrorAuth } from "@monarcode/session-kit";
import type { LoginResult } from "../backend";
import { getSessionFn, signInFn } from "./functions";
export function createAppAuth() {
return createMirrorAuth({
name: "app",
session: null, // filled by loadSession, then by hydration
endpoint: "/api/session",
revalidate: () => getSessionFn(),
signIn: (result: LoginResult) => signInFn({ data: result }),
});
}
export type AppAuth = ReturnType;
```
Anyone can then put any user in their own cookie, with tokens of their own.
That's safe only when the cookie's user is shown, never trusted:
- **Your backend authorizes every request** with the access token, and
nothing on your server acts on `session.user` alone, such as reading
another account's data by its `id`.
- **A forged token gets nowhere.** Your API refuses it. At the first
refresh, your backend refuses its refresh token too, and a `refresh` that
returns `null` for that, as this guide's does, signs the user out.
When in doubt, check the tokens first. It costs one request at sign-in.
## 4. Call your API from the browser
`createAuthFetch` from `@monarcode/session-kit/http` sends the access token
that the session route serves. Make one per client, since the client is made
once per page load:
```tsx title="src/orders.tsx"
import { useMemo, useState } from "react";
import { createAuthFetch } from "@monarcode/session-kit/http";
import { useAuthClient } from "@monarcode/session-kit/tanstack-router";
export function Orders() {
const auth = useAuthClient();
const authFetch = useMemo(
() => createAuthFetch(auth, { baseUrl: "https://dummyjson.com/" }),
[auth],
);
const [count, setCount] = useState(null);
async function load() {
// DummyJSON's carts stand in for your orders.
const response = await authFetch("auth/carts");
if (!response.ok) throw new Error(`Orders failed (${response.status})`);
const body: unknown = await response.json();
const carts = (body as { carts?: unknown } | null)?.carts;
setCount(Array.isArray(carts) ? carts.length : 0);
}
return (
);
}
```
After a 401, the client asks the session route for a new access token, and
the server refreshes with the cookie's refresh token.
[The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser)
says how the browser holds the token.
ky, axios and openapi-fetch can send their requests through `authFetch`:
see [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients). Server functions
can still call your API too, as the guide's
[Call your API](https://session-kit.pages.dev/docs/setups/tanstack-start#call-your-api) shows.
## Other frameworks
With Next.js or React Router, the steps are the same. What changes is where
each piece lives, and how the session reaches the browser after sign-in.
In the [Next.js](https://session-kit.pages.dev/docs/setups/next) guide's app:
- Add `clientCredentials: true` in `lib/auth/server.ts`.
- Have `signInAction` in `app/actions.ts` take the tokens, check them as in
step 3, and call `session.signIn`.
- The client in `lib/auth/client.ts` already reads the session through
`endpoint`, with no `revalidate`. Its `signIn` option calls
`signInAction` with the tokens.
- Components get the client with `useAuthClient` from
`@monarcode/session-kit/react`.
In the [React Router with server rendering](https://session-kit.pages.dev/docs/setups/react-router-ssr)
guide's app:
- Add `clientCredentials: true` in `app/auth/session.server.ts`.
- Give the sign-in route an action that takes the tokens, checks them as in
step 3, and calls `auth(context).signIn`.
- After your backend's sign-in, submit the tokens to that action from the
browser, such as with `useSubmit`. React Router runs the loaders again,
and `useMirrorAuth` takes the new session.
- Components get the client with `useAuthClient` from
`@monarcode/session-kit/react`.
## Things to know
- **The refresh token passes through page scripts during sign-in,** in
your backend's sign-in response, on its way to your server. Session kit's
client passes it on without keeping it, and never holds it again. A
provider's SDK may keep its own copy: check its storage settings. If your
backend's sign-in can run on the server, sign in there, as the setup
guides do.
- **Signing out** works as in the guide's
[Sign out](https://session-kit.pages.dev/docs/setups/tanstack-start#7-sign-out) step, through the
session route. To end the session at your backend too, give
`createServerAuth` a `revoke`.
## Next steps
- [Your backend decides what's allowed](https://session-kit.pages.dev/docs/security#your-backend-decides-whats-allowed):
what the cookie's user can be trusted for.
- [The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser):
how page scripts get and renew the access token.
- [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients): send ky, axios or
openapi-fetch requests through `authFetch`.
- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): the cookie, its
secret and the limits every server-rendered setup shares.
# Effect and effetch (https://session-kit.pages.dev/docs/effect)
If your app is written with [Effect](https://effect.website), your Effects
need the session too: who is signed in, and an access token for your API.
Session kit gives them both, from the same client that React and your
router use, so there's one session for all of them. Your API calls go
through [effetch](https://github.com/monarcode/effetch), with a plugin that
sends the token and gets a new one after a 401.
This page shows what the two entry points give you and where they differ
from the rest of Session kit. To set them up, follow
[Use Effect in the browser](https://session-kit.pages.dev/docs/effect/browser), then, with server
rendering, [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server).
## What `./effect` and `./effetch` give you
Two entry points connect Session kit to Effect:
- **`@monarcode/session-kit/effect`** gives your Effects the session as the
`Auth` service. It wraps the client you already have, so React, your
router and your Effects share one session. `Auth.layer(auth)` provides it.
- **`@monarcode/session-kit/effetch`** has the `sessionBearer` plugin for
effetch clients. It sends the access token with each call, and gets a new
one after a 401.
`effect` and `@monarcode/effetch` are optional peer dependencies.
[effetch-query](https://github.com/monarcode/effetch-query), which caches
each account's data, works with them but isn't needed.
### The `Auth` service at a glance
Here's what `Auth` gives your Effects:
| Member | What it does |
| ------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `Auth.layer(client)` | Provides the client, or on the server one request's session, as the `Auth` service. It doesn't mount it. |
| `Auth.session` | The current session, refreshed first if the access token expired. Fails with `UNAUTHENTICATED` when signed out. |
| `Auth.sessionOption` | The same, with `Option.none()` when no one is signed in. |
| `Auth.credentials` | The access token and session ID, for a request. |
| `Auth.renew(credentials)` | New credentials after your API rejected these. Calls at the same time share one refresh. |
| `Auth.signIn(input)` | Saves a new session, as the client's `signIn` does. |
| `Auth.signOut` | Signs out, as the client's `signOut` does. |
| `Auth.updateUser(input)` | Replaces the user with the one given, or with what an Effect fetches. |
| `Auth.changes` | A `Stream` of the client's state: the current state, then every change. |
| `Auth.fromAuthError` | Turns an `AuthError` from a client method `Auth` doesn't wrap into an `AuthFailure`. |
Register your client's type once, as
[Register the client](https://session-kit.pages.dev/docs/effect/browser#3-register-the-client) shows, so
these carry your user. The [`./effect` reference](https://session-kit.pages.dev/docs/reference/effect)
lists every failure.
## How Effects fail
Every `Auth` Effect fails with `AuthFailure`, a tagged error that
`Effect.catchTag("AuthFailure", …)` handles like your own errors. Its
`code` is the client's [`AuthErrorCode`](https://session-kit.pages.dev/docs/configuration/errors), such
as `UNAUTHENTICATED` or `REFRESH_FAILED`. Its `cause` is the `AuthError`
itself.
Misuse, which the client reports as `INVALID_OPTIONS`, isn't an
`AuthFailure`. The Effect dies with it instead, as a defect: it's a mistake
in the code to fix, not a failure to handle. So `AuthFailure`'s `code` is
never `INVALID_OPTIONS`.
## Why `sessionBearer`, not effetch's `bearer`
effetch has a `bearer` plugin of its own, which can take its token and its
refresh from `Auth`. It's built for any token, though, so
it has no rules about where the token goes. Here's what `bearer` does that
`sessionBearer` doesn't:
- **It sends the token to any URL a call names.** An absolute URL skips the
client's `baseUrl`, and gets the token all the same.
- **It follows redirects,** so the token can follow one to another server.
- **It sends a `POST` again after a refresh,** and any other method that
got the 401.
- **It doesn't check the account.** A response to a request sent for an
account that has since signed out comes back as it is.
`sessionBearer` sends the token only to your API's origin, and with
Effect's `FetchHttpClient` it refuses redirects. It sends only a `GET` or
`HEAD` again, and fails with `SESSION_CHANGED` rather than return a response
meant for another account.
## How `sessionBearer` differs from `createAuthFetch`
`sessionBearer` follows the same rules as `createAuthFetch`, which
[Authenticated requests](https://session-kit.pages.dev/docs/client/requests) explains: when the token is
sent, what happens after a 401, and when the user is signed out after a
second one. Here's what's different with `sessionBearer`:
- **Failures are `AuthFailure`s,** in the Effect's error channel, rather
than a rejected `AuthError`.
- **A 401 it hands back is an `HttpError`.** Where `authFetch` resolves a
401 response, such as for a `POST` after a refresh, the call fails with
an `HttpError` whose `status` is 401. A client's `statusErrors` turns it
into your own error instead.
- **Another origin dies rather than fails.** A request for another origin,
or with a username or password in its URL, dies with `INVALID_OPTIONS`,
so `Effect.catch` and `Effect.catchTag` don't see it.
- **A redirect fails as a `Fetch.NetworkError`,** with Effect's
`FetchHttpClient`, rather than a `TypeError`. On React Native before Expo
SDK 58, `fetch` follows redirects whatever it's told, so the redirected
request has already gone out. `authFetch` still refuses the response, and
`sessionBearer` returns it. Don't let your API redirect requests that
carry a token.
- **A request that already has an `Authorization` header passes
through.** While signed in, `authFetch` replaces the header.
`sessionBearer` sends the request as it is, with no token, no refresh, and
none of the checks: not the origin or redirect check, and no
`UNAUTHENTICATED`, `LOCKED` or `SESSION_CHANGED`.
Streams, such as `api.sse` or a stream endpoint, go through the same checks
up to the response's headers. As with a body `authFetch` returns, one that's
open when the user signs out or switches accounts keeps reading until it
ends, so stop it yourself if it mustn't outlive the session.
The [`sessionBearer` reference](https://session-kit.pages.dev/docs/reference/effetch#sessionbearer)
lists its options.
## What `Auth` covers
`Auth` covers what Effect code does with a session: reading it, signing in
and out, and updating the user. Everything else stays on the client, which
React and the routers already drive: `lock` and `unlock`, `refresh` and
`retry`, `mount`, and the client's options. On the server, a request's
session signs in and updates the user with its own methods.
## On the server
With server rendering, `Auth.layer` takes one request's session, so
`Auth.session`, `Auth.credentials` and `sessionBearer` work in server
functions, actions and route handlers too. There, `sessionBearer` sends the
cookie's token, and saves a renewed one after a 401.
[Use Effect on the server](https://session-kit.pages.dev/docs/effect/server) sets it up, step by step.
## Cache with effetch-query
effetch-query caches what your endpoints return, with a client per account,
so no account sees another's data. Its React bindings need React 19.
[Cache with effetch-query](https://session-kit.pages.dev/docs/effect/browser#cache-with-effetch-query),
on the browser guide, sets it up.
## Next steps
- [Use Effect in the browser](https://session-kit.pages.dev/docs/effect/browser): set up `Auth`,
`sessionBearer` and the runtime in a single-page or Expo app.
- [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run Effects with each
request's session.
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): the 401 rules
`sessionBearer` shares with `createAuthFetch`.
# Use Effect in the browser (https://session-kit.pages.dev/docs/effect/browser)
Your app runs its logic as [Effect](https://effect.website) programs, and
they need to know who is signed in and to send the access token with every
API call. This guide sets that up in a single-page app or an Expo app. Your
Effects read the session as the `Auth` service, call your API with
[effetch](https://github.com/monarcode/effetch), and, if you want, cache each
account's data with
[effetch-query](https://github.com/monarcode/effetch-query).
The guide builds the app from [Getting started](https://session-kit.pages.dev/docs/getting-started) again,
with Effect Schemas and effetch. [Effect and effetch](https://session-kit.pages.dev/docs/effect) explains
the two entry points it uses. The browser half of this guide, with TanStack
Router and a user read from the access token, runs in
[`examples/tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa-effetch).
With server rendering, your framework's guide creates and registers the
browser's client in place of step 3. Build the layer and runtime of steps 4
and 7 where that client is created.
[Use Effect on the server](https://session-kit.pages.dev/docs/effect/server) covers the server's side.
## Before you begin
- Read [Getting started](https://session-kit.pages.dev/docs/getting-started).
[Refresh](https://session-kit.pages.dev/docs/configuration/refresh) and
[Errors](https://session-kit.pages.dev/docs/configuration/errors) explain how the client renews and
fails.
- Know Effect's generators, services and layers.
- Effect asks for TypeScript 5.9 or newer.
- To cache with effetch-query, you need React 19: its React bindings don't
support React 18. [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) lists
every version.
## Installation
To install the packages, run the following command:
```npm
npm install @monarcode/session-kit effect @monarcode/effetch
```
`effect` and `@monarcode/effetch` are optional peer dependencies of Session
kit. `./effect` and `./effetch` need `effect` 4.1 or newer, and `./effetch`
also needs `@monarcode/effetch` 0.1.0-rc.4 or newer. effetch-query has its
own install, in [Cache with effetch-query](#cache-with-effetch-query).
## 1. Describe your backend
Start with the backend from
[Getting started](https://session-kit.pages.dev/docs/getting-started#1-talk-to-your-backend), as Effect
Schemas: the user, the tokens, and the body DummyJSON explains a failure
with. The file holds schemas only, with no client, so the rest of the app
and the [server](https://session-kit.pages.dev/docs/effect/server) can import them from one place:
```ts title="src/backend.ts"
import * as Schema from "effect/Schema";
export const API_BASE_URL = "https://dummyjson.com";
export const SessionUser = Schema.Struct({
id: Schema.Finite,
username: Schema.String,
email: Schema.String,
firstName: Schema.String,
});
/** The user, as Session kit's `user` option takes it. */
export const userSchema = Schema.toStandardSchemaV1(SessionUser);
export const SessionTokens = Schema.Struct({
accessToken: Schema.String,
refreshToken: Schema.String,
});
/** DummyJSON returns the user's fields beside the tokens. */
export const SignInResponse = Schema.Struct({
...SessionTokens.fields,
...SessionUser.fields,
});
export const ApiError = Schema.Struct({ message: Schema.String });
```
## 2. Refresh with effetch
The refresh exchanges the refresh token for new tokens. It gets an effetch
client of its own, made with its own `Fetch.make`:
```ts title="src/refresh.ts"
import { Fetch } from "@monarcode/effetch";
import * as Effect from "effect/Effect";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as HttpClient from "effect/http/HttpClient";
import { API_BASE_URL, SessionTokens } from "./backend.js";
// Not the app's API client: its session plugin waits for this refresh.
const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }).pipe(
// No tracing headers, as for the API client in step 6.
Effect.provideService(HttpClient.TracerPropagationEnabled, false),
);
/** New tokens. `null` signs out; a failure keeps the session for a retry. */
export const refreshSession = (refreshToken: string, signal: AbortSignal) =>
Effect.runPromise(
Effect.gen(function* () {
const client = yield* makeRefreshClient;
return yield* client.post("/auth/refresh", {
body: { refreshToken },
output: SessionTokens,
});
}).pipe(
Fetch.catchStatus([401, 403], () => Effect.succeed(null)),
Effect.provide(FetchHttpClient.layer),
),
{ signal },
);
```
The refresh can't use the app's API client or its runtime, for two reasons:
- After a 401, the app's API client
[waits for a refresh](#6-call-your-api-with-effetch). A refresh sent
through it would wait for itself.
- The app's runtime is built on the session client this refresh belongs
to, so the refresh can't run in it. It provides its own
`FetchHttpClient`, which effetch sends requests with.
`refreshSession` resolves `null` when the backend rejects the refresh token,
which signs the user out. It fails for anything else, such as an outage, and
the session is kept for a retry. [Refresh](https://session-kit.pages.dev/docs/configuration/refresh)
explains both. The server uses this function too.
## 3. Register the client
Create the client as usual, then register its type once, so that every
Effect carries your user. The same registration types the hooks from
`@monarcode/session-kit/react`:
```ts title="src/auth.ts"
import { createAuth, webStorage } from "@monarcode/session-kit";
import { userSchema } from "./backend.js";
import { refreshSession } from "./refresh.js";
export const auth = createAuth({
name: "app",
user: userSchema,
storage: webStorage(),
refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal),
});
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
```
## 4. Provide the service
`Auth.layer` provides the client as the `Auth` service. Create the layer
once:
```ts title="src/layer.ts"
import { Auth } from "@monarcode/session-kit/effect";
import { auth } from "./auth.js";
export const AuthLive = Auth.layer(auth);
```
The layer doesn't mount the client. `AuthProvider`, `SessionGate` or the
router adapters still do that, as your setup guide shows.
In tests, provide a layer over another `createAuth` client with the same
`user`, such as one that keeps the session in memory. After you register
your client, `Auth.layer` takes only a client of that type:
```ts title="src/test-layer.ts"
import { createAuth, memoryStorage } from "@monarcode/session-kit";
import { Auth } from "@monarcode/session-kit/effect";
import { userSchema } from "./backend.js";
export const testAuth = createAuth({
name: "test",
user: userSchema,
storage: memoryStorage(),
});
export const AuthTest = Auth.layer(testAuth);
```
## 5. Read the session
`Auth.session` is the current session. If the access token has expired, it
refreshes first, and it fails with `UNAUTHENTICATED` when no one is signed
in. For code that also runs signed out, `Auth.sessionOption` gives
`Option.none()` instead:
```ts title="src/greeting.ts"
import { Auth } from "@monarcode/session-kit/effect";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
export const greeting = Auth.sessionOption.pipe(
Effect.map(
Option.match({
onNone: () => "Welcome",
onSome: (session) => `Welcome back, ${session.user.firstName}`,
}),
),
);
```
`greeting` needs the `Auth` service to run. Step 7 runs it with the rest of
the app's services.
## 6. Call your API with effetch
Make the app's API client as an effetch `Fetch.Service`: the backend's base
URL, its error body, and the plugins every call goes through. The
`sessionBearer` plugin sends the access token, and gets a new one after a
401:
```ts title="src/api.ts"
import { Fetch } from "@monarcode/effetch";
import { retry } from "@monarcode/effetch/plugins";
import { sessionBearer } from "@monarcode/session-kit/effetch";
import * as HttpClient from "effect/http/HttpClient";
import * as Layer from "effect/Layer";
import { API_BASE_URL, ApiError } from "./backend.js";
export class ApiClient extends Fetch.Service()("ApiClient", {
baseUrl: API_BASE_URL,
defaultError: ApiError,
plugins: [retry(), sessionBearer({ baseUrl: API_BASE_URL, optional: true })],
}) {}
/** The API client, over whichever `Auth` is provided. */
export const ApiClientLive = ApiClient.layer.pipe(
// Effect adds tracing headers to every request, which fail the preflight
// of an API that doesn't allow them.
Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)),
);
```
Here's what the plugin's options and place do:
- **Last in `plugins`.** A retry then reads the current token.
- **`baseUrl`.** The token goes only to that origin, so give it the
client's `baseUrl`.
- **`optional: true`.** One client here serves public and private
endpoints. A call made while signed out is then sent without a token, and
a private endpoint answers with its own 401. A locked client still fails
with `LOCKED`.
- **The `Auth` service.** The client's layer needs it, once. Calls don't.
`sessionBearer` handles a 401 the way
[Authenticated requests](https://session-kit.pages.dev/docs/client/requests#after-a-401) describes for
`createAuthFetch`. One rule matters most: if a `GET` or `HEAD` sent again
with the new token gets a 401 too, the user is signed out. For an API that
also answers 401 for other reasons, such as a missing permission, pass
`signOutOnRepeated401: false`. Its failures and a few other details differ
from `createAuthFetch`'s, as
[How `sessionBearer` differs from `createAuthFetch`](https://session-kit.pages.dev/docs/effect#how-sessionbearer-differs-from-createauthfetch)
lists.
Effect code yields the client and calls its methods, such as `get` and
`post`. To read the current user and to sign in, add `src/user.ts`:
```ts title="src/user.ts"
import * as Effect from "effect/Effect";
import { ApiClient } from "./api.js";
import { SessionUser, SignInResponse } from "./backend.js";
export const currentUser = Effect.gen(function* () {
const client = yield* ApiClient;
return yield* client.get("/auth/me", { output: SessionUser });
});
export const login = (username: string, password: string) =>
Effect.gen(function* () {
const client = yield* ApiClient;
return yield* client.post("/auth/login", {
body: { username, password },
output: SignInResponse,
plugins: { sessionBearer: false },
});
});
```
The sign-in call skips the plugin with `sessionBearer: false`, because it's
how the user gets a token.
After a refresh, `sessionBearer` sends only a `GET` or `HEAD` again. A
`POST` or any other method that got the 401 fails with an `HttpError` whose
`status` is 401, after the token is renewed. Where sending it twice is safe,
catch that status with `Fetch.catchStatus` and call again, since the next
call reads the new token:
```ts title="src/cart.ts"
import { Fetch } from "@monarcode/effetch";
import * as Effect from "effect/Effect";
import { ApiClient } from "./api.js";
export const addToCart = (userId: number, productId: number) => {
const add = Effect.gen(function* () {
const client = yield* ApiClient;
return yield* client.post("/auth/carts/add", {
body: { userId, products: [{ id: productId, quantity: 1 }] },
});
});
// The 401 refreshed the token, so one more try uses the new one.
return add.pipe(Fetch.catchStatus(401, () => add));
};
```
With [another HTTP client](https://session-kit.pages.dev/docs/client/other-http-clients), use
`Auth.credentials`, the access token. It's kept apart from `Auth.session`,
so code that only needs the user never holds a token. After a 401,
`Auth.renew(credentials)` gets new credentials once for every caller.
## 7. Run Effects in one runtime
Compose the app's layers in one place: the API client, the session, and the
`FetchHttpClient` effetch sends requests with, each made once:
```ts title="src/runtime.ts"
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import { ApiClientLive } from "./api.js";
import { AuthLive } from "./layer.js";
const AppLayer = ApiClientLive.pipe(
Layer.provideMerge(AuthLive),
Layer.provide(FetchHttpClient.layer),
);
/** One runtime for the app's lifetime. */
export const appRuntime = ManagedRuntime.make(AppLayer);
export type AppRuntime = typeof appRuntime;
```
Run every Effect with this runtime. For example,
`appRuntime.runPromise(greeting)` resolves `"Welcome back, Emily"` while
`emilys` is signed in, and `appRuntime.runPromise(currentUser)` fetches her
profile.
## 8. Sign in and out
Session kit doesn't sign users in: your backend checks the password. Ask it
with `login`, then save what it returns with `Auth.signIn`, which takes what
the client's `signIn` takes. `Auth.signOut` signs out:
```ts title="src/sign-in.ts"
import { Auth } from "@monarcode/session-kit/effect";
import * as Effect from "effect/Effect";
import { appRuntime } from "./runtime.js";
import { login } from "./user.js";
export const signIn = (username: string, password: string) =>
appRuntime.runPromise(
Effect.gen(function* () {
const response = yield* login(username, password);
const { accessToken, refreshToken, ...user } = response;
yield* Auth.signIn({ accessToken, refreshToken, user });
}),
);
export const signOut = () => appRuntime.runPromise(Auth.signOut);
```
Your sign-in form calls `signIn("emilys", "emilyspass")`. A wrong password
fails `login` with an `HttpError`, and no one is signed in. When the
response can't be saved, `Auth.signIn` fails with an `AuthFailure`, such as
`USER_VALIDATION_FAILED` for a user your schema rejects.
[Signing in and out](https://session-kit.pages.dev/docs/client/signing-in-and-out) explains what each
call does to the session.
That completes the setup. The rest of this page covers failures, the user
and changes to the session, then optional caching.
## Handle failures
Every `Auth` Effect fails with `AuthFailure`, whose `code` is the client's
`AuthErrorCode`, and misuse is a defect.
[How Effects fail](https://session-kit.pages.dev/docs/effect#how-effects-fail) explains both. Handle it
with `Effect.catchTag`, as you do your own errors. For example, to show
"Guest" when no one is signed in:
```ts title="src/account.ts"
import { Auth } from "@monarcode/session-kit/effect";
import * as Effect from "effect/Effect";
export const accountName = Auth.session.pipe(
Effect.map((session) => session.user.firstName),
Effect.catchTag("AuthFailure", (failure) =>
failure.code === "UNAUTHENTICATED"
? Effect.succeed("Guest")
: Effect.fail(failure),
),
);
```
A client method that `Auth` doesn't wrap, such as `auth.unlock()`, rejects
with an `AuthError`. `Auth.fromAuthError` turns it into an `AuthFailure`.
Anything else it's given, such as a network error from `createAuthFetch`,
is a defect.
## Update the user
`Auth.updateUser` takes the user, or an Effect that fetches it:
```ts title="src/profile.ts"
import { Auth } from "@monarcode/session-kit/effect";
import { currentUser } from "./user.js";
export const reloadProfile = Auth.updateUser(currentUser);
```
The client notes the session before the Effect runs, so a profile fetched
for one account never lands on another:
- **The session changes first.** The fetch is interrupted, and the update
fails with `SESSION_CHANGED`.
- **The fetch takes more than 15 seconds.** It's interrupted, and the update
fails with `USER_VALIDATION_FAILED`, whose `cause` is the timeout.
- **The fetch fails.** Its own failure, such as an `HttpError`, comes
through unchanged.
[Updating the user](https://session-kit.pages.dev/docs/client/updating-the-user) covers the rest, such as
a user your schema rejects.
## Watch the session
`Auth.changes` is a `Stream` of the client's `AuthState`: the current state,
then every change, until the stream ends:
```ts title="src/watch.ts"
import { Auth } from "@monarcode/session-kit/effect";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
export const logStatus = Auth.changes.pipe(
Stream.map((state) => state.status),
Stream.changes,
Stream.runForEach((status) => Effect.log(`Auth is ${status}`)),
);
```
## Cache with effetch-query
effetch-query keeps what your endpoints return in a cache, and your
components read it from there. The steps in this section are optional, and
need React 19. To install effetch-query 0.1.0-rc.4 or newer, with its
`@effect/atom-react` peer for React, run the following command:
```npm
npm install @monarcode/effetch-query @effect/atom-react
```
### Optional: Create the query client
effetch-query calls endpoints, each a route and its schemas defined with
`Fetch.endpoint`, through the app's API client. Its queries and mutations
run with the app's runtime, so components never run an Effect by hand.
`fromClient` reads the client's `defaultError` from its class:
```ts title="src/query.ts"
import { QueryClient } from "@monarcode/effetch-query";
import { fromClient } from "@monarcode/effetch-query/effetch";
import type * as ManagedRuntime from "effect/ManagedRuntime";
import { ApiClient } from "./api.js";
import { appRuntime, type AppRuntime } from "./runtime.js";
declare module "@monarcode/effetch-query" {
interface Register {
readonly services: ManagedRuntime.ManagedRuntime.Services;
}
}
export const api = fromClient(ApiClient);
export const makeQueryClient = () => QueryClient.make({ runtime: appRuntime });
```
### Optional: Give each account its own cache
A cache must not outlive the account that filled it. Let `QueryProvider` own
its client (`make` instead of `client`) and pass the session ID as
`resetKey`. Signing out or switching accounts then disposes the client,
with its cache and any requests still running, and renders the tree with a
new one:
```tsx title="src/query-provider.tsx"
import type { ReactNode } from "react";
import { QueryProvider } from "@monarcode/effetch-query/react";
import { useAuth } from "@monarcode/session-kit/react";
import { makeQueryClient } from "./query.js";
export function Queries({ children }: { children: ReactNode }) {
const account = useAuth((state) => state.sessionId ?? "signed-out");
return (
{children}
);
}
```
Render `Queries` inside `AuthProvider`, above every `Suspense` boundary. On
Expo, that's inside the `AuthProvider` around `SessionGate`. With TanStack
Router, there's no `AuthProvider`: import `useAuth` from
`@monarcode/session-kit/tanstack-router` instead, and render `Queries` in
the root route, as the example app does.
The cache follows the session ID, so these keep it:
- **A refresh, a failed refresh or a profile update.** The session ID
stays the same.
- **Locking.** The session ID stays the same. Queries that need a token
fail with `LOCKED` until `unlock()`, then refetch on their next trigger,
such as the app coming back into focus.
Until a saved session is restored, the key is `"signed-out"`, and the
restore replaces that client.
The owned client is for the browser and React Native. On the server, give
`QueryProvider` a `client` per request instead, as
[Use Effect on the server](https://session-kit.pages.dev/docs/effect/server#5-optional-render-queries-on-the-server)
shows. In the browser, an app with server rendering keeps the owned client,
over its mirror client.
### Optional: Query and mutate endpoints
A feature defines the endpoints it caches, and its components use the
queries and mutations made of them:
```tsx title="src/features/account.tsx"
import { Fetch } from "@monarcode/effetch";
import { useMutation, useQuery } from "@monarcode/effetch-query/react";
import { useAuthClient } from "@monarcode/session-kit/react";
import * as Exit from "effect/Exit";
import * as AsyncResult from "effect/reactivity/AsyncResult";
import * as Schema from "effect/Schema";
import { SessionUser, SignInResponse } from "../backend.js";
import { api } from "../query.js";
const signInMutation = api.mutation(
Fetch.endpoint("POST /auth/login", {
input: Schema.Struct({ username: Schema.String, password: Schema.String }),
output: SignInResponse,
}),
{ plugins: { sessionBearer: false } },
);
const profileQuery = api.query(
Fetch.endpoint("GET /auth/me", { output: SessionUser }),
);
export function SignInButton() {
const auth = useAuthClient();
const { result, run } = useMutation(signInMutation);
async function signIn() {
const exit = await run({
// DummyJSON's documented test user.
body: { username: "emilys", password: "emilyspass" },
});
// A failed request shows in `result`.
if (Exit.isFailure(exit)) return;
const { accessToken, refreshToken, ...user } = exit.value;
await auth.signIn({ accessToken, refreshToken, user });
}
return (
void signIn().catch(console.error)}
>
Sign in
);
}
export function Email() {
const result = useQuery(profileQuery());
return AsyncResult.match(result, {
onInitial: () =>