# 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 (

Sign in

{/* DummyJSON's documented test user. */} {error &&

{error}

}
); } ``` 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 (
void submit(event)}> {error &&

{error}

}
); } ``` 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"}

); } export const router = createBrowserRouter([ { element: , HydrateFallback: () =>

Checking session…

, 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 (
{result?.error &&

{result.error}

}
); } ``` 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 (
{error &&

{error}

}
); } ``` 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."} )} ); } ``` `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 (
{count !== null &&

{count} orders

}
); } ``` 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 ( ); } export function Email() { const result = useQuery(profileQuery()); return AsyncResult.match(result, { onInitial: () =>

Loading…

, onFailure: () =>

Couldn't load your profile.

, onSuccess: ({ value }) =>

{value.email}

, }); } ``` The sign-in mutation saves the session with the client's own `signIn`, which `useAuthClient` returns. With TanStack Router, import `useAuthClient` from `@monarcode/session-kit/tanstack-router` too. ## Next steps - [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run the same Effects in server functions and route handlers, with each request's session. - [Effect and effetch](https://session-kit.pages.dev/docs/effect): what `Auth` covers, and how `sessionBearer` differs from `createAuthFetch`. - [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients): the calls `sessionBearer` is built on, for any other client. - [Locking](https://session-kit.pages.dev/docs/client/locking): lock a native app's session. `Auth.session` and `sessionBearer` then fail with `LOCKED` until it's unlocked. - [`./effect` reference](https://session-kit.pages.dev/docs/reference/effect) and [`./effetch` reference](https://session-kit.pages.dev/docs/reference/effetch): every export. # Use Effect on the server (https://session-kit.pages.dev/docs/effect/server) With server rendering, your server functions, actions and route handlers run Effects too. There, the session is the encrypted cookie the server keeps ([Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions)), and each request has its own. This guide runs your Effects with that request's session, so `Auth.session`, `Auth.credentials` and `sessionBearer` work on the server as they do in the browser. `sessionBearer` sends the cookie's access token, and saves a renewed one after a 401. Each framework's adapter gives one request's session (`RequestAuth`), and `Auth.layer` takes it. The rule that shapes this page: a request's session belongs to that request, and so does everything that uses it. ## Before you begin - Follow your framework's guide, which creates the server engine and registers the browser's `createMirrorAuth` client: [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start), [Next.js](https://session-kit.pages.dev/docs/setups/next) or [React Router](https://session-kit.pages.dev/docs/setups/react-router-ssr). - Follow steps 1, 2 and 6 of [Use Effect in the browser](https://session-kit.pages.dev/docs/effect/browser). The server's files build on the `src/backend.ts`, `src/refresh.ts`, `src/api.ts` and `src/user.ts` they add. - Effect asks for TypeScript 5.9 or newer. - To render queries with effetch-query in step 5, you need React 19: its React bindings don't support React 18. [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) lists every version. ## 1. Create the server engine On the server, the session comes from `createServerAuth`, with the user schema the app registers and the same refresh as the browser. Your framework's guide creates `serverAuth`. Build it from `userSchema` and `refreshSession`, as this `src/server/auth.ts` does: ```ts title="src/server/auth.ts" import { createServerAuth } from "@monarcode/session-kit/server"; import { userSchema } from "../backend.js"; import { refreshSession } from "../refresh.js"; declare const secret: string; // from the environment export const serverAuth = createServerAuth({ name: "app", user: userSchema, secret, refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), }); /** One request's session, as your framework's adapter gives it. */ export type ServerSession = ReturnType; ``` ## 2. Run Effects per request Build the session's layer and the API client per request, and keep one runtime for what belongs to no user: ```ts title="src/server/run.ts" import { Auth } from "@monarcode/session-kit/effect"; import * as Effect from "effect/Effect"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import { type ApiClient, ApiClientLive } from "../api.js"; import type { ServerSession } from "./auth.js"; /** Built once: what belongs to no user. */ const serverRuntime = ManagedRuntime.make(FetchHttpClient.layer); /** Built per request: its session, and the API client that uses it. */ export const requestLayer = (session: ServerSession) => ApiClientLive.pipe(Layer.provideMerge(Auth.layer(session))); /** Runs `effect` with the request's `session`. */ export function runRequest( session: ServerSession, effect: Effect.Effect, ): Promise { return serverRuntime.runPromise( Effect.provide(effect, requestLayer(session)), ); } ``` The runtime has no `Auth` and no API client. So an Effect that needs them doesn't compile until it goes through `runRequest`, and nothing a service keeps outlives its request. ## 3. Call your API from a server function Each framework's adapter gives the request's session in the server function, action or handler. Pass it to `runRequest` with the Effect: ```ts title="src/server/profile.ts" import { currentUser } from "../user.js"; import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; // TanStack Start: startAuth(serverAuth). React Router: // routerAuth(serverAuth)(context). Next.js, from // nextSession(serverAuth, { cookies, redirect }): await session.writable() // in a Server Function, or await session.readOnly() in a Server Component. export const profileFor = (session: ServerSession) => runRequest(session, currentUser); ``` [A request's session](https://session-kit.pages.dev/docs/server-rendering/server-sessions#a-requests-session) explains each adapter. ## 4. Sign in on the server `Auth.signIn` and `Auth.updateUser` take what the browser client's methods take, so they aren't available on a request's session. Sign in with the session's own `signIn`, which takes the tokens and the user, and update the user with its own `updateUser`. Ask your backend with an Effect, then save what it returns with the session's `signIn`: ```ts title="src/server/sign-in.ts" import { login } from "../user.js"; import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; export async function signIn( session: ServerSession, username: string, password: string, ) { const { accessToken, refreshToken, ...user } = await runRequest( session, login(username, password), ); return session.signIn({ accessToken, refreshToken, user }); } ``` ## 5. Optional: Render queries on the server To render a page with its data from effetch-query, make a query client per request, on the server, over that request's layer: ```ts title="src/server/query-client.ts" import { QueryClient } from "@monarcode/effetch-query"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; import type { ServerSession } from "./auth.js"; import { requestLayer } from "./run.js"; export const queryClientFor = (session: ServerSession) => QueryClient.make({ layer: requestLayer(session).pipe(Layer.provide(FetchHttpClient.layer)), }); ``` Give it no `memoMap`: [Things to know](#things-to-know) says why. Pass it to `QueryProvider` as `client` while the page renders, and dispose of it after the page is sent. For a server that answers with a streamed `Response`, `QueryClient.disposeAfter` does that: ```ts title="src/server/respond.ts" import { QueryClient } from "@monarcode/effetch-query"; import type { ServerSession } from "./auth.js"; import { queryClientFor } from "./query-client.js"; /** `render` gives `` its tree. */ export async function respondWithQueries( session: ServerSession, render: (queryClient: QueryClient.QueryClient) => Promise, ): Promise { const queryClient = queryClientFor(session); try { return QueryClient.disposeAfter(queryClient, await render(queryClient)); } catch (error) { await queryClient.dispose(); throw error; } } ``` Each framework has its own place for the client and its disposal, which effetch-query's [Frameworks](https://github.com/monarcode/effetch-query#frameworks) section shows: - **TanStack Start:** make the client in `getRouter`, and `connectQueryClient` disposes it when the request ends. - **Next.js:** make it with React's `cache()`, and dispose of it in `after()`. - **React Router:** make it in middleware, and wrap the response in `QueryClient.disposeAfter`, as `respondWithQueries` does. A page's render can't always save a renewed cookie: a Next.js Server Component never can, and TanStack Start loses a cookie set after the page starts streaming. So refresh before the page renders, in middleware or Proxy, as each framework guide does. In TanStack Start, a prefetch that runs before the page starts streaming can also save a renewed cookie. In the browser, the cache is the owned one from [Give each account its own cache](https://session-kit.pages.dev/docs/effect/browser#optional-give-each-account-its-own-cache), over the mirror client. ## Things to know - **One registration.** An app with server rendering registers its mirror client, and that registration types `Auth` on the server too. `Auth.layer` takes a request's session whose user is the registered one. In the browser, build `Auth.layer(mirror)` where the mirror is created. There, `Auth.signIn` needs the mirror's `signIn` option, and `Auth.updateUser` isn't available, since the user comes from the server. `sessionBearer` in the browser needs `clientCredentials: true` in `createServerAuth`, or the mirror's `credentials` option ([The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser)). - **Keep server modules free of the browser client.** In this guide, the server's files import only `src/backend.ts`, `src/refresh.ts`, `src/api.ts` and `src/user.ts`, which create no Session kit client. Keep it that way in your app. A module the server imports, such as the one that defines `ApiClientLive` or the user schema, mustn't also create a browser client or its layer, or the server loads it too. - **Name the services in `runRequest`'s signature,** as `src/server/run.ts` does, rather than inferring them from `requestLayer`. With a mirror registered, the registration depends on the server functions the mirror calls, which call `runRequest`, and TypeScript reports a circular type. For the same reason, the server functions the mirror is made from, such as its `revalidate` and `signIn`, read the request's session directly, not `Auth.session`. - **Keep a request's layer off a shared `memoMap`,** such as the runtime's or one passed to `QueryClient.make`. Layers are shared by identity there, so overlapping requests can get one build. A service that keeps `Auth` when it's built would then serve one request's session to another. - **Requests that can't set cookies,** such as a Next.js Server Component's. `Auth.session` returns the cookie's session as it is. `Auth.credentials` and `sessionBearer` fail with `REFRESH_FAILED` after the access token has expired, or after a 401, since nothing new can be saved. Refresh first, in middleware or Proxy, as the framework guides do. `Auth.signOut` dies there with `INVALID_OPTIONS`, so sign out in an action or route handler. [A request's session](https://session-kit.pages.dev/docs/server-rendering/server-sessions#a-requests-session) lists which requests these are. - **Only `Auth`'s Effects.** A request's session isn't your browser client, so don't reach for client methods through `Auth.use` there. - **`Auth.layer` binds a session from `startAuth`** to the request that's current when it's called, so call it per request, as `requestLayer` does. Outside a request, it throws `INVALID_OPTIONS`. ## Next steps - [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): how the server keeps the session in a cookie, and refreshes it. - [Effect and effetch](https://session-kit.pages.dev/docs/effect): what `Auth` covers, and how `sessionBearer` differs from `createAuthFetch`. - [`./effect` reference](https://session-kit.pages.dev/docs/reference/effect): `Auth.layer` and every other export. # Security (https://session-kit.pages.dev/docs/security) Your app holds tokens that act for the user, so you need to know who can read them and where they're sent. Session kit saves the tokens your backend issues and manages the session around them. It doesn't decide what a user may do. This page shows what stays your backend's job, where the tokens live in each setup, how the session route refuses other sites, and where the access token goes. ## Your backend decides what's allowed Your backend must authenticate every request and authorize private operations. Route guards, screen guards and the user's fields in the client decide what to show, not what's allowed. With server rendering, `signIn` seals what it's given into the cookie. If the browser signs in with your backend and sends the tokens and the user to your server, the cookie's user is what the browser sent, until a refresh or `updateUser` replaces it. Use that user to show who is signed in. Let your backend authorize requests with the access token, or check the tokens before `signIn`. ## Where tokens live Each setup saves the tokens in a different place, and each place protects them differently: - **In a browser app**, `webStorage()` saves them in `localStorage` or `sessionStorage`. Any JavaScript on your origin can read them there, as it can read anything else in that storage. They never go in cookies, so the browser doesn't send them on its own. - **With [server rendering](https://session-kit.pages.dev/docs/server-rendering)**, they're sealed in an encrypted `httpOnly` cookie, which page scripts can't read. That includes the refresh token. Only the access token reaches page scripts, and only with `clientCredentials`: see [The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser). - **In an [Expo app](https://session-kit.pages.dev/docs/setups/expo)**, `secureStorage()` saves them in the iOS keychain, or encrypted with an Android Keystore key. The `expo-secure-store` config plugin keeps the session out of Android backups. By default, `secureStorage()` also removes a session that an earlier install left in the iOS keychain (its `clearOnReinstall` option). See [Reinstalls and Android backups](https://session-kit.pages.dev/docs/setups/expo#reinstalls-and-android-backups). To keep tokens off disk in a browser, `memoryStorage()` holds them in memory, and the session ends when the page unloads. [Storage](https://session-kit.pages.dev/docs/configuration/storage) lists every store. ## The session route With server rendering, the browser's client calls a route in your app, the session route, to sign out and to get the access token. In most setups, it reads the session there too. `sessionHandler` from `@monarcode/session-kit/server` answers it, through each framework's `sessionRoute`. The session route answers your own site's pages only, so another site can't sign the user out or ask for the access token. It makes two checks, and answers 403 to a request that fails either one: - A `Sec-Fetch-Site` header, when the request has one, must be `same-origin`. Browsers send it with requests to https and localhost sites. - On plain http, where browsers don't send that header, a `POST` must have an `Origin` header that matches the request's URL. A `GET` passes: it changes nothing, and another site can't read the answer. These checks stop other sites, not a script injected into your own pages. Such a script passes them, so it can sign the user out, and with `clientCredentials`, get the access token. Protect your pages against cross-site scripting (XSS), for example with a Content Security Policy. ### Check your own routes Signing in stays your own server code. A route of your own that changes the session must refuse other sites too, wherever your framework doesn't check for you. Session kit doesn't export its check, so copy it into your app: ```ts title="src/same-site.ts" /** * Whether a request comes from this site's own pages, by the same two checks * as the session route. */ export function fromThisSite(request: Request): boolean { const site = request.headers.get("Sec-Fetch-Site"); if (site !== null) return site === "same-origin"; // Plain http: let a GET through, so change the session on POST only. if (request.method === "GET") return true; return request.headers.get("Origin") === new URL(request.url).origin; } ``` Call it first in the route's handler or action, with the incoming `Request`. When it returns `false`, answer 403 and change nothing. Change the session only on a `POST`: on plain http, the check lets any `GET` through, as the session route does. ## Where tokens go [`createAuthFetch`](https://session-kit.pages.dev/docs/client/requests) and the effetch plugin `sessionBearer` send the access token only to your API's origin: - A request to another origin, or with a username or password in its URL, is refused before anything is sent. `authFetch` rejects with `INVALID_OPTIONS`. With `sessionBearer`, the Effect dies with it, so `Effect.catch` doesn't catch it. - A redirect isn't followed, so the token doesn't reach the server it points to. On React Native before Expo SDK 58, `fetch` follows a redirect 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. [Authenticated requests](https://session-kit.pages.dev/docs/client/requests) has the full list of what `authFetch` refuses, and [Effect and effetch](https://session-kit.pages.dev/docs/effect#how-sessionbearer-differs-from-createauthfetch) how `sessionBearer` differs. [Debug events](https://session-kit.pages.dev/docs/configuration/debugging) leave out tokens unless you turn on `sensitive`. ## Keep tokens out of page data Sessions, the auth state, route context and the loader results Session kit makes hold no tokens: a `Session` has the user and its `sessionId` only. Don't put tokens in loader results or hydrated page data yourself. ## Next steps - [Server rendering](https://session-kit.pages.dev/docs/server-rendering): keep the tokens in an `httpOnly` cookie, out of page scripts' reach. - [Storage](https://session-kit.pages.dev/docs/configuration/storage): choose where a browser or Expo app saves the session. - [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): send the access token to your API, and only there. # Common questions (https://session-kit.pages.dev/docs/faq) These questions come up when you adopt Session kit. Each answer is short, and links to the page that covers the subject in full. ## Do I need a refresh token? No. Without a refresh token or a `refresh` callback, the user is signed out when the access token expires, or when `authFetch` gets a 401. See [Authenticated requests](https://session-kit.pages.dev/docs/client/requests) for what happens after a 401, and [Refresh](https://session-kit.pages.dev/docs/configuration/refresh) to add a refresh later. ## What if my backend doesn't say when the token expires? The client still works. See [Expiry](https://session-kit.pages.dev/docs/configuration/expiry) for where the client looks for the expiry, and what it does when it finds none. ## Is it safe to keep tokens in `localStorage`? Any script on your origin can read them, as [Security](https://session-kit.pages.dev/docs/security) explains. If that isn't acceptable for your app, you have two options: - Keep the session on the server, in an `httpOnly` cookie, with [server rendering](https://session-kit.pages.dev/docs/server-rendering). - Keep the tokens off disk with `memoryStorage()`. The session then ends when the page unloads. See [Storage](https://session-kit.pages.dev/docs/configuration/storage). ## How do I use it with TanStack Query, or another cache? Put [`state.sessionId`](https://session-kit.pages.dev/docs/client/state) in the query key, or clear the cache when it changes, so one account never reads another's data. With effetch-query, [`resetKey`](https://session-kit.pages.dev/docs/effect#cache-with-effetch-query) does it. ## Why does TanStack Start in SPA mode flash my pending component? The build prerenders an HTML shell, which the browser shows before any JavaScript runs. The client restores the session as soon as the script loads. Plain TanStack Router shows a blank page for the same moment. Give the shell a neutral pending component, as [TanStack Start in SPA mode](https://session-kit.pages.dev/docs/setups/tanstack-router#tanstack-start-in-spa-mode) does. ## What if some endpoints answer 401 for other reasons? Turn off `signOutOnRepeated401` in `createAuthFetch`'s options. A second 401 from those endpoints then comes back to your code instead of signing the user out. Without a refresh token or a `refresh` callback, the first 401 still signs the user out. See [Keep users signed in after a second 401](https://session-kit.pages.dev/docs/client/requests#keep-users-signed-in-after-a-second-401). ## How much does it add to my bundle? About 11 kB gzipped for a single-page app with a router adapter and `createAuthFetch`. With server rendering, where the session work happens on the server, it's about 5 kB. The routers you don't use add nothing: see [Entry points](https://session-kit.pages.dev/docs/reference). ## Can I sign users in with Google, or a magic link? Yes, through your backend. Whatever your backend does to sign a user in, Session kit starts from the tokens it answers with. See [What it doesn't do](https://session-kit.pages.dev/docs#what-it-doesnt-do). ## Next steps - [Security](https://session-kit.pages.dev/docs/security): what Session kit protects, and what stays your backend's job. - [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility): the runtimes and versions Session kit supports. # Entry points (https://session-kit.pages.dev/docs/reference) Find the import path for your setup here, then open its page for the options and types of each export. Import from these paths only: the internal `dist` paths aren't part of the public API. ## Entry points Each entry point, what it's for, and what it exports: | Import | Use it for | Exports | | --------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | [`@monarcode/session-kit`](https://session-kit.pages.dev/docs/reference/core) | Creating the client, in every setup | `createAuth`, `createMirrorAuth`, `fromAccessToken`, `webStorage`, `memoryStorage`, `isSignedIn`, `safeReturnTo`, `loginHref`, `AuthError`, types | | [`@monarcode/session-kit/react`](https://session-kit.pages.dev/docs/reference/react) | Reading the session in React: the provider and hooks | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | | [`@monarcode/session-kit/tanstack-router`](https://session-kit.pages.dev/docs/reference/tanstack-router) | Guarding routes with TanStack Router | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | | [`@monarcode/session-kit/react-router`](https://session-kit.pages.dev/docs/reference/react-router) | Guarding routes with React Router in the browser | `requireSession`, `requireSessionLoader`, `redirectIfSignedIn`, `redirectIfSignedInLoader`, `SessionOutlet`, `useAuthRevalidation`, types | | [`@monarcode/session-kit/react-router/server`](https://session-kit.pages.dev/docs/reference/react-router-server) | Server sessions with React Router | `sessionMiddleware`, `requireSession`, `redirectIfSignedIn`, `sessionRoute`, `routerAuth`, `cookieJarMiddleware`, `routerJar`, types | | [`@monarcode/session-kit/http`](https://session-kit.pages.dev/docs/reference/http) | Calling your API with the access token | `createAuthFetch`, types | | [`@monarcode/session-kit/server`](https://session-kit.pages.dev/docs/reference/server) | Server sessions on any server | `createServerAuth`, `sessionHandler`, types | | [`@monarcode/session-kit/tanstack-start`](https://session-kit.pages.dev/docs/reference/tanstack-start) | The browser side of TanStack Start with server sessions | `connectSession`, `loadSession` | | [`@monarcode/session-kit/tanstack-start/server`](https://session-kit.pages.dev/docs/reference/tanstack-start-server) | The server side of TanStack Start | `startAuth`, `refreshSession`, `sessionRoute`, `startJar`, types | | [`@monarcode/session-kit/next`](https://session-kit.pages.dev/docs/reference/next) | Server sessions with Next.js | `nextSession`, `sessionRoute`, `nextJar`, `proxyJar`, types | | [`@monarcode/session-kit/expo`](https://session-kit.pages.dev/docs/reference/expo) | Expo Router apps on iOS and Android | `secureStorage`, `SessionGate`, `deepLinkHandler`, `rememberDeepLink`, types | | [`@monarcode/session-kit/effect`](https://session-kit.pages.dev/docs/reference/effect) | Reading the session from Effect code | `Auth`, `AuthFailure`, types | | [`@monarcode/session-kit/effetch`](https://session-kit.pages.dev/docs/reference/effetch) | Calling your API with effetch | `sessionBearer`, types | ## Bundle size The package is tree-shakeable, so a bundle holds only what you import. An entry point you don't import adds nothing. ## Errors Errors from Session kit's own logic are `AuthError`s, with a `code` you can match on. [Error codes](https://session-kit.pages.dev/docs/reference/error-codes) lists every code, and [Effect and effetch](https://session-kit.pages.dev/docs/effect#how-effects-fail) how they reach Effect code. ## Next steps - [Installation](https://session-kit.pages.dev/docs/installation#pick-your-setup): find the guide for your setup. - [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility): the versions and runtimes each entry point supports. # Core (https://session-kit.pages.dev/docs/reference/core) Import these from `@monarcode/session-kit`. To set it up, see [Getting started](https://session-kit.pages.dev/docs/getting-started). ## Functions ### createAuth Creates an auth client. It keeps the session your backend issued, saves it, refreshes its tokens, and tells your app when it changes. Create one client per `name`. Throws `INVALID_OPTIONS` for options it can't use. To keep sessions on your server instead, in a cookie, use `createServerAuth` from `@monarcode/session-kit/server`. The saved session is read on the first `mount()`, which `AuthProvider` and the router adapters call, or by the first method that needs it, such as `getSession()`. Until then, `state.status` is `initializing`. See [`AuthOptions`](#authoptions) for every option. See [`AuthClient`](#authclient) for what the client does. ### createMirrorAuth Creates a browser client ([`MirrorAuth`](#mirrorauth)) for a session your server keeps in an encrypted cookie, with `createServerAuth` from `@monarcode/session-kit/server`. It starts from the session the page was rendered with, so there's no loading state, and it never sees the refresh token. Create one per page load in the browser, and one per request on the server, never at module level. `useMirrorAuth` does this for you. Let TypeScript infer its types from the options. With an explicit `createMirrorAuth(…)`, `signIn` drops out of the type. Throws `INVALID_OPTIONS` for options it can't use, and `INVALID_SESSION` for a `session` that isn't a session or `null`. See [`MirrorAuthOptions`](#mirrorauthoptions) for every option. ### fromAccessToken Reads the user from the access token, rather than from what `signIn` is given. Pass the result as `createAuth`'s `user` option. The `claims` schema checks the token's claims, and `map` turns them into the user. Without `map`, the claims are the user. The client then works a little differently: - `signIn` takes tokens only, and your refresh callback returns tokens only. - There's no `updateUser`. The user changes when the token does, so call `auth.refresh()` to pick up a change. `map` runs on every restore and every new token, so keep it pure and synchronous. The same claims must give the same user. Leave out claims that change on every refresh, such as `exp`, `iat` or `jti`. A token that can't be read, or whose claims the schema rejects, fails with `USER_VALIDATION_FAILED`. See [`FromAccessTokenOptions`](#fromaccesstokenoptions) to verify the token yourself. ### isSignedIn Whether someone is signed in: `true` while `authenticated` or `refreshing`. It narrows `state`, so `state.user` is set when it's `true`. Check this rather than `status === "authenticated"`, which is `false` for a moment while an expired access token refreshes. A `locked` session is `false`. It has a user, but no access until it's unlocked. ### loginHref Builds the sign-in page's URL, with `?redirectTo=` set to `returnTo`, so the user comes back after signing in. The guards use it. Use it in a guard of your own, such as in a route handler. `returnTo` is encoded as is. Pass a path you read from the request through [`safeReturnTo`](#safereturnto) first. Throws `INVALID_OPTIONS` when `loginPath` doesn't start with `/`. ### memoryStorage Keeps the session in memory only. It ends when the page unloads, and other tabs never see it. Use it in tests, or where tokens must never be written to disk. Each call has its own entries. ### safeReturnTo Makes a "send me back here after sign-in" path safe to redirect to, such as a `?redirectTo=` search param. It returns the path, normalized, when it leads somewhere in your app, query and fragment included. Anything else returns `"/"`: - Another site, including protocol-relative `//host` paths. - A path with backslashes, spaces or control characters. - The sign-in page itself, so a stale `redirectTo` can't loop. Throws `INVALID_OPTIONS` when a `loginPath` doesn't start with `/`. ### webStorage Saves the session in the browser's `localStorage`, or in `sessionStorage` with `{ area: "session" }`. With `localStorage`, tabs follow each other's changes, such as a sign-out. Tabs take turns to refresh where the browser supports Web Locks. It touches browser storage only when the client reads or saves, so creating a client in code that also runs on a server is safe. Reading the session on a server fails with `PERSISTENCE_FAILED`. ## Classes ### AuthError The error Session kit throws, rejects with, or shows in `state.error`. `code` says what went wrong ([`AuthErrorCode`](#autherrorcode)). `cause` holds what failed underneath, such as your refresh callback's error, and `issues` holds the schema's issues when the user was rejected. ## Types ### AccessTokenUser A user read from the access token, made by [`fromAccessToken`](#fromaccesstoken). Pass it as `createAuth`'s `user` option. `C` is the token's claims, and `U` is the user made from them. ### AuthClient The auth client that `createAuth` returns. It holds the session, saves it, refreshes it, and tells your app when it changes. `U` is the user ([`User`](#user)) and `I` is the user `signIn` accepts ([`UserInput`](#userinput)). With `fromAccessToken`, `I` is `never` and there's no `updateUser`. Write `typeof auth` rather than spelling out both. Members: - `state`: The current [`AuthState`](#authstate), and a way to listen for changes. In React, read it with `useAuth`. `subscribe` calls the listener on each later change, not with the current state. A listener that throws doesn't break auth. Its error is rethrown asynchronously. - `state.get` - `state.subscribe` - `signIn`: Signs in with the tokens your backend issued, and saves the session. It replaces any current session, even a locked one. Rejects with `INVALID_SESSION` for tokens it can't use, such as ones that already expired, and with `USER_VALIDATION_FAILED` for a user the schema rejects. The previous session then stays. If `signIn` or `signOut()` is called again while it's still checking the user, it rejects with `SESSION_CHANGED`, as the latest call wins. If the session can't be saved, it rejects with `PERSISTENCE_FAILED`, and no one is signed in. - `signOut`: Signs out at once, clears the saved session, then calls your `revoke` option and waits for it. Other tabs that share the storage sign out too, when it reports changes (`subscribe`) and `locking` is off. If `revoke` fails, `state.error` shows `REVOKE_FAILED`, and `signOut()` still resolves. If storage can't be cleared, it rejects with `PERSISTENCE_FAILED`. The app is signed out anyway, but the next load would restore the session, so call it again later. - `getSession`: Resolves who is signed in, or `null` when signed out. It reads the saved session first if needed, and refreshes an expired access token. After a refresh fails, it rejects with that failure until `retry()`, `signIn` or `signOut()`. Rejects with `PERSISTENCE_FAILED` when the saved session can't be read, with `SESSION_CHANGED` when the session changes while it runs, and with `LOCKED` while locked. - `retry`: Like `getSession()`, but tries a failed refresh again instead of rejecting with its error. Use it for a "Try again" button. - `refresh`: Refreshes the tokens now, even if the access token is still valid, for example to pick up changes to the user. Resolves `null` when signed out. Rejects with `REFRESH_FAILED` when there's no `refresh` option or no refresh token, and with `LOCKED` while locked. - `isCurrent`: Whether `session` is still the signed-in one, by its `sessionId`. Use it to drop a response that arrives after the user signed out or switched accounts. - `lock`: Locks the session (with `locking`). The tokens leave memory and timers stop, but the saved session and `state.user` stay. `state.status` turns `locked` at once. While locked, `getSession`, `retry`, `refresh`, `updateUser`, `credentials.get` and `credentials.renew` reject with `LOCKED`. Call `unlock()` to continue, or `signOut()`. A refresh already running still saves its tokens, and `lock()` resolves after that save. Keep the key `seal` needs until then. Does nothing when signed out or already locked. Rejects with `INVALID_OPTIONS` without `locking`. - `unlock`: Unlocks a `locked` session and resolves it. It reads the saved tokens and opens them with `locking.open`. When not locked, it acts like `getSession()`. Overlapping calls share one unlock. If `open` throws or doesn't return a string, it rejects with `UNLOCK_FAILED`, and the session stays locked. If storage can't be read, it rejects with `PERSISTENCE_FAILED`, and the session stays locked too. If the saved session can't be used, it signs out and rejects with `INVALID_SESSION`. If it's gone, or past `maxAge`, it signs out and resolves `null`. An expired access token is refreshed at once. If your backend rejects the refresh token, it signs out and resolves `null`. If the refresh fails otherwise, it rejects with `REFRESH_FAILED`. The session is then unlocked, but `unavailable` until `retry()`. Rejects with `INVALID_OPTIONS` without `locking`. - `mount`: Starts the background work: expiry timers, and following other tabs. Returns a function that stops it. `AuthProvider` and the router adapters call it for you. Calls are counted, and the work stops when the last one is stopped. Each call also checks the session again. It reads the saved session if that hasn't worked yet, and refreshes an access token that expired. - `credentials`: The access token ([`Credentials`](#credentials)), for code that sends it with requests, such as `createAuthFetch`. - `credentials.get`: Like `getSession()`, but resolves the current access token. - `credentials.renew`: Gets a new access token after your API rejected `credentials`, such as with a 401. Calls that overlap share one refresh. Without a `refresh` option or a refresh token, it signs out and resolves `null`. Rejects with the refresh's failure, such as `REFRESH_FAILED`, or `INVALID_SESSION` and `USER_VALIDATION_FAILED` for tokens or a user the client can't use. Rejects with `SESSION_CHANGED` when another session has replaced theirs, and with `LOCKED` while locked. - `credentials.reject`: Signs out because your API rejected `credentials` for good. Does nothing if they're no longer current, such as after a refresh. - `updateUser`: Replaces the signed-in user, such as after a profile edit. Pass the user, or an async function that fetches it. The session ID stays. Rejects with `UNAUTHENTICATED` when signed out, and with `USER_VALIDATION_FAILED` for a user the schema rejects, or when the function rejects or takes more than 15 seconds. An `AuthError` the function throws keeps its own `code`. If calls overlap, the latest wins and the others reject with `SESSION_CHANGED`. It reads the session as `getSession()` does first, so it rejects with `LOCKED` while locked, and with a refresh's failure, such as `REFRESH_FAILED`. If the new user can't be saved, it rejects with `PERSISTENCE_FAILED` and signs out. ### AuthDebug What `createAuth`'s `debug` option takes: - `true`: log every event to the console. - A function: receive every [`AuthDebugEvent`](#authdebugevent). - [`AuthDebugOptions`](#authdebugoptions): choose where events go, and whether they include secrets. - `false`, or leaving it out: no logging. ### AuthDebugEvent One thing the client did, sent to the `debug` option ([`AuthDebug`](#authdebug)). Filter on `type`, which doesn't change between releases. `message` and `data` are for reading, and may change in any release. Events are frozen, so copy one before changing it. ### AuthDebugOptions The object form of `createAuth`'s `debug` option ([`AuthDebug`](#authdebug)): where events go, and whether they include secrets. ### AuthDebugOptions The object form of `createAuth`'s `debug` option (AuthDebug): where events go, and whether they include secrets. | Prop | Type | Description | | ------------ | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `log?` | `function` | Receives every event. Default: one `console.info` line per event. | | `sensitive?` | `union` | Also puts tokens, saved values, user fields, whole deep-link paths and error details in events. Anyone who reads such logs can act as the user, so use it only in development. Default: `false` | ### AuthDebugType Which part of Session kit an [`AuthDebugEvent`](#authdebugevent) comes from, such as `refresh` or `storage`. These names don't change between releases, so filter on them. `sync` events report changes from other tabs and, with server rendering, from the server. `gate`, `deep-link` and `foreground` events come from `@monarcode/session-kit/expo`. ### AuthErrorCode What went wrong: the `code` of every [`AuthError`](#autherror). Match on it rather than on the message, which may change in any release. ### AuthErrorOptions Options for creating an [`AuthError`](#autherror) yourself, such as in a test or a custom storage adapter: the standard `cause`, plus schema `issues`. ### AuthErrorOptions Options for creating an AuthError yourself, such as in a test or a custom storage adapter: the standard `cause`, plus schema `issues`. | Prop | Type | Description | | --------- | --------- | ---------------------------------------------------------- | | `cause?` | `unknown` | | | `issues?` | `array` | The schema's issues, for a `USER_VALIDATION_FAILED` error. | ### AuthLocking Encrypts the saved tokens with a key your app holds, such as one behind Face ID. Pass it as the `locking` option of [`AuthOptions`](#authoptions). The client calls `seal` whenever it saves tokens, and `open` only from `unlock()`. The user and session ID are saved unencrypted, so a locked session can still show who is signed in. Members: - `seal`: Encrypts the tokens, given as a JSON string. If it throws while a session is saved, the save fails with `PERSISTENCE_FAILED`, which signs the user out. - `open`: Decrypts what `seal` returned. It must throw when it can't. ### AuthOptions Options for `createAuth`. The client's user types ([`User`](#user), [`UserInput`](#userinput)) are inferred from the `user` option. ### AuthOptions Options for `createAuth`. The client's user types (User, UserInput) are inferred from the `user` option. | Prop | Type | Description | | ---------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | Names this auth, so several can share one storage. It's used in the storage key (`:auth:session`) and in the lock that keeps tabs from refreshing at once. Letters, digits, `_` or `-`, up to 64 characters. | | `user` | `Src` | Where the user comes from: a schema, or `fromAccessToken(…)`. A Standard Schema schema, such as Zod's, checks the `user` passed to `signIn`. Its output must be a plain JSON object that it accepts again unchanged, as a restored session is checked again. `fromAccessToken` reads the user from the access token instead. | | `storage` | `AuthStorage` | Where the session is saved, such as `webStorage()` (AuthStorage). | | `refresh?` | `RefreshFn>>` | Exchanges a refresh token for new tokens (RefreshFn). Without it, the user is signed out when the access token expires or your API rejects it. | | `revoke?` | `RevokeFn` | Asks your backend to revoke the tokens after `signOut()` (RevokeFn). | | `maxAge?` | `number` | How long a saved session lasts, in whole seconds. Each save, such as after a refresh, starts it again. A session saved longer ago isn't restored, 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. Default: 30 days. | | `debug?` | `union` | Logs what the client does, for debugging: restores, refreshes, timers, storage and state changes. `true` logs to the console, and a function receives each event instead (AuthDebug). Tokens, user fields, saved values and error details are left out unless you pass `{ sensitive: true }`. Pass a development flag, such as Expo's `__DEV__`, to keep it out of production. Default: `false` | | `locking?` | `Src extends AccessTokenUser ? never : true \| AuthLocking` | Restores a saved session as `locked`. Its user shows, but its tokens wait for `unlock()`. `true` saves the tokens as they are, and `{ seal, open }` encrypts them with your app's key (AuthLocking). It's meant for native apps. In a browser, tabs stop following each other, so 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. It needs a user schema, as a user read from the access token can't show while the token is locked. | ### AuthState The current auth state, from `state.get()` or `useAuth()`. It holds no tokens. Check `status`, not `user`, to know whether requests can be made. `user` stays set while `locked`, when they can't. `isSignedIn` is that check. Checking `status` also narrows `user`, so TypeScript knows when it's set. ### AuthStatus Where the session stands: `state.status` ([`AuthState`](#authstate)). - `initializing`: the saved session hasn't been read yet. - `authenticated`: signed in, with an access token that hasn't expired or been rejected. - `refreshing`: signed in, and replacing an access token that expired or was rejected. - `locked`: signed in, but the tokens wait for `unlock()` (with `locking`). - `unauthenticated`: signed out. - `unavailable`: the access token expired or was rejected and couldn't be refreshed, or the saved session couldn't be read. `state.error` usually says why. On a client, `retry()` tries again. `user` is set while `authenticated`, `refreshing` or `locked`. ### AuthStorage Where Session kit saves the session: `createAuth`'s `storage` option. Use [`webStorage`](#webstorage) in browsers, `secureStorage()` from `@monarcode/session-kit/expo` in Expo apps, and [`memoryStorage`](#memorystorage) in tests. Implement it yourself for another store. Values are strings in a format Session kit owns. Methods may return promises. Session kit runs them one at a time, in order, so a store that answers out of order is still safe. ### AuthStorage Where Session kit saves the session: `createAuth`'s `storage` option. Use webStorage in browsers, `secureStorage()` from `@monarcode/session-kit/expo` in Expo apps, and memoryStorage in tests. Implement it yourself for another store. Values are strings in a format Session kit owns. Methods may return promises. Session kit runs them one at a time, in order, so a store that answers out of order is still safe. | Prop | Type | Description | | ------------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `get` | `function` | Returns the value saved under `key`, or `null` when there's none. If it answers synchronously, a saved session shows before the first render. | | `set` | `function` | Saves `value` under `key`. `meta.expiresAt` is when the saved session stops being valid, in Unix milliseconds, for a store that can expire entries itself. | | `remove` | `function` | Removes the value saved under `key`. | | `subscribe?` | `function` | Calls `onChange` when another tab changes `key`, and returns a function that stops listening. Leave it out when nothing else shares the store. | | `lock?` | `function` | Runs `work` while holding the lock `name` in every tab that shares the store, so only one tab refreshes at a time. Aborting `signal` stops waiting for the lock. Leave it out when nothing else shares the store. | | `debug?` | `function` | Lets your adapter add its own events to the debug log, such as why it discarded a saved value. Each `createAuth` with `debug` on calls it with the key it saves under and a `report` function for that key. One adapter can serve several auths, so keep a `report` per key. `sensitive` says whether saved values may appear in `data`. | ### ClientCredentials The access token as your server gives it to the browser, from `serverAuth.clientCredentials` in `@monarcode/session-kit/server`. `expiresIn` counts from when the server answered, so the browser's clock doesn't matter. ### Credentials The current access token, from `credentials.get()`, to send with your API requests. `createAuthFetch` from `@monarcode/session-kit/http` does this for you. Members: - `sessionId` - `accessToken` - `expiresAt`: When the access token expires, as Unix time in milliseconds on **this device's clock**, so you can compare it with `Date.now()`. `undefined` when the token has no known expiry. ### FromAccessTokenOptions Options for [`fromAccessToken`](#fromaccesstoken). ### FromAccessTokenOptions Options for fromAccessToken. | Prop | Type | Description | | --------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `decode?` | `function` | Reads the claims from the access token. It may return a promise, but then a saved session can't show before the first render. The default doesn't verify the signature. That's fine in a browser, which trusts its own backend's responses. On a server, pass a function that verifies the token. Default: the JWT's payload, **unverified**. | ### MirrorAuth The browser client that [`createMirrorAuth`](#createmirrorauth) returns. It mirrors a session your server keeps in a cookie. It works with `AuthProvider`, the hooks, the router guards, `createAuthFetch` and `sessionBearer`, as a `createAuth` client does. It has no `lock`, `unlock` or `updateUser`. `U` is the user, and `In` is what `signIn` takes (`never` without the `signIn` option). Members: - `state`: The current [`AuthState`](#authstate), and a way to listen for changes. It's only ever `authenticated` or `unauthenticated`. A failed revalidation shows in `error` and changes nothing else. `subscribe` calls the listener on each later change, not with the current state. - `state.get` - `state.subscribe` - `getSession`: Resolves the session this client holds, or `null`. It doesn't ask the server. - `retry`: Asks your server for the session again, with `revalidate` or `endpoint`, and resolves it. If that fails, it rejects and keeps the current session. The code is `REFRESH_FAILED`, or the session route's own code, such as `INVALID_OPTIONS` for a request it refused. - `refresh`: Same as `retry()`. The server refreshes tokens itself, so this only asks for the session again. - `isCurrent`: Whether `session` is still the signed-in one, by its `sessionId`. Use it to drop a response that arrives after the user signed out or switched accounts. - `signOut`: Signs out on your server, then in this tab and the others. If the server's sign-out fails, it rejects and keeps the session. The code is `PERSISTENCE_FAILED`, or the session route's own code. - `adopt`: Takes a session your server returned, such as from your own sign-in or a profile update, and tells other tabs. Route guards run again when the account or the user changed. Throws `INVALID_SESSION` for anything but a session or `null`. - `mount`: Starts watching for other tabs' changes, and asks the server for the session when the tab becomes visible again (unless it answered in the last 10 seconds). Returns a function that stops. Calls are counted, and watching stops when the last one is stopped. `AuthProvider` and the router adapters call it for you. - `credentials`: The access token ([`Credentials`](#credentials)), for `createAuthFetch` and `sessionBearer`. Needs `endpoint` or the `credentials` option, or `get` and `renew` reject with `INVALID_OPTIONS`. The token is kept in memory only, and fetched again shortly before it expires. - `credentials.get`: Resolves the current access token, or `null` when signed out. Calls that overlap share one request. Rejects with `REFRESH_FAILED` when your server fails, or with the session route's own code, such as `INVALID_OPTIONS` without `clientCredentials`. Rejects with `SESSION_CHANGED` when the session changed meanwhile, here or on the server. - `credentials.renew`: Asks your server for a new access token after your API rejected `credentials`. Calls that overlap share one request. Resolves `null` when the server has signed out. Rejects with `SESSION_CHANGED` when the server holds another account, and follows it. - `credentials.reject`: Signs out because your API rejected `credentials` for good. Does nothing if a newer token has replaced them. - `signIn`: Signs in on your server with the `signIn` option, then takes the session it resolves and tells other tabs. If the option throws, it rejects with that error, unchanged, as a sign-in in a single-page app does. If it resolves anything but a session, it rejects with `INVALID_SESSION`. ### MirrorAuthOptions Options for [`createMirrorAuth`](#createmirrorauth). The client talks to your server through `endpoint`, your session route, or through functions of your own, such as server functions, which call `serverAuth` from `@monarcode/session-kit/server`. Pass `endpoint`, or `revalidate` and `signOut`. ### MirrorAuthOptions Options for createMirrorAuth. The client talks to your server through `endpoint`, your session route, or through functions of your own, such as server functions, which call `serverAuth` from `@monarcode/session-kit/server`. Pass `endpoint`, or `revalidate` and `signOut`. | Prop | Type | Description | | -------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | Names this auth. Tabs tell each other about changes on the `BroadcastChannel` `:auth`. Letters, digits, `_` or `-`, up to 64 characters. | | `session` | `union` | The session the page was rendered with, from `serverAuth.getSession`, or `null`. The client starts from it, so there's no loading state. | | `endpoint?` | `string` | The path of your session route on this site, such as `"/api/session"`, which answers with `sessionRoute` or `sessionHandler` from the server entry points. The client reads the session, signs out and gets the access token through it. Pass it, or `revalidate` and `signOut`. `revalidate`, `signOut` and `credentials` win when you pass them too. It's the full path, with your app's base path, such as React Router's `basename` or Next's `basePath`. It's called from the browser only: on the server, a call through it rejects with `INVALID_OPTIONS`. | | `revalidate?` | `union` | Reads the session on your server again, with `serverAuth.getSession`, such as through a server function. Required without `endpoint`. The client calls it when the tab becomes visible again, unless the server answered in the last 10 seconds, when another tab signs in or out, and from `retry()` and `refresh()`. Pass one when the session is also read while the server renders, where `endpoint` can't be called, as in TanStack Start. Default: a `GET` to `endpoint`. | | `signOut?` | `union` | Signs out on your server, with `serverAuth.signOut`. The client's `signOut()` calls it, then signs out this tab and the others. Required without `endpoint`. Default: a `POST` to `endpoint`. | | `signIn?` | `function` | Signs in on the server with `input`, and resolves the new session. Use `serverAuth.signIn`, or your own sign-in that ends with it. Without this option, the client has no `signIn`. Call your function, then pass its result to `adopt`. | | `credentials?` | `MirrorCredentials` | Gets the access token from your server (MirrorCredentials), so page scripts can call your API with `createAuthFetch` or `sessionBearer`. Default: through `endpoint`, which serves it when `createServerAuth` has `clientCredentials`. Without either, `credentials.get()` and `credentials.renew()` reject with `INVALID_OPTIONS`. | | `debug?` | `union` | Logs what the client does, like `createAuth`'s `debug`. | ### MirrorCredentials How a [`MirrorAuth`](#mirrorauth) gets the access token from your server. It's the `credentials` option of [`MirrorAuthOptions`](#mirrorauthoptions). Both functions call your own server functions, on the same origin and protected against CSRF, which call `serverAuth.clientCredentials`. ### RefreshFn Exchanges a refresh token for new tokens. It's the `refresh` option of [`AuthOptions`](#authoptions). The client calls it whenever it needs a new access token: shortly before the current one expires (while mounted), once it has expired, when your API rejects it, on `refresh()`, and on `retry()` once it has expired. It never runs two at once. Callers that need a refresh while one runs share its result. See [`RefreshResult`](#refreshresult) for what to return or throw. ### RefreshResult What your refresh callback ([`RefreshFn`](#refreshfn)) returns: - [`Tokens`](#tokens): the new tokens. They must last at least five seconds. Leave out `refreshToken` or `user` to keep the current one. - `null`: your backend rejected the refresh token. The user is signed out. For any other failure, such as a network error or a 5xx, throw. The session is kept, and the failure shows as a `REFRESH_FAILED` error whose `cause` is what you threw. An `AuthError` you throw keeps its own `code`. With `fromAccessToken`, return tokens only. The user is read from the new access token. ### Register Register your client's type here, once, so the hooks from `@monarcode/session-kit/react` and the Effect service carry your user. Without it, the user is typed `unknown`. Register the client you give `AuthProvider`: one from `createAuth`, or with server rendering from `createMirrorAuth`. Register a mirror client by the type its function returns, such as `ReturnType`. Anything else types the hooks and the Effect service as `never`. A TanStack Router app doesn't need it for its hooks: those from `@monarcode/session-kit/tanstack-router` are typed by the Router. See [`RegisteredAuth`](#registeredauth) for the type it gives. ### RegisteredAuth The client registered in [`Register`](#register), or a client with an `unknown` user when none is. It's `never` when what's registered isn't a client. ### RevokeFn Asks your backend to revoke the tokens of a session that just signed out. It's the `revoke` option of [`AuthOptions`](#authoptions). `signOut()` calls it after the user is already signed out, so a UI that follows the state never waits for it. `signOut()` itself resolves once it settles. If it fails, `state.error` shows `REVOKE_FAILED`, and `signOut()` still resolves. It isn't called when your backend ended the session itself, or when a `locked` session signs out, as its tokens aren't in memory. ### SafeReturnToOptions Options for [`safeReturnTo`](#safereturnto). ### SafeReturnToOptions Options for safeReturnTo. | Prop | Type | Description | | ------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `loginPath?` | `union` | Your sign-in page's path, or several. A path to it is replaced with `"/"`, so signing in never sends the user back to sign in. Matched by path, ignoring case, percent-encoding, trailing slashes and any query. Default: `"/login"` | ### Session Who is signed in: the session ID and the user, from `getSession()`. It holds no tokens, so it's safe to keep in route context or pass around. See [`Credentials`](#credentials) for the access token. Members: - `sessionId`: Identifies this sign-in. It stays the same across refreshes and profile updates, and is new on every sign-in. - `user` ### SessionOf The session type of a client: what its `getSession` resolves, without `null`. It takes any client: one from `createAuth` or `createMirrorAuth`, the server's from `createServerAuth`, or a request's session from it. The browser can take its types from the server's. An `import type` of the server's module is left out of the browser bundle. See [`UserOf`](#userof) for the user alone. ### SignInInput What `signIn` takes: the [`Tokens`](#tokens), plus the `user` when a schema validates it. With `fromAccessToken` (`I` is `never`), it takes tokens only. ### Tokens The tokens your backend issues. Pass them to `signIn`, and return them from your refresh callback ([`RefreshFn`](#refreshfn)). When the access token expires comes from the first of these that is set: 1. `expiresIn` or `expiresAt`. Pass one, not both. 2. A JWT access token's `exp - iat`, counted from when the client receives it. 3. A JWT access token's `exp` alone, compared with the device's clock. With none of them, the token never expires on its own. It's replaced only after your API rejects it. Prefer `expiresIn`, or a JWT with `iat`. Device clocks can be minutes off, and a clock that runs fast makes a fixed deadline look already passed, so `signIn` would reject the tokens. ### Tokens The tokens your backend issues. Pass them to `signIn`, and return them from your refresh callback (RefreshFn). When the access token expires comes from the first of these that is set: 1. `expiresIn` or `expiresAt`. Pass one, not both. 2. A JWT access token's `exp - iat`, counted from when the client receives it. 3. A JWT access token's `exp` alone, compared with the device's clock. With none of them, the token never expires on its own. It's replaced only after your API rejects it. Prefer `expiresIn`, or a JWT with `iat`. Device clocks can be minutes off, and a clock that runs fast makes a fixed deadline look already passed, so `signIn` would reject the tokens. | Prop | Type | Description | | --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `accessToken` | `string` | The token your API accepts. `createAuthFetch` sends it as `Authorization: Bearer `. | | `refreshToken?` | `string` | The token your refresh callback exchanges for new tokens. Without one, the user is signed out when the access token expires or is rejected. A refresh that returns none keeps the current one. | | `expiresIn?` | `number` | How long the access token lasts, in **seconds**, like OAuth's `expires_in` (`900` is 15 minutes). It's counted from when the client receives the token, so a wrong device clock doesn't matter. | | `expiresAt?` | `number` | When the access token expires, as Unix time in **milliseconds**, such as `Date.parse("2026-10-02T12:15:00Z")`. It's compared with the device's clock, so use it only when your backend gives no lifetime. | ### User The signed-in user's type, inferred from the `user` option: what `state.user` and `session.user` hold. See [`UserInput`](#userinput) for the user that `signIn` accepts. ### UserInput The user that `signIn` and `updateUser` accept, inferred from the `user` option. It differs from [`User`](#user) when the schema has defaults or transforms. It's `never` with `fromAccessToken`. The user is then read from the token, so `signIn` takes tokens only. ### UserOf The user type of a client, as [`SessionOf`](#sessionof) finds it: the `user` of its session. ### UserSource What `createAuth`'s `user` option takes: a schema, such as Zod's, that checks the `user` passed to `signIn`, or [`fromAccessToken`](#fromaccesstoken), which reads the user from the access token. ### WebStorageOptions Options for [`webStorage`](#webstorage). ### WebStorageOptions Options for webStorage. | Prop | Type | Description | | ------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `area?` | `union` | Which browser storage to use. `"local"` keeps the session across browser restarts and shares it with every tab. `"session"` gives each tab its own session, which ends with the tab. Avoid `"session"` with rotating refresh tokens. A duplicated tab starts with the same refresh token, and the first to use it signs the other out. Default: `"local"` | # React (https://session-kit.pages.dev/docs/reference/react) Import these from `@monarcode/session-kit/react`. To set it up, see [Read the session in React](https://session-kit.pages.dev/docs/getting-started#4-read-the-session-in-react). ## Functions ### createAuthHooks Creates React hooks typed for one auth client. Use it when an app has several clients: each call has its own context, so call it once per client. With one client, register it and use [`useAuth`](#useauth), [`useAuthClient`](#useauthclient) and [`AuthProvider`](#authprovider) instead. See [`AuthHooksOptions`](#authhooksoptions) to find the client without `AuthProvider`. ### useAuth Reads the current auth state, or the part `selector` picks, and re-renders when it changes. With a selector, it re-renders only when that part changes. The part is compared with `Object.is`. A selector that returns a new object or array each time re-renders on every change. It reads the client of the nearest [`AuthProvider`](#authprovider), typed by the client you register in `Register`, from `@monarcode/session-kit`. Throws `INVALID_OPTIONS` without an `AuthProvider` above. With TanStack Router, use the hooks from `@monarcode/session-kit/tanstack-router` instead: they read Router context, and need no `AuthProvider`. ### useAuthClient Returns the client of the nearest [`AuthProvider`](#authprovider), for actions such as `signIn` and `signOut`. It's typed by the client you register in `Register`, from `@monarcode/session-kit` ([`ProvidedAuth`](#providedauth)). Throws `INVALID_OPTIONS` without an `AuthProvider` above, as [`useAuth`](#useauth) does. ### useMirrorAuth Creates a `createMirrorAuth` client once, from the session the page was rendered with, and keeps it in step with your server. Call it in the component that renders `AuthProvider`. When a new server render brings another session, such as after a server action signs in or out, the client takes it and tells other tabs. When the session changes in the browser, it calls `onChange`. Throws `INVALID_OPTIONS` without a `create` or an `onChange` function. Creating the client here, rather than at module level, keeps one per request during server rendering. See [`UseMirrorAuthOptions`](#usemirrorauthoptions) for `create`, `session` and `onChange`. ## Components ### AuthProvider Gives a client to the hooks below it, and mounts it while rendered, which starts expiry timers and following other tabs. Render it once, around your app. Mounting restores the saved session, before the first paint with synchronous storage and schemas. On a server, nothing starts, as effects don't run there. Its `client` is typed by the client you register in `Register`, from `@monarcode/session-kit`. Until you register one, it takes any client ([`ProvidedAuth`](#providedauth)). See [`useAuth`](#useauth) to read the session below it. ## Types ### AuthHooks The provider and hooks [`createAuthHooks`](#createauthhooks) returns, typed for one client. ### AuthHooksOptions Options for [`createAuthHooks`](#createauthhooks). ### AuthHooksOptions Options for createAuthHooks. | Prop | Type | Description | | ------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `useClient?` | `function` | Finds the client some other way than `AuthProvider`, such as from a context of your own. It's called as a hook, inside every hook, on every render. The hooks then need no `AuthProvider`, so mount the client another way. Default: the client of the nearest `AuthProvider` from the same `createAuthHooks` call. | ### AuthProviderProps Props for [`AuthProvider`](#authprovider), and for the one that [`createAuthHooks`](#createauthhooks) returns. ### AuthProviderProps Props for AuthProvider, and for the one that createAuthHooks returns. | Prop | Type | Description | | ----------- | ----------- | -------------------------------------------------------------- | | `client` | `Client` | The client for this tree. On a server, create one per request. | | `children?` | `ReactNode` | The tree that reads `client` through the hooks. | ### AuthSource What the React bindings need from an auth client: its `state`, and `mount` to start background work while rendered. A `createAuth` or `createMirrorAuth` client fits. ### ProvidedAuth The client `AuthProvider` takes and `useAuthClient` returns: the one you register in `Register`, from `@monarcode/session-kit`. Until you register one, it's any client, with what every client has: its state, `mount`, `getSession`, `signOut`, `isCurrent` and `credentials`. Its user is then `unknown`. ### StateOf The state type of a client: what `useAuth()` returns (`AuthState`). ### UseMirrorAuthOptions Options for [`useMirrorAuth`](#usemirrorauth). ### UseMirrorAuthOptions Options for useMirrorAuth. | Prop | Type | Description | | ---------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `create` | `function` | Creates the client from the session the page was rendered with. It's called once, on the first render. | | `session` | `union` | The session your server rendered this page with, or `null`. When a new server render brings another one, the client takes it. | | `onChange` | `function` | Called when the session changes in the browser, such as after `signOut()` or in another tab. Make it render on the server again, so its redirects run: `router.refresh()` in Next.js, or `revalidate` from `useRevalidator()` in React Router. It can be a new function on each render: the latest one is called. | # TanStack Router (https://session-kit.pages.dev/docs/reference/tanstack-router) Import these from `@monarcode/session-kit/tanstack-router`. To set it up, see [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router). ## Functions ### connectAuth Starts auth for a Router whose context holds the client as `auth`. It restores the session, runs expiry timers, follows other tabs, and runs guards such as `requireSession` again when the session changes. Call it once, beside the Router. When the session changes, it also clears the Router's cached and preloaded route data, so one account's data never shows for the next. It returns a function that stops. Calling it again for the same Router returns that same function. Throws `INVALID_OPTIONS` when the Router's context has no client as `auth`. On a server, such as when TanStack Start renders its SPA shell, it does nothing. The shell keeps the `initializing` state, which shows your pending UI. ### redirectIfSignedIn Guards your sign-in page in `beforeLoad`, so a signed-in user goes straight to `redirectTo`, made safe with `safeReturnTo`. If the session can't be read, such as after a failed refresh or while locked, the sign-in page shows, so the user can sign in again. A `loginPath` that doesn't start with `/` rejects with `INVALID_OPTIONS`. ### requireSession Guards a route in `beforeLoad`, so only signed-in users get through. They get `{ session }` in route context, typed and never `null`, with no tokens in it. Signed-out users go to `loginPath`, with `?redirectTo=` set to where they were going. A locked session counts as signed out, as locking is for native apps and the router adapters don't unlock. Other errors, such as `REFRESH_FAILED` after a failed refresh, are rethrown to the route's error component, which can offer `auth.retry()`. A `loginPath` that doesn't start with `/` rejects with `INVALID_OPTIONS`. Render the route's children with `SessionOutlet`, and call `connectAuth`, so the guard runs again when the session changes. ### useAuth Reads the current auth state of the client in Router context, or the part `selector` picks, and re-renders when it changes. With a selector, it re-renders only when that part changes. Typed by your registered Router, as [`useAuthClient`](#useauthclient) is. Throws `INVALID_OPTIONS` when Router context has no `auth`. ### useAuthClient Returns the auth client from Router context, where it's `auth`, for actions such as `signIn` and `signOut`. It needs no `AuthProvider`: `connectAuth` mounts the client. The client's type comes from your registered Router ([`RouterAuth`](#routerauth)). Router context is per request in TanStack Start, so this is safe during server rendering. Throws `INVALID_OPTIONS` when Router context has no `auth`. ## Components ### SessionOutlet Renders the child routes of a route guarded by `requireSession`, but only while the session it accepted is still the signed-in one. After a change, such as a sign-out or another account signing in, it shows `pending` until the guard has run again. A locked or `unavailable` session shows `pending` too, until the guard redirects or throws. Child routes remount for each account, so nothing from one stays mounted for the next. Token refreshes and profile updates keep them mounted. UI the route renders around the outlet, such as a sidebar, isn't guarded this way. Read the user there from state, where it may be `null`. Throws `INVALID_OPTIONS` when neither an `AuthProvider` nor Router context has a client. ## Types ### AuthRouter What [`connectAuth`](#connectauth) needs from a TanStack Router: the client in its context as `auth`, and the methods that run guards again and clear cached route data. A Router made by `createRouter` with `context: { auth }` fits. Use it to type a function that takes your Router. ### RedirectIfSignedInOptions Options for [`redirectIfSignedIn`](#redirectifsignedin). ### RedirectIfSignedInOptions Options for redirectIfSignedIn. | Prop | Type | Description | | ------------ | --------- | -------------------------------------------------------------------------------------------------------- | | `redirectTo` | `unknown` | Where to send a signed-in user, usually the `redirectTo` search param. It's checked with `safeReturnTo`. | | `loginPath?` | `union` | Your sign-in page's path, or several. `redirectTo` never sends the user back to one. Default: `"/login"` | ### RequireSessionOptions Options for [`requireSession`](#requiresession). ### RequireSessionOptions Options for requireSession. | Prop | Type | Description | | ------------ | -------- | -------------------------------------------------------------------------------------------------------- | | `location` | `object` | The route's location, from `beforeLoad`'s `location`. Signed-out users come back to it after signing in. | | `loginPath?` | `string` | Your sign-in page's path, starting with `/`. Default: `"/login"` | ### RouterAuth The auth client type in your registered Router's context, as `auth`, which [`useAuthClient`](#useauthclient) returns. It's `never` until the Router is registered. ### SessionOutletProps Props for [`SessionOutlet`](#sessionoutlet). ### SessionOutletProps Props for SessionOutlet. | Prop | Type | Description | | ---------- | ------------ | ------------------------------------------------------------------------------------------ | | `pending?` | `ReactNode` | Shown while the guard checks the session again, such as after a sign-out. | | `client?` | `AuthSource` | The client to watch. Default: the nearest `AuthProvider`'s, then `auth` in Router context. | # React Router (https://session-kit.pages.dev/docs/reference/react-router) Import these from `@monarcode/session-kit/react-router`. To set it up, see [React Router](https://session-kit.pages.dev/docs/setups/react-router). ## Functions ### redirectIfSignedIn Sends a signed-in user from your sign-in page straight to `redirectTo`, made safe with `safeReturnTo`, inside a loader of your own. When the loader does nothing else, use [`redirectIfSignedInLoader`](#redirectifsignedinloader) instead. If the session can't be read, such as after a failed refresh or while locked, the sign-in page shows, so the user can sign in again. A `loginPath` that doesn't start with `/` rejects with `INVALID_OPTIONS`. ### redirectIfSignedInLoader Makes the loader for your sign-in page, for `loader` or `clientLoader`. It reads `?redirectTo=` from the URL and works as [`redirectIfSignedIn`](#redirectifsignedin) does. A `loginPath` that doesn't start with `/` throws `INVALID_OPTIONS` when the loader is made. ### requireSession Checks for a signed-in user inside a loader of your own, in data or framework mode, and resolves `{ session }`, which holds no tokens. When the loader does nothing else, use [`requireSessionLoader`](#requiresessionloader) as the loader instead. Call it in a page's loader that calls your API, even under a guarded layout. React Router runs nested routes' loaders at the same time, so the page's doesn't wait for the layout's guard. Signed-out users go to `loginPath`, with `?redirectTo=` set to the path and query they asked for. React Router leaves the `#fragment` out of a loader's request, so it isn't kept. A locked session counts as signed out, as locking is for native apps and the router adapters don't unlock. Other errors, such as `REFRESH_FAILED` after a failed refresh, are rethrown to the route's error element, which can offer `auth.retry()`. A `loginPath` or `basename` that doesn't start with `/` rejects with `INVALID_OPTIONS`. Use `SessionOutlet` as the route's element, and call `useAuthRevalidation`, so the loader runs again when the session changes. ### requireSessionLoader Makes the loader that guards a route, for `loader` or `clientLoader`, so only signed-in users get through. It resolves `{ session }`, typed with the client's user, and works as [`requireSession`](#requiresession) does. Pass `loginPath` or `basename` when they aren't the defaults. A `loginPath` or `basename` that doesn't start with `/` throws `INVALID_OPTIONS` when the loader is made. ### useAuthRevalidation Runs your loaders again when the session changes, so guards such as `requireSession` check it again. That's on sign-in, sign-out, a switch of account, a profile update, a lock, or a refresh that fails once the access token has expired. A token refresh alone doesn't, nor does a failed refresh while the token is still valid. Call it once in the root layout, in data or framework mode. Declarative mode has no loaders, and React Router throws when the hook runs there. It watches `client`, or the nearest `AuthProvider`'s, and doesn't mount the client itself. Throws `INVALID_OPTIONS` without either. ## Components ### SessionOutlet Renders child routes only while someone is signed in, in any mode. It needs an `AuthProvider` above it, or a `client`. Signed-out users, and a locked session, go to `loginPath`, with `?redirectTo=` set to where they were. In declarative mode, that makes it the guard. In data or framework mode, render it from a route whose loader returns `requireSession`'s result. When the account changes, it shows `pending` until the loader has run again, so no child sees the last account's data. Child routes remount for each account, but not on token refreshes or profile updates. UI the route renders around the outlet, such as a sidebar, isn't guarded this way. Read the user there from state, where it may be `null`. Throws `INVALID_OPTIONS` when it has neither an `AuthProvider` around it nor a `client`. ## Types ### RedirectIfSignedInLoader The loader that [`redirectIfSignedInLoader`](#redirectifsignedinloader) makes. It reads `redirectTo` from the request's URL, and resolves `null` for a signed-out user. ### RedirectIfSignedInLoaderOptions Options for [`redirectIfSignedInLoader`](#redirectifsignedinloader). ### RedirectIfSignedInLoaderOptions Options for redirectIfSignedInLoader. | Prop | Type | Description | | ------------ | ------- | -------------------------------------------------------------------------------------------------------- | | `loginPath?` | `union` | Your sign-in page's path, or several. `redirectTo` never sends the user back to one. Default: `"/login"` | ### RedirectIfSignedInOptions Options for [`redirectIfSignedIn`](#redirectifsignedin). ### RedirectIfSignedInOptions Options for redirectIfSignedIn. | Prop | Type | Description | | ------------ | --------- | -------------------------------------------------------------------------------------------------------- | | `loginPath?` | `union` | Your sign-in page's path, or several. `redirectTo` never sends the user back to one. Default: `"/login"` | | `redirectTo` | `unknown` | Where to send a signed-in user, usually the `redirectTo` search param. It's checked with `safeReturnTo`. | ### RequireSessionLoader The loader that [`requireSessionLoader`](#requiresessionloader) makes. It resolves `{ session }`, typed with the client's user. ### RequireSessionLoaderOptions Options for [`requireSessionLoader`](#requiresessionloader). ### RequireSessionLoaderOptions Options for requireSessionLoader. | Prop | Type | Description | | ------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `loginPath?` | `string` | Your sign-in page's path, starting with `/`. Use the same one as `SessionOutlet`'s. Default: `"/login"` | | `basename?` | `string` | The router's `basename`, if it has one. Loaders see URLs that include it, but redirects add it again, so `redirectTo` must leave it out. | ### RequireSessionOptions Options for [`requireSession`](#requiresession). ### RequireSessionOptions Options for requireSession. | Prop | Type | Description | | ------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `loginPath?` | `string` | Your sign-in page's path, starting with `/`. Use the same one as `SessionOutlet`'s. Default: `"/login"` | | `basename?` | `string` | The router's `basename`, if it has one. Loaders see URLs that include it, but redirects add it again, so `redirectTo` must leave it out. | | `request` | `object` | The loader's `request`. Signed-out users come back to its URL after signing in. | ### SessionOutletProps Props for [`SessionOutlet`](#sessionoutlet). ### SessionOutletProps Props for SessionOutlet. | Prop | Type | Description | | -------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `loginPath?` | `string` | Your sign-in page's path, starting with `/`. Use the same one as `requireSession`'s. Default: `"/login"` | | `pending?` | `ReactNode` | Shown while the saved session is read and, in data or framework mode, until the loader has accepted a new session. | | `unavailable?` | `function` | Shown when the session is `unavailable`, such as after a failed refresh (UnavailableProps). Without it, the error is thrown to the nearest error boundary or error element. | | `client?` | `RetryableSource` | The client to watch. Default: the nearest `AuthProvider`'s. | ### UnavailableProps What the `unavailable` render prop of an adapter component, such as React Router's `SessionOutlet` or Expo's `SessionGate`, receives. ### UnavailableProps What the `unavailable` render prop of an adapter component, such as React Router's `SessionOutlet` or Expo's `SessionGate`, receives. | Prop | Type | Description | | ------- | ---------- | ------------------------------------------------------------------------------- | | `error` | `union` | Why access is unavailable, such as a failed refresh or a locked keychain. | | `retry` | `function` | Tries again, as `auth.retry()` does. A repeated failure stays in `state.error`. | # React Router server (https://session-kit.pages.dev/docs/reference/react-router-server) Import these from `@monarcode/session-kit/react-router/server`. To set it up, see [React Router with server rendering](https://session-kit.pages.dev/docs/setups/react-router-ssr). ## Functions ### cookieJarMiddleware Server middleware that gives each request a `CookieJar`, found with [`routerJar`](#routerjar). It sets the cookies written to the jar on the response, redirects and error responses included. [`sessionMiddleware`](#sessionmiddleware) starts with it, so most apps don't list it themselves. To refresh your own way, list it first in the root route's `middleware`, so it wraps the rest. It needs React Router 8, or 7.9 and later with `future.v8_middleware`. The jar can set cookies until the response leaves the middleware, which first waits for a refresh under way, so its new tokens are saved. After that, such as while a loader's deferred data streams, it's read-only. Nothing is saved, and a call that needs a refresh rejects with `REFRESH_FAILED`. Refresh before rendering, with `refreshIfDue` in middleware. ### redirectIfSignedIn Makes the loader for your sign-in page, which sends a signed-in user on to the page's `redirectTo` search param, made safe with `safeReturnTo`. Signed-out users see the page. React Router adds the app's `basename` to the redirect. If the session can't be read, such as after a failed refresh, the sign-in page shows, so the user can sign in again. Throws `INVALID_OPTIONS` when a `loginPath` doesn't start with `/`. It needs [`sessionMiddleware`](#sessionmiddleware) in the root route. ### requireSession Makes server middleware that lets only signed-in users through to a route and the routes nested in it ([`SessionGuard`](#sessionguard)). Their loaders and actions get the session from its `session(context)`, never `null`. Signed-out users go to `loginPath`, with `?redirectTo=` set to the URL they asked for, for page loads and navigation in the browser alike. Other errors, such as `REFRESH_FAILED` after a failed refresh, reach the route's error boundary. List it in the guarded route's `middleware`, with [`sessionMiddleware`](#sessionmiddleware) in the root route. Server middleware runs during navigation in the browser only when a route has a loader to fetch, so give the guarded route a `loader`, even `() => null`. Throws `INVALID_OPTIONS` when `loginPath` or `basename` doesn't start with `/`. See [`redirectIfSignedIn`](#redirectifsignedin) for the sign-in page. ### routerAuth Returns a function that gives the session of the request React Router is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Make it once, at module level. Calling it throws `INVALID_OPTIONS` when the middleware hasn't run for `context`, as [`routerJar`](#routerjar) does. ### routerJar The `CookieJar` for the request React Router is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`routerAuth`](#routerauth) passes it for you. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Every call during one request returns the same jar. Throws `INVALID_OPTIONS` when the middleware hasn't run for `context`, such as in a client loader. ### sessionMiddleware The root route's server middleware, which gives each request a cookie jar and refreshes the session while the response can still set the cookie. Export it as the root route's `middleware`, or spread it first into a list of your own. It refreshes access that expires within `within` seconds, before any loader reads it. A failed refresh doesn't fail the request. Loaders read the session as usual, and an error there reaches the route's error boundary. It sets `Cache-Control` to `private, no-store` on each response that doesn't set its own. Pass `cacheControl` for another value, or `false` to leave every response as it is (`SessionMiddlewareOptions`). It's [`cookieJarMiddleware`](#cookiejarmiddleware) followed by the refresh, and needs React Router 8, or 7.9 and later with `future.v8_middleware`. Throws `INVALID_OPTIONS` when `within` is negative. See [`requireSession`](#requiresession) to let only signed-in users through. ### sessionRoute Makes the loader and action of your session route, a resource route that answers `createMirrorAuth`'s `endpoint`: the browser client reads the session, signs out and gets the access token through it. It needs [`sessionMiddleware`](#sessionmiddleware) in the root route. It answers this site's own pages only, as `sessionHandler` from `@monarcode/session-kit/server` explains, and serves the access token only when `createServerAuth` has `clientCredentials`. Sign-in stays your own action. Export the loader and action one by one, as the example does. React Router's build can't remove a destructured `export const { loader }` from the browser's bundle, and fails. ## Types ### RouterArgs The arguments React Router passes to server middleware and loaders, as far as the middleware and guards here read them. It's typed by its shape, like [`RouterContextLike`](#routercontextlike). ### RouterContextLike The `context` React Router passes to server middleware, loaders and actions in framework mode: a `RouterContextProvider`, one per request. [`routerAuth`](#routerauth) and [`cookieJarMiddleware`](#cookiejarmiddleware) find the request by it. It's typed by its shape, so this entry point doesn't depend on React Router's types. ### RouterLoader A loader typed by its shape, such as [`redirectIfSignedIn`](#redirectifsignedin)'s. ### RouterMiddleware Server middleware for a route's `middleware`, typed by its shape. ### RouterSessionRoute The loader and action [`sessionRoute`](#sessionroute) makes, for a resource route. ### SessionGuard Server middleware that lets only signed-in users through, made by [`requireSession`](#requiresession). Call `session(context)` in the loaders and actions it guards for the session, which is never `null` there. Members: - `session`: The request's session, once the guard has let it through. It's read when called, so a change by an action shows. Throws `INVALID_OPTIONS` when the guard hasn't run for this request, such as in a route outside the ones it guards. Throws `UNAUTHENTICATED` once an action signed out, and `REFRESH_FAILED` when the access token can no longer be refreshed. ### SessionGuardOptions Options for [`requireSession`](#requiresession). ### SessionGuardOptions Options for requireSession. | Prop | Type | Description | | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `loginPath?` | `string` | Your sign-in page's path in the app, starting with `/`, without the `basename`. Default: `"/login"` | | `basename?` | `string` | The app's `basename`, if it has one. React Router adds it to a loader's redirects but not to middleware's, so the guard adds it to its own. It leaves it out of `redirectTo`, which a loader then uses. | # HTTP (https://session-kit.pages.dev/docs/reference/http) Import these from `@monarcode/session-kit/http`. To set it up, see [Authenticated requests](https://session-kit.pages.dev/docs/client/requests). ## Functions ### createAuthFetch Creates a `fetch` for your API ([`AuthFetch`](#authfetch)) that sends the current access token as `Authorization: Bearer`. After a 401, it gets a new access token once. `GET` and `HEAD` requests are then sent again; other requests resolve the 401 for you to retry. If the request sent again gets a 401 too, the user is signed out, unless `signOutOnRepeated401` is off. Rejects with `UNAUTHENTICATED` when signed out, unless `optional` sends the request without a token, and with `LOCKED` while locked. When a refresh fails, it rejects with that failure, such as `REFRESH_FAILED`. If the session changes during a request, it rejects with `SESSION_CHANGED` rather than resolve a response meant for another account. The token never leaves your API. A request for another origin, with a username or password in its URL, or with an invalid URL rejects with `INVALID_OPTIONS`, as does a `Request` from another realm or a polyfill. A missing or invalid `baseUrl` throws `INVALID_OPTIONS`. While signed in, a request's own `Authorization` header is replaced. A redirect isn't followed: the request rejects as `fetch` does when it refuses one, with a `TypeError` in browsers and Node.js. On React Native before Expo SDK 58, `fetch` follows a redirect whatever it's told. The response is still refused, with a `TypeError`, but the redirected request has already gone out, so don't let your API redirect requests that carry a token. `fetch`'s own failures, such as a network error, and an `init` that `Request` refuses, reject as `fetch` and `Request` do. An HTTP client that takes a custom `fetch`, such as ky or openapi-fetch, can take this one. Its requests then get the same checks, and the same handling of a 401. See [`AuthFetchOptions`](#authfetchoptions) for `baseUrl`, `optional` and `signOutOnRepeated401`. ## Types ### AuthFetch The `fetch` that [`createAuthFetch`](#createauthfetch) returns. Call it with a path under your API's base URL, and `init` as you would pass to `fetch`. It takes a `URL` or a `Request` too, as `fetch` does. A `Request` with a body can be sent once, as with `fetch`. To retry a write after a 401, send a clone you kept. A call that rejects before sending anything leaves the `Request` unused. `init` takes what `Request` takes. An option that only a runtime's own `fetch` reads, such as Next.js's `next`, isn't passed on. Use the name to type a prop, a context or a test fake that stands in for it. See [`createAuthFetch`](#createauthfetch) for how it sends the token and handles a 401. ### AuthFetchClient The part of an auth client that [`createAuthFetch`](#createauthfetch) uses. A `createAuth` or `createMirrorAuth` client fits, and so does a request's session on the server (`RequestAuth`). ### AuthFetchOptions Options for [`createAuthFetch`](#createauthfetch). ### AuthFetchOptions Options for createAuthFetch. | Prop | Type | Description | | ----------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `baseUrl` | `string` | Your API's base URL. It must be absolute, such as `https://api.example.com/`. The access token goes only to requests on its origin. A path is resolved against it as a link is against a page's address. End it with `/`, so that `"orders"` lands under it. | | `optional?` | `union` | Whether a request made while signed out is sent without an `Authorization` header, rather than rejecting with `UNAUTHENTICATED`. Set `true` when one `authFetch` serves public and private endpoints. A locked client still rejects with `LOCKED`. A 401 to a request sent without a token comes back as it is. Default: `false` | | `signOutOnRepeated401?` | `union` | Whether a second 401, after a successful refresh, signs the user out. Set `false` when some endpoints answer 401 for reasons other than a rejected token, so a second 401 from them doesn't sign users out. Without a refresh token or a `refresh` option, the first 401 still does. Default: `true` | # Server (https://session-kit.pages.dev/docs/reference/server) Import these from `@monarcode/session-kit/server`. To set it up, see [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions). ## Functions ### createServerAuth Creates the server side of Session kit ([`ServerAuth`](#serverauth)). It keeps both tokens and the user in an encrypted, `httpOnly` cookie, so page scripts never see the refresh token. Create one per app, at module level, and give it to your framework's adapter for each request's session. Throws `INVALID_OPTIONS` for options it can't use, such as a bad `name`. A missing or short `secret` is reported later, when a method first runs. See [`ServerAuthOptions`](#serverauthoptions) for every option. ### sessionHandler Makes the handler for your session route ([`SessionHandler`](#sessionhandler)), which answers `createMirrorAuth`'s `endpoint`. A `GET` reads the session. A `POST` signs out, or gets or renews the access token for page scripts. It answers only this site's own pages, by the `Sec-Fetch-Site` header, so another site can't sign the user out or ask for a token. Browsers send it to https and localhost pages, since 2023 (Safari 16.4). Without it, as on plain http, a `GET` is answered, and a `POST` needs an `Origin` header that matches the request's URL. Anything else is refused with 403. Every answer has `Cache-Control: no-store`. The access token is served only when `createServerAuth` has `clientCredentials`. A failure answers with its `AuthErrorCode`, which the browser client rejects with. Anything that isn't an `AuthError` is thrown, for your framework to log. A request it can't read answers 400 with `INVALID_OPTIONS`. Otherwise a failure's status is 401 for `UNAUTHENTICATED`, 409 for `SESSION_CHANGED` and 500 for any other code. That includes `INVALID_OPTIONS` from the server's setup, such as a missing secret or middleware, so your monitoring sees it. A method other than `GET` or `POST` answers 405. Each framework's `sessionRoute` wraps it in a route. Use it directly on a server without an adapter, with the request's cookie jar. ## Types ### ClientCredentials The access token as your server gives it to the browser, from `serverAuth.clientCredentials` in `@monarcode/session-kit/server`. `expiresIn` counts from when the server answered, so the browser's clock doesn't matter. ### CookieJar Reads and writes one request's cookies, for `createServerAuth`'s methods. The framework adapters, such as `nextJar` and `startJar`, build one. Elsewhere, wrap the request's cookies and the response's `Set-Cookie`. Make a new jar for each request, and pass it to every call while handling that request, so they share one refresh and see each other's writes. Never keep one at module level, or one request's session would show in the next. ### CookieJar Reads and writes one request's cookies, for `createServerAuth`'s methods. The framework adapters, such as `nextJar` and `startJar`, build one. Elsewhere, wrap the request's cookies and the response's `Set-Cookie`. Make a new jar for each request, and pass it to every call while handling that request, so they share one refresh and see each other's writes. Never keep one at module level, or one request's session would show in the next. | Prop | Type | Description | | ---------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `get` | `function` | Returns the request's cookie `name`, or `undefined` when it has none. | | `set` | `function` | Sets cookie `name` on the response. | | `delete` | `function` | Removes cookie `name`, with the attributes it was set with. | | `writable` | `union` | Whether the response can still set cookies. It's `false` where the framework can't, such as while a Next.js Server Component renders. Then nothing is refreshed or saved, and calls that would write reject, as each `serverAuth` method says. | ### CookieOptions The session cookie's attributes, as [`CookieJar`](#cookiejar)'s `set` and `delete` receive them. Every framework's cookie API takes this shape, or maps from it in a line. ### CookieOptions The session cookie's attributes, as CookieJar's `set` and `delete` receive them. Every framework's cookie API takes this shape, or maps from it in a line. | Prop | Type | Description | | ---------- | -------- | ---------------------------------------------------------------- | | `httpOnly` | `true` | Always `true`: page scripts can't read the session cookie. | | `secure` | `union` | Whether the cookie is sent over HTTPS only. | | `sameSite` | `union` | Which cross-site requests carry the cookie. | | `path` | `string` | The paths that receive the cookie. | | `domain?` | `string` | The domain that receives the cookie, or none for this host only. | | `maxAge?` | `number` | Lifetime in seconds. Absent when deleting. | ### RefreshIfDueOptions Options for [`ServerAuth`](#serverauth)'s `refreshIfDue`. ### RefreshIfDueOptions Options for ServerAuth's `refreshIfDue`. | Prop | Type | Description | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `within?` | `number` | Refreshes when the access token expires within this many seconds, so it lasts through the request. Keep it well below the token's lifetime: a token that lives less than `within` is refreshed on every request. Default: `60` | ### RequestAuth One request's session: what [`ServerAuth`](#serverauth) does for a request, without its [`CookieJar`](#cookiejar). `startAuth` from `@monarcode/session-kit/tanstack-start/server` and `routerAuth` from `@monarcode/session-kit/react-router/server` give you one, and so do `readOnly()` and `writable()` from `nextSession` in `@monarcode/session-kit/next`. Elsewhere, `serverAuth.forRequest(jar)` does. It's shaped like a client, so code written for one works on the server with it, such as `createAuthFetch` from `@monarcode/session-kit/http`. `U` is the user, and `I` is the user `signIn` accepts, as for [`ServerAuth`](#serverauth). Write `SessionOf` or `UserOf` from `@monarcode/session-kit` for its types. Some requests can't set cookies: a Next.js page, or a React Router loader once its response has left the middleware. There, nothing can be saved, so `signIn`, `signOut`, `updateUser` and `refreshIfDue` reject with `INVALID_OPTIONS`. `getSession` still resolves, and `credentials.get` rejects with `REFRESH_FAILED` once the access token has expired. Refresh first, in middleware or a proxy, with `refreshIfDue`. Members: - `getSession`: Resolves who is signed in, from the cookie, or `null`. It holds no tokens, so you can return it to the browser, such as from a server function or a loader. An expired access token is refreshed first, and a refresh token your backend rejects signs out. Rejects with `REFRESH_FAILED` when that refresh fails. Where the request can't set cookies, the session is returned as the cookie holds it. - `refreshIfDue`: Refreshes the access token when it has less than `within` seconds left ([`RefreshIfDueOptions`](#refreshifdueoptions)), then resolves the session. Each adapter's middleware calls it before rendering, so pages get a fresh token to read. Call it yourself only in middleware of your own. It refreshes at most once per request. A failed refresh is ignored while the access token still works. Once the token has expired, it rejects with `REFRESH_FAILED`. Rejects with `INVALID_OPTIONS` for a negative `within`, or where the request can't set cookies. - `signIn`: Signs in by sealing your backend's tokens and the user into the cookie, replacing any session it held. Pass what your backend's sign-in returned: `accessToken`, `refreshToken` if there is one, and `user` unless the user comes from the access token. Resolves the new session, which holds no tokens, so you can return it to the browser. It never calls your backend, and trusts what it's given. If the browser signs in with your backend and sends the tokens and the user, the cookie's user is what the browser said, until a refresh or `updateUser` replaces it. Show it, but let your backend authorize with the access token. To trust it, check the input first, or sign in on the server. Rejects with `USER_VALIDATION_FAILED` for a user your schema rejects, with `INVALID_SESSION` for tokens that already expired, and with `PERSISTENCE_FAILED` for a session too large for the cookie. Rejects with `INVALID_OPTIONS` where the request can't set cookies. - `signOut`: Signs out by clearing the cookie, then calls `revoke` and waits for it. A failed `revoke` doesn't reject. The browser's client signs out through your session route, so call it yourself only from server code of your own, such as an action. Rejects with `INVALID_OPTIONS` where the request can't set cookies. - `credentials`: The access token (`Credentials`), for server code that calls your API. `get`, `renew` and `reject` work like the client's. - `clientCredentials`: The access token for your own page scripts ([`ClientCredentials`](#clientcredentials)), with the `clientCredentials` option. Your session route serves these. Expose them yourself only to your own site's pages, protected against CSRF. Both reject with `INVALID_OPTIONS` without the option. - `isCurrent`: Whether `session` is the one this request has read. - `state`: The state of this request's session, an `AuthState`. It's `initializing` until a call reads the cookie. Where the request can set cookies and the access token has expired, it stays so until a call refreshes it. It's `unavailable` when the request can't set cookies and the access token has expired, or the secret is missing. A Next.js page, which can't set cookies, follows the session that the same request's Server Function signed in or refreshed. Listeners must not throw. Their errors are rethrown asynchronously, which is an uncaught exception on a server. - `updateUser`: Replaces the signed-in user in the cookie, such as after a profile edit, and resolves the session. Pass the user, or an async function that fetches it. The session ID stays. Rejects with `UNAUTHENTICATED` when signed out, and with `USER_VALIDATION_FAILED` for a user your schema rejects, or when the function rejects or times out. Rejects with `INVALID_OPTIONS` where the request can't set cookies. ### ServerAuth The server side of Session kit, from [`createServerAuth`](#createserverauth). It keeps the session in an encrypted cookie. Your framework's adapter gives you one request's session ([`RequestAuth`](#requestauth)), with every method and no cookie jar. Its methods are here too, each taking the request's [`CookieJar`](#cookiejar), for a server without an adapter. `forRequest(jar)` gives that request's session, which alone has `isCurrent` and `state`. `U` is the user, and `I` is the user `signIn` accepts, or `never` with `fromAccessToken`. Write `typeof serverAuth` rather than spelling them out. Nothing is kept between requests except a short record of new tokens, so parallel requests that carry the same cookie share one refresh. That record belongs to one `createServerAuth` call. A framework may load your module once per bundle, making several, so with rotating refresh tokens, give your backend a short reuse window. `signIn` trusts what it's given. [`RequestAuth`](#requestauth)'s `signIn` says what that means. Members: - `getSession`: [`RequestAuth`](#requestauth)'s `getSession`, for `jar`. - `refreshIfDue`: [`RequestAuth`](#requestauth)'s `refreshIfDue`, for `jar`. It refreshes at most once per jar. - `signIn`: [`RequestAuth`](#requestauth)'s `signIn`, for `jar`. - `signOut`: [`RequestAuth`](#requestauth)'s `signOut`, for `jar`. - `credentials`: [`RequestAuth`](#requestauth)'s `credentials`, for `jar`. - `credentials.get`: Resolves the access token for `jar`, or `null`, as [`RequestAuth`](#requestauth)'s `credentials.get` does. With a read-only jar, an expired one rejects with `REFRESH_FAILED`. - `credentials.renew`: Gets a new access token for `jar` after your API rejected `credentials`, as [`RequestAuth`](#requestauth)'s `credentials.renew` does. - `credentials.reject`: Signs `jar`'s session out because your API rejected `credentials` for good, unless they're no longer current. Rejects with `INVALID_OPTIONS` given a read-only jar. - `clientCredentials`: [`RequestAuth`](#requestauth)'s `clientCredentials`, for `jar`. - `clientCredentials.get`: The access token for your page scripts, for `jar`, as [`RequestAuth`](#requestauth)'s `clientCredentials.get` gives it. - `clientCredentials.renew`: Renews the page scripts' access token for `jar`, as [`RequestAuth`](#requestauth)'s `clientCredentials.renew` does. - `forRequest`: This request's session ([`RequestAuth`](#requestauth)), for code that has the request's jar. The same jar always gives the same object. - `updateUser`: [`RequestAuth`](#requestauth)'s `updateUser`, for `jar`. ### ServerAuthOptions Options for [`createServerAuth`](#createserverauth). `user`, `refresh`, `revoke`, `maxAge` and `debug` work as they do for `createAuth`. ### ServerAuthOptions Options for createServerAuth. `user`, `refresh`, `revoke`, `maxAge` and `debug` work as they do for `createAuth`. | Prop | Type | Description | | -------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | Names this auth and its cookie, `.session`, which is split into `.session.0…n` when large. Up to 64 letters, digits, `_` or `-`. | | `user` | `Src` | Where the user comes from: a schema that checks the `user` passed to `signIn`, or `fromAccessToken(…)`. The cookie is trusted once sealed, but `signIn` doesn't check its input with your backend (RequestAuth's `signIn` says what to do). | | `secret` | `union` | The key that seals the cookie, with AES-256-GCM: at least 32 random characters, kept out of your code and the browser. Pass a list to rotate keys. The first seals, and any of them opens, so sessions survive a new secret. A cookie none of them opens reads as signed out. It's checked when a method first runs, not at creation, so build tools that load your module without it, such as `next build`, still work. Without a valid secret, every method rejects with `INVALID_OPTIONS`, and a request's `state` is `unavailable`. | | `refresh?` | `RefreshFn>>` | Exchanges a refresh token for new tokens, as RefreshFn says. | | `revoke?` | `RevokeFn` | Asks your backend to revoke the tokens after `signOut` (RevokeFn). | | `maxAge?` | `number` | How long the cookie lasts, in seconds. Each save starts it again. Default: 30 days. | | `cookie?` | `SessionCookieOptions` | The session cookie's attributes (SessionCookieOptions). Default: each attribute's own. | | `clientCredentials?` | `union` | Lets your session route, or a request's `clientCredentials`, give the access token to your own page scripts. The refresh token never leaves the server. Without it, `clientCredentials` rejects with `INVALID_OPTIONS`. Default: `false` | | `debug?` | `union` | Logs what Session kit does on the server, like `createAuth`'s `debug` option. | ### SessionCookieOptions The session cookie's attributes: the `cookie` option of [`ServerAuthOptions`](#serverauthoptions). The cookie is always `httpOnly`. ### SessionCookieOptions The session cookie's attributes: the `cookie` option of ServerAuthOptions. The cookie is always `httpOnly`. | Prop | Type | Description | | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `secure?` | `union` | Sends the cookie over HTTPS only. Turn it off only for plain-http development on `localhost`. Default: `true` | | `sameSite?` | `union` | Which cross-site requests send the cookie. `"none"` needs `secure`, or `createServerAuth` throws `INVALID_OPTIONS`. Default: `"lax"` | | `path?` | `string` | The paths the cookie is sent to. Default: `"/"` | | `domain?` | `string` | Shares the cookie with subdomains. Default: this host only. | ### SessionHandler Answers the browser client's requests to your session route, for one request and its cookie jar. [`sessionHandler`](#sessionhandler) makes one. ### SessionMiddlewareOptions Options for the middleware that refreshes before each request: `refreshSession` from `@monarcode/session-kit/tanstack-start/server` and `sessionMiddleware` from `@monarcode/session-kit/react-router/server`. ### SessionMiddlewareOptions Options for the middleware that refreshes before each request: `refreshSession` from `@monarcode/session-kit/tanstack-start/server` and `sessionMiddleware` from `@monarcode/session-kit/react-router/server`. | Prop | Type | Description | | --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `within?` | `number` | Refreshes when the access token expires within this many seconds, as RefreshIfDueOptions explains. Default: `60` | | `cacheControl?` | `union` | The `Cache-Control` header for every response that doesn't set its own, as each one depends on who is signed in. `false` leaves every response as it is. Default: `"private, no-store"` | # TanStack Start (https://session-kit.pages.dev/docs/reference/tanstack-start) Import these from `@monarcode/session-kit/tanstack-start`. To set it up, see [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start). ## Functions ### connectSession Connects a TanStack Start router to the browser client in its context, as `auth`. Call it once in `getRouter`, after `createRouter`. It carries the session from the server render to the browser. On the server, the page is sent with the session [`loadSession`](#loadsession) read. In the browser, the client starts from it before the first render, without running guards again or telling other tabs. When the server didn't read the session, the browser reads it itself. In the browser, it then does what `connectAuth` does for a TanStack Router app: guards run again when the session changes. It returns a function that stops. Throws `INVALID_OPTIONS` when the router's context has no client from `createMirrorAuth` as `auth`. A `dehydrate` and a `hydrate` of your own keep working: yours gets back what yours sent. Pass them to `createRouter`. One set later, such as with `router.update`, replaces the session's. See [`loadSession`](#loadsession) to read the session before the guards run. ### loadSession Reads this request's session into the client. Call it in the root route's `beforeLoad`. On the server, it calls the client's `revalidate`, so guards and the page see the session from the cookie. In the browser, it does nothing when [`connectSession`](#connectsession) already brought the server's session. Otherwise, such as for a root route that didn't render on the server, it asks the server on each navigation until a read succeeds. Rejects as the client's `retry()` does when the read fails. # TanStack Start server (https://session-kit.pages.dev/docs/reference/tanstack-start-server) Import these from `@monarcode/session-kit/tanstack-start/server`. To set it up, see [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start). ## Functions ### refreshSession Refreshes the session before each request, while the response can still set the cookie. Pass it to Start's `createMiddleware().server()`, and list that middleware in `requestMiddleware` in `src/start.ts`. It refreshes access that expires within `within` seconds, so pages and server functions don't refresh while rendering, once a cookie can't be set. A failed refresh doesn't fail the request. Routes read the session as usual, and an error there reaches the route's error component. It sets `Cache-Control` to `private, no-store` on each response that doesn't set its own, unless you pass `cacheControl`. Start bundles `src/start.ts` for the browser too, and strips only what's inside `.server()` from it. Calling `refreshSession` there keeps `serverAuth` out of the browser bundle. Throws `INVALID_OPTIONS` when `within` is negative. ### sessionRoute Makes the handlers of your session route, a server route that answers `createMirrorAuth`'s `endpoint`: the browser client signs out and gets the access token through it. Pass them as the route's `server.handlers`. It answers this site's own pages only, as `sessionHandler` from `@monarcode/session-kit/server` explains, and serves the access token only when `createServerAuth` has `clientCredentials`. Start's `createCsrfMiddleware` filtered to server functions doesn't cover server routes, so this check does. `loadSession` reads the session while Start renders on the server, where the client can't call the route. Pass `createMirrorAuth` a `revalidate` server function too. Sign-in stays your own server function. ### startAuth The session of the request TanStack Start is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Each call finds the current request, so make it once, at module level, beside `serverAuth`. Use it in server functions, request middleware, server routes, and `beforeLoad` and loaders while they run on the server. As [`startJar`](#startjar) explains, Start can't set a cookie once a page streams, so refresh before rendering, in request middleware with [`refreshSession`](#refreshsession). Outside a request, such as in the browser, its methods reject with `INVALID_OPTIONS`, and `isCurrent` and `state` throw it. Import it only from server code, as you do `serverAuth`. ### startJar The `CookieJar` for the request TanStack Start is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`startAuth`](#startauth) passes it for you. Use it in a server function, request middleware, a server route, or `beforeLoad` and loaders while they run on the server. Every call during one request returns the same jar. Start adds its cookies to the response, a redirect's included, but not once it has started streaming a page. A cookie set after that is lost, so refresh before rendering, in request middleware with [`refreshSession`](#refreshsession). Throws `INVALID_OPTIONS` outside a request, such as in the browser. Import it only from server code, such as a server function's handler, so Start's compiler leaves it out of the browser bundle. ## Types ### StartSessionRoute The handlers [`sessionRoute`](#sessionroute) makes, for a server route's `GET` and `POST`. # Next.js (https://session-kit.pages.dev/docs/reference/next) Import these from `@monarcode/session-kit/next`. To set it up, see [Next.js](https://session-kit.pages.dev/docs/setups/next). ## Functions ### nextJar The `CookieJar` for `cookies()` from `next/headers`, to pass to `serverAuth` from `@monarcode/session-kit/server`. It's read-only unless you pass `writable: true`, which only a Server Function or a Route Handler may do, as Next throws when a Server Component sets a cookie. A read-only jar can't refresh, so refresh before rendering, in Proxy, with [`proxyJar`](#proxyjar). The read-only jar follows the writable jar for the same store, so a sign-in, sign-out or refresh through the writable one shows in it. The same store and `writable` always give the same jar. ### nextSession Gives a Next.js app its session ([`NextSession`](#nextsession)), over [`nextJar`](#nextjar) and [`proxyJar`](#proxyjar). Make it once, beside `serverAuth`, in a module only server code imports. Server Components read it with `get` and guard pages with `require`. Server Functions and Route Handlers sign in and out with `signIn` and `signOut`. `proxy.ts` refreshes with `refresh`, as rendering can't set cookies. Throws `INVALID_OPTIONS` without `cookies` or `redirect`, when `loginPath` doesn't start with `/`, or when `within` is negative. ### proxyJar The `CookieJar` for a request in Next's Proxy (`proxy.ts`). It reads `request`'s cookies and sets new ones on `response`. Use it with `serverAuth.refreshIfDue`, so the pages that render the request see a fresh token through [`nextJar`](#nextjar). Return `response` from Proxy, or the new cookies are lost. Pages on the Edge runtime may still read the old cookie. Every call with the same `response` returns the same jar. ### sessionRoute Makes the Route Handlers for your session route, which answers `createMirrorAuth`'s `endpoint`: the browser client reads the session, signs out and gets the access token through it. Pass `cookies` from `next/headers` ([`NextSessionRouteOptions`](#nextsessionrouteoptions)). It answers this site's own pages only, as `sessionHandler` from `@monarcode/session-kit/server` explains, and serves the access token only when `createServerAuth` has `clientCredentials`. Sign-in stays your own Server Function. Throws `INVALID_OPTIONS` without `cookies`. ## Types ### NextCookies A request's cookie store, as `cookies()` from `next/headers` resolves it. [`nextJar`](#nextjar) reads and writes it, and Next's own store fits. ### NextJarOptions Options for [`nextJar`](#nextjar). ### NextJarOptions Options for nextJar. | Prop | Type | Description | | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `writable?` | `union` | Whether the jar can set cookies. Pass `true` in a Server Function (an action) or a Route Handler. Server Components can't set cookies, so there the jar is read-only and never refreshes. Default: `false` | ### NextSession The session in a Next.js app, made by [`nextSession`](#nextsession): reads and guards for Server Components, the request's session for Server Functions and Route Handlers, and the refresh for Proxy. Members: - `get`: Resolves who is signed in, from the cookie, or `null`. It doesn't set cookies, so it works in Server Components. Proxy refreshes first. - `require`: Resolves the session, or redirects to the sign-in page with `?redirectTo=` set to `path`, the page's own path, as Server Components don't know their URL. Next adds a `basePath` to redirects from pages and Server Functions, but not from Route Handlers. With a `basePath`, a Route Handler should read the session with `get` and answer 401 instead. - `redirectIfSignedIn`: For your sign-in page: redirects a signed-in user to `redirectTo`, usually the `redirectTo` search param, made safe with `safeReturnTo`. It resolves for a signed-out user, or when the session can't be read. - `readOnly`: The request's session for Server Components, which doesn't set cookies. Read its `credentials` to call your API while rendering. - `writable`: The request's session for Server Functions and Route Handlers, which sets cookies. `signIn`, `signOut` and `updateUser` are shortcuts to it. Use it for the rest, such as renewing the access token. - `signIn`: Signs in with your backend's tokens, setting the cookie, as `RequestAuth`'s `signIn` does over `writable()`. Use it in Server Functions and Route Handlers. - `signOut`: Signs out and clears the cookie, as `RequestAuth`'s `signOut` does over `writable()`. Use it in Server Functions and Route Handlers. - `refresh`: For Proxy: refreshes access that expires within `within` seconds, setting the new cookie on `response`, and resolves `response`. A failed refresh is left for the page, which reads the session as it is. - `updateUser`: Replaces the signed-in user in the cookie, such as after a profile edit, as `RequestAuth`'s `updateUser` does over `writable()`. Use it in Server Functions and Route Handlers. ### NextSessionOptions Options for [`nextSession`](#nextsession). Pass Next's own `cookies` and `redirect`, as this entry point doesn't import `next`. ### NextSessionOptions Options for nextSession. Pass Next's own `cookies` and `redirect`, as this entry point doesn't import `next`. | Prop | Type | Description | | ------------ | ---------- | --------------------------------------------------------------------------------------------------------------------------------- | | `cookies` | `function` | `cookies` from `next/headers`. | | `redirect` | `function` | `redirect` from `next/navigation`. | | `loginPath?` | `string` | Your sign-in page's path, starting with `/`. Default: `"/login"` | | `within?` | `number` | How soon before the access token expires `refresh` refreshes it, in seconds, as `serverAuth.refreshIfDue` explains. Default: `60` | ### NextSessionRoute The Route Handlers [`sessionRoute`](#sessionroute) makes, for `GET` and `POST`. ### NextSessionRouteOptions Options for [`sessionRoute`](#sessionroute). Pass Next's own `cookies`, as this entry point doesn't import `next`. ### NextSessionRouteOptions Options for sessionRoute. Pass Next's own `cookies`, as this entry point doesn't import `next`. | Prop | Type | Description | | --------- | ---------- | ------------------------------ | | `cookies` | `function` | `cookies` from `next/headers`. | ### ProxyRequest The request [`proxyJar`](#proxyjar) reads cookies from. A `NextRequest` fits. ### ProxyResponse The response [`proxyJar`](#proxyjar) sets cookies on. A `NextResponse` fits. # Expo (https://session-kit.pages.dev/docs/reference/expo) Import these from `@monarcode/session-kit/expo`. To set it up, see [Expo Router](https://session-kit.pages.dev/docs/setups/expo). ## Functions ### deepLinkHandler Makes `redirectSystemPath` for `app/+native-intent.tsx`. It keeps each incoming link with [`rememberDeepLink`](#rememberdeeplink), so `SessionGate` opens it after sign-in, and returns the path unchanged. Use `rememberDeepLink` itself when your `redirectSystemPath` does more, such as rewriting old links. Throws `INVALID_OPTIONS` for a `loginPath` that doesn't start with `/`. It throws when it's made, so a link never meets the error. See [`RememberDeepLinkOptions`](#rememberdeeplinkoptions) to set your sign-in screen's path. ### rememberDeepLink Keeps an incoming deep link, so `SessionGate` can open it after the user signs in. Without it, `Stack.Protected` sends a signed-out user from a guarded screen to one they may see, and the link is lost. Call it from `redirectSystemPath` in `app/+native-intent.tsx`, which Expo Router calls with every URL that opens the app. `url` can be a full URL or a path. Return the path unchanged, so a signed-in user still lands on it. The path is checked with `safeReturnTo`, so the sign-in path, the root, and anything that could leave the app are ignored. A newer link replaces an older one. The link is kept in memory only, so an app restart forgets it. What `SessionGate` does with it: - **Signed in already**: drops it, since Expo Router opens it as usual. - **Signed out or locked**: opens it with `router.replace` after the next sign-in or unlock, once `SessionGate`'s `ready` is `true`. - **A screen anyone may see**: drops it once that screen is showing. Throws `INVALID_OPTIONS` for a `loginPath` that doesn't start with `/`. Expo Router warns that a throw in `redirectSystemPath` can crash the app. [`deepLinkHandler`](#deeplinkhandler) throws when it's made instead. ### secureStorage Saves the session with `expo-secure-store`: in the iOS keychain, and encrypted with an Android Keystore key on Android. Pass it as `createAuth`'s `storage` in Expo apps. - Values over 2048 bytes, which some iOS releases refuse to store, are split across keys. A write cut short, for example when the app is killed, keeps the previous value whole. A value over 128 KB fails to save, with `PERSISTENCE_FAILED`. - Reads are synchronous, so with a synchronous user schema the session is restored before the first render. Writes and removals are asynchronous. - On iOS, a session left in the keychain by an earlier install is removed unless `clearOnReinstall` is `false`. A marker file in the app's documents directory, which deleting the app removes, tells installs apart. - Data that can't be decrypted, as after Android restores a backup onto another device, reads as signed out and is removed. Other read failures, such as a locked iOS keychain, make the session `unavailable`. Unlike `webStorage`, it has no `subscribe` or `lock`, because an app has no other tabs to follow or to share refreshes with. See [`SecureStorageOptions`](#securestorageoptions) for iOS keychain access and reinstalls. ## Components ### SessionGate Wraps the root navigator in `app/_layout.tsx`. It adds what Expo Router's `Stack.Protected` lacks: a splash screen held while the session is restored, a screen for when access is unavailable, and deep links kept for after sign-in. Render it inside `AuthProvider`, or pass a `client`, which it mounts. Without either, it throws `INVALID_OPTIONS`. - **While the session is restored**, and until `ready`, it renders nothing, so the splash screen stays up, and hides the splash screen once both are done. The navigator mounts only then, so a cold-start deep link isn't sent to the sign-in screen first. Call `SplashScreen.preventAutoHideAsync()` at the top of the root layout. - **While access is unavailable** it renders `unavailable({ error, retry })` instead of the navigator. Without `unavailable`, it hides the splash screen and throws the error to the root layout's `ErrorBoundary`. - **While locked** it renders the navigator, so its guards can show an unlock screen. Neither unlocking nor a password sign-in from the lock screen remounts the navigator. - **When the app returns to the foreground** it re-checks the session, because timers don't run while iOS suspends the app. An access token that expired meanwhile is refreshed. A refresh that already failed stays failed until `retry()`. - **After a sign-in or unlock** it opens the deep link `rememberDeepLink` kept, with `router.replace`, once `ready`. - **When one account replaces another** without a sign-out between them, it remounts the navigator, so no screen keeps the previous account's component state. The screens that were open stay open. A sign-out already removes the guarded screens. ## Types ### DeepLinkHandler The `redirectSystemPath` that [`deepLinkHandler`](#deeplinkhandler) makes, for `app/+native-intent.tsx`. ### RememberDeepLinkOptions Options for [`rememberDeepLink`](#rememberdeeplink) and [`deepLinkHandler`](#deeplinkhandler), the same as `safeReturnTo`'s. Set `loginPath` when your sign-in screen isn't `/login`, so links to it are dropped rather than kept. ### RememberDeepLinkOptions Options for rememberDeepLink and deepLinkHandler, the same as `safeReturnTo`'s. Set `loginPath` when your sign-in screen isn't `/login`, so links to it are dropped rather than kept. | Prop | Type | Description | | ------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `loginPath?` | `union` | Your sign-in page's path, or several. A path to it is replaced with `"/"`, so signing in never sends the user back to sign in. Matched by path, ignoring case, percent-encoding, trailing slashes and any query. Default: `"/login"` | ### SecureStorageOptions Options for [`secureStorage`](#securestorage). Both are for iOS: when the keychain may be read, and what happens to a session an earlier install left there. ### SecureStorageOptions Options for secureStorage. Both are for iOS: when the keychain may be read, and what happens to a session an earlier install left there. | Prop | Type | Description | | --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `keychainAccessible?` | `number` | When iOS lets the app read the session: one of SecureStore's constants, such as `AFTER_FIRST_UNLOCK`. An app that refreshes in a background task while the device is locked needs `AFTER_FIRST_UNLOCK`. Passed to SecureStore unchanged. If the keychain can't be read when the app starts, the session is `unavailable`, not signed out. A refresh that runs while it's locked can't save the new tokens, and that signs the user out. Default: `WHEN_UNLOCKED` | | `clearOnReinstall?` | `union` | Whether a reinstalled app starts signed out. iOS keeps keychain items after the app is deleted, so a session an earlier install left is removed before it's read. `false` restores it instead. Default: `true` | ### SessionGateProps Props for [`SessionGate`](#sessiongate): the root navigator, what to show while access is unavailable, and what else the splash screen waits for. ### SessionGateProps Props for SessionGate: the root navigator, what to show while access is unavailable, and what else the splash screen waits for. | Prop | Type | Description | | -------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `children?` | `ReactNode` | The root navigator, usually a `Stack` guarded with `Stack.Protected`. | | `unavailable?` | `function` | Shown instead of the navigator while access is unavailable, such as after a failed refresh. Without it, the error is thrown to the root layout's `ErrorBoundary`. That boundary's `retry` only renders again, and a failed refresh stays failed until `auth.retry()`, so call both. | | `client?` | `RetryableSource` | The client to watch. Default: the nearest `AuthProvider`'s. | | `ready?` | `union` | Whether the rest of the app is ready for its first screen, such as fonts or remote config. Until it's `true`, and while the session is restored, the gate renders nothing and keeps the splash screen up. It only holds the splash screen the first time, even if the gate remounts. Setting it `false` later changes nothing on screen, but the deep link opened after a sign-in still waits for it. Default: `true` | ### UnavailableProps What the `unavailable` render prop of an adapter component, such as React Router's `SessionOutlet` or Expo's `SessionGate`, receives. ### UnavailableProps What the `unavailable` render prop of an adapter component, such as React Router's `SessionOutlet` or Expo's `SessionGate`, receives. | Prop | Type | Description | | ------- | ---------- | ------------------------------------------------------------------------------- | | `error` | `union` | Why access is unavailable, such as a failed refresh or a locked keychain. | | `retry` | `function` | Tries again, as `auth.retry()` does. A repeated failure stays in `state.error`. | # Effect (https://session-kit.pages.dev/docs/reference/effect) Import these from `@monarcode/session-kit/effect`. To set it up, see [Effect and effetch](https://session-kit.pages.dev/docs/effect). ## Classes ### Auth Your auth client as an Effect service. Its Effects read the session, get an access token for API calls, sign in and out, update the user, and stream state changes. Provide it with `Auth.layer`. Register your client's type in the main entry point's `Register`, so the Effects carry your user. Each Effect fails with an [`AuthFailure`](#authfailure) whose `code` is the client's `AuthErrorCode`. An Effect dies on misuse (`INVALID_OPTIONS`). The layer doesn't mount the client. `AuthProvider`, `SessionGate` or the router adapters do, or call `auth.mount()` yourself. `lock()` and `unlock()` stay on the client. Wrap their errors with `Auth.fromAuthError`. ### AuthFailure How `Auth`'s Effects fail: a tagged error that carries the client's `AuthError`. Handle it with `Effect.catchTag("AuthFailure", …)` and match on `code`. The original error is the `cause`. ## Types ### AuthFailureCode The codes an [`AuthFailure`](#authfailure) carries: every `AuthErrorCode` except `INVALID_OPTIONS`, which is misuse and so a defect. ### AuthLayerClient What `Auth.layer` takes. Once you register a client in `Register`, that's your client, or on the server a request's session with the same user (`RequestAuth`). Until then, it's any [`AuthServiceClient`](#authserviceclient). ### AuthServiceClient What `Auth` needs from a client. Any `createAuth` or `createMirrorAuth` client fits, and so does a fake with these members in tests. `signIn` is optional, because a mirror made without it has none. ### RegisteredSession The session `Auth.session` gives you: your registered client's `Session`, never `null`. ### RegisteredSignIn What `Auth.signIn` takes: your registered client's `signIn` input. It's `never` for a client without `signIn`. ### RegisteredState Your registered client's `AuthState`, as `Auth.changes` emits it. ### RegisteredUserInput What `Auth.updateUser` takes: your registered client's user input. It's `never` for a client without `updateUser`, such as one whose user comes from the access token. # effetch (https://session-kit.pages.dev/docs/reference/effetch) Import these from `@monarcode/session-kit/effetch`. To set it up, see [Effect and effetch](https://session-kit.pages.dev/docs/effect). ## Functions ### sessionBearer An effetch plugin that sends the current access token as `Authorization: Bearer`. After a 401, it gets a new access token once. `GET` and `HEAD` requests are then sent again. Other requests keep their 401, which effetch fails the call with as an `HttpError`, for you to retry. If the request sent again gets a 401 too, the user is signed out, unless `signOutOnRepeated401` is off. If the renewal ends the session, the call fails with the 401 too. Calls fail with `AuthFailure`, before sending anything: `UNAUTHENTICATED` when signed out, unless `optional` sends them without a token, and `LOCKED` while locked. When a refresh fails, the call fails with that failure, such as `REFRESH_FAILED`. If the session changes during a call, it fails with `SESSION_CHANGED` rather than return a response meant for another account. Streams, such as `api.sse` and stream endpoints, work the same way up to the response's headers. A stream that's open when the user signs out or switches accounts keeps reading until it ends. Stop it yourself if it mustn't outlive the session. The token never leaves your API. A request on another origin, or with a username or password in its URL, dies with `INVALID_OPTIONS`. With Effect's `FetchHttpClient`, a redirect fails as a `Fetch.NetworkError` rather than being followed, except on React Native before Expo SDK 58, whose `fetch` follows redirects whatever it's told. An invalid `baseUrl` throws `INVALID_OPTIONS`. A request that already has an `Authorization` header is sent as it is, as effetch's `bearer` does. Put it last in `plugins`, after `retry`, so each attempt reads the current token. The client then needs the `Auth` service, but calls don't. On the server, make the effetch client per request, and provide it the `Auth` layer for that request's session (`RequestAuth`). It reads the token from the request's cookie and saves a renewed one. See [`SessionBearerOptions`](#sessionbeareroptions) for `optional` and `signOutOnRepeated401`. ## Types ### SessionBearerOptions Options for [`sessionBearer`](#sessionbearer). ### SessionBearerOptions Options for sessionBearer. | Prop | Type | Description | | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `baseUrl` | `string` | Your API's URL, usually the effetch client's `baseUrl`. It must be absolute, such as `https://api.example.com`. The access token goes only to requests on its origin. | | `optional?` | `union` | Whether a call made while signed out is sent without an `Authorization` header, rather than failing with `UNAUTHENTICATED`. Set `true` when one client serves public and private endpoints. A locked client still fails with `LOCKED`. Calls can override it. Default: `false` | | `signOutOnRepeated401?` | `union` | Whether a second 401, after a successful refresh, signs the user out. Set `false` when some endpoints answer 401 for reasons other than a rejected token. Calls can override it. Default: `true` | ### SessionBearerPlugin The plugin [`sessionBearer`](#sessionbearer) returns. Its calls can fail with `AuthFailure`, and a client made with it needs the `Auth` service. A call can skip it with `plugins: { sessionBearer: false }`, or override `optional` and `signOutOnRepeated401`. # Error codes (https://session-kit.pages.dev/docs/reference/error-codes) Every error from Session kit's own logic is an `AuthError`. Match on its `code`, because the `message` is for people and can change. For example, to check for a locked session: ```ts title="src/error-codes.ts" import { AuthError } from "@monarcode/session-kit"; export function isLocked(error: unknown): boolean { return error instanceof AuthError && error.code === "LOCKED"; } ``` How errors reach your app, and how to show them: [Errors](https://session-kit.pages.dev/docs/configuration/errors). ## USER_VALIDATION_FAILED The user couldn't be accepted. `issues` holds the schema's issues when it rejected the user, and `cause` holds the error when something else failed, such as an `updateUser` function. Otherwise `message` says why, such as a user that isn't a plain JSON object. It also covers a schema that doesn't return its own output unchanged (saved users are checked again when restored), an access token that `fromAccessToken` can't read, and a user your refresh callback returned that the schema rejects. ## INVALID_SESSION Tokens or a saved session that can't be used, such as an access token that already expired at sign-in, or a saved session that's malformed. Tokens from your refresh callback fail with it too when they last under five seconds, have already expired, or repeat the access token your API rejected. In the browser of a server-rendered app, your server answered with something other than a session or an access token. ## PERSISTENCE_FAILED Storage couldn't be read, written or cleared, or `locking.seal` failed. That includes a session too large to save: over two cookies on the server, or more than `secureStorage` holds. In the browser of a server-rendered app, signing out on the server failed. ## REFRESH_FAILED The refresh failed: your refresh callback threw or timed out, or `refresh()` was called without a `refresh` option or a refresh token. Without them, an access token that expires or that your API rejects signs the user out instead, with no error. In the browser of a server-rendered app, reading the session or the access token from the server failed. On the server, the access token needed a refresh in a request that can't set cookies. ## REVOKE_FAILED Your `revoke` callback failed. It shows in `state.error`, and `signOut()` still resolves. ## SESSION_CHANGED The session changed while the call ran: a newer sign-in, a sign-out, a newer `updateUser` call, or another tab replaced it. A route guard rejects with it when the session kept changing while it was read. ## UNAUTHENTICATED The call needs someone signed in, and no one is. ## LOCKED The session is locked. Call `unlock()` first. ## UNLOCK_FAILED `locking.open` failed, so the session stays locked. ## INVALID_OPTIONS An option or argument Session kit can't use, or a method called without the option it needs or where it can't work, such as a server `signIn` in a request that can't set cookies. In the browser of a server-rendered app, your session route refused the request, such as one from a page an older version of your app served. # Compatibility (https://session-kit.pages.dev/docs/reference/compatibility) Before you upgrade React, a router or a framework, check here that Session kit supports the new version. This page also lists the runtimes Session kit is built for, and which of them CI tests. ## Peer dependencies Every peer dependency is optional. Install only the ones used by the entry points you import: | Peer | Range | Used by | | ------------------------ | ----------------------- | ------------------------------------------------------------------------- | | `react` | `^18.0.0 \|\| ^19.0.0` | `/react`, `/tanstack-router`, `/tanstack-start`, `/react-router`, `/expo` | | `@tanstack/react-router` | `^1.132.0` | `/tanstack-router` | | `@tanstack/react-start` | `^1.169.0` | `/tanstack-start/server` | | `react-router` | `^7.0.0 \|\| ^8.0.0` | `/react-router`, `/react-router/server` | | `next` | `^16.0.0` | `/next` | | `effect` | `^4.1.0` | `/effect`, `/effetch` | | `@monarcode/effetch` | `^0.1.0-rc.4` | `/effetch` | | `expo-router` | `^5.0.2` through `^58` | `/expo` | | `expo-secure-store` | `^14.2.0` through `^58` | `/expo` | | `expo-file-system` | `^18.1.0` through `^58` | `/expo` | | `react-native` | `>=0.79.0` | `/expo` | Things to know about these peers: - **Expo.** The Expo ranges cover Expo SDK 53 to 58. Install them with `npx expo install`, so that they match your SDK, as the [Expo guide](https://session-kit.pages.dev/docs/setups/expo#installation) shows. - **React Router 8** needs React 19.2.7 or newer. With React 18, use React Router 7. - **Next.js 16** needs React 18.2 or newer. - **React Router with server rendering.** `/react-router/server` needs React Router's middleware: React Router 8, or 7.9 and later with `future.v8_middleware`. - **effetch-query**, for caching Effect queries, needs React 19. - **React DOM.** No entry point imports React DOM. ## Runtimes Session kit is built for these runtimes: - browsers; - React Native through Expo SDK 53 to 58, with Hermes and Metro; - Node.js 20 and newer, for server rendering and for the server entry points. Your framework can need a newer Node.js than Session kit does. React Router 8.5 needs Node.js 22.22, TanStack Start 1.169 needs 22.12, and Next.js 16.4 needs 20.9. Session kit uses these platform features: - **`AbortController`** is required. React Native's, which can't carry an abort reason, works too. - **`atob`** decodes JWTs, to read an access token's expiry and for `fromAccessToken`. Every runtime above has it. - **`fetch`, `Request` and `Response`** are required by `@monarcode/session-kit/http` and by the server entry points. - **`crypto.randomUUID`** makes session IDs when present. Without it, the client uses `crypto.getRandomValues`, or `Math.random` as a last resort. - **Web Locks** keep tabs to one refresh at a time when present. Without them, two tabs can refresh at the same instant, as [Tabs](https://session-kit.pages.dev/docs/configuration/tabs) explains. - **`BroadcastChannel`** lets a `createMirrorAuth` client follow sign-ins and sign-outs in other tabs, when present. - **Web Crypto** is required on the server by `@monarcode/session-kit/server`, as in Node.js 20 and newer. ## What CI tests CI runs every test on Node.js 24, twice: - with the peer versions in the repository's lockfile, which can be behind the newest releases; - with the oldest version in each peer range, such as React 18.0 and React Router 7.0, and Expo SDK 53's packages. `expo-file-system` stays at the lockfile's version, because 18.1 publishes no `exports` map, so its types don't resolve under NodeNext. CI also builds each example app, and bundles the Expo app for iOS and Android. It doesn't run Node.js 20 or 22, browsers or a device. Those are built for, but not tested in CI. ## TypeScript Session kit's types need TypeScript 5.4 or newer. `/effect` and `/effetch` also load Effect's types, and Effect asks for TypeScript 5.9 or newer. The package is ESM-only. CI checks its types with TypeScript 6.0.3 under NodeNext and Bundler resolution, with `exactOptionalPropertyTypes` both on and off.