Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
9121f17
feat(http)!: authFetch accepts a URL or a Request; createAuthFetch ta…
monarcode Nov 13, 2026
327ab06
feat!: unwrap mirror sign-in errors, take options in useMirrorAuth, add
monarcode Nov 13, 2026
1dd9ba8
feat!: hooks without a hooks file, typed by one Register in the main …
monarcode Nov 13, 2026
6bc042a
feat(server)!: one request-scoped session object, with startAuth, rou…
monarcode Nov 13, 2026
4f9ec53
feat(server): middleware and server guards for Start, React Router an…
monarcode Nov 14, 2026
b5b7c7c
feat(server): add a session route that the mirror client calls
monarcode Nov 14, 2026
eab4c81
feat(server): session route for the browser client, with sessionHandler,
monarcode Nov 14, 2026
80efcc1
feat: add isSignedIn, loader guards and a deep link handler
monarcode Nov 14, 2026
1ba6763
refactor(react-router): split the loader guards into their own functions
monarcode Nov 14, 2026
ac10d38
docs: revise the guides and examples to match the current API
monarcode Nov 14, 2026
e8750f9
docs: add a Hybrid server-rendering page and fill gaps in hovers
monarcode Nov 14, 2026
fa6e332
docs(react-router): explain when to use requireSessionLoader or requi…
monarcode Nov 14, 2026
6bbabc7
refactor(examples): lay out the effetch example as the Effect guide does
monarcode Nov 14, 2026
2647665
docs: check the hovers and guides against the code
monarcode Nov 14, 2026
7bc2b44
fix!: fix sign-out, guard and session-route edge cases
monarcode Nov 14, 2026
bc2601a
feat(next): add signIn, signOut and updateUser to NextSession
monarcode Nov 14, 2026
b28e583
feat(site): rewrite the landing page's pitch and features
monarcode Nov 14, 2026
1109790
feat(site): retitle the landing page's tour around the typed user
monarcode Nov 14, 2026
d0cca80
chore(release): 0.1.0-rc.0
monarcode Nov 14, 2026
49a0593
test: check React Router middleware types and the Start guides only o…
monarcode Nov 14, 2026
3927348
feat(site): order llms.txt by the sidebar with full URLs, and link it…
monarcode Nov 14, 2026
e87c12c
docs: link Other HTTP clients from the Call your API sections
monarcode Nov 14, 2026
ececead
docs: align the package description with the new pitch
monarcode Nov 14, 2026
6b1ceae
feat(site): send a packet across the How it works arrows
monarcode Nov 14, 2026
36505db
docs(readme): replace the quick start's excerpts with a small compile…
monarcode Nov 15, 2026
56bb128
docs(readme): show the tree-shaken bundle size and a types badge
monarcode Nov 15, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Release alpha
name: Release

env:
HUSKY: 0
Expand All @@ -7,7 +7,7 @@ on:
workflow_dispatch:
inputs:
version:
description: Alpha version already committed in package.json (without v)
description: Alpha or release candidate version already committed in package.json (without v)
required: true
type: string

Expand Down Expand Up @@ -84,7 +84,7 @@ jobs:
- name: Check npm supports trusted publishing
run: |
node --input-type=module -e 'import { execFileSync } from "node:child_process"; const [major, minor, patch] = execFileSync("npm", ["--version"], { encoding: "utf8" }).trim().split(".").map(Number); if (!(major > 11 || (major === 11 && (minor > 5 || (minor === 5 && patch >= 1))))) throw new Error("npm >=11.5.1 is required");'
- name: Publish alpha to npm
- name: Publish to npm
env:
RELEASE_VERSION: ${{ inputs.version }}
run: npm publish "$RUNNER_TEMP/release/monarcode-session-kit-$RELEASE_VERSION.tgz" --tag latest --access public --ignore-scripts
Expand Down
13 changes: 9 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ Consumers import from the root and from subpaths:
(`INVALID_OPTIONS`). Wrap a failure at the operation's boundary with
`toAuthError(code, message, cause)`, where the operation knows its code;
a `cause` is whatever failed, and doesn't need to be an `AuthError`.
`fetch`'s and `Request`'s own failures pass through `authFetch`.
`fetch`'s and `Request`'s own failures pass through `authFetch`, and the
app's own sign-in errors pass through a `createMirrorAuth` client's
`signIn`.
- Source imports use explicit `.js` extensions. Because
`exactOptionalPropertyTypes` is on, write optional props as
`foo?: T | undefined`. `readonly` is a separate, per-type choice: outputs
Expand Down Expand Up @@ -168,9 +170,12 @@ developers, not for us. Every comment ships: keep it short, plain and true.
`scripts/docs-pages.mjs`, which the site also reads for type hovers, and
a page that builds on Getting started lists the files it uses as `shared`.
A new page with titled examples fails the check until it's listed.
- A README example marked `<!-- from: site/content/docs/(latest)/page.mdx -->`
is an excerpt of that page's examples, and the check fails when the two
differ: edit the page, then copy.
- The README's quick start is its own small app: each block marked
`<!-- file: src/auth.ts -->` is a file, compiled together like a page's
(`README.md` in `documents`). A README example marked
`<!-- from: site/content/docs/(latest)/page.mdx -->` is an excerpt of that
page's examples instead, and the check fails when the two differ: edit the
page, then copy.
- The reference pages in `site/content/docs/(latest)/reference/` (one per
entry point, and the error codes) are generated from the JSDoc by
`pnpm run docs:reference`, except the entry points index and
Expand Down
361 changes: 356 additions & 5 deletions CHANGELOG.md

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ example:
- **The reference.** The API reference pages are generated from the JSDoc
by `pnpm run docs:reference`, and the check fails when they're out of
date. Run it after changing a public export or its JSDoc.
- **The README.** A block marked with a `from:` comment is an excerpt of a
page's examples, and must match it.
- **The README.** Its quick start is a small app of its own: each block
marked `<!-- file: path -->` is a file, and they compile together. A block
marked with a `from:` comment is an excerpt of a page's examples instead,
and must match it.

`pnpm test` runs the runtime tests twice: with synchronous storage, and with
storage that settles every operation late, removals last, to catch ordering
Expand Down
215 changes: 122 additions & 93 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
![session-kit](https://raw.githubusercontent.com/monarcode/session-kit/main/assets/sk-banner.png)
![Session kit: schema-driven, type-safe sessions for React apps](https://raw.githubusercontent.com/monarcode/session-kit/main/assets/sk-banner.png)

[![npm](https://img.shields.io/npm/v/@monarcode/session-kit)](https://www.npmjs.com/package/@monarcode/session-kit)
[![CI](https://github.com/monarcode/session-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/monarcode/session-kit/actions/workflows/ci.yml)
[![bundle size](https://deno.bundlejs.com/badge?q=@monarcode/session-kit)](https://bundlejs.com/?q=@monarcode/session-kit)
[![tree-shakeable](https://img.shields.io/badge/tree--shakeable-yes-brightgreen)](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D)
[![bundle size](https://deno.bundlejs.com/badge?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D)](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D)
[![types](https://img.shields.io/npm/types/@monarcode/session-kit)](https://www.npmjs.com/package/@monarcode/session-kit)
[![provenance](https://img.shields.io/badge/provenance-verified-brightgreen?logo=npm)](https://www.npmjs.com/package/@monarcode/session-kit#provenance)
[![license](https://img.shields.io/npm/l/@monarcode/session-kit)](./LICENSE)

Expand All @@ -15,142 +15,171 @@
[![Expo](https://img.shields.io/badge/Expo-20232a?logo=expo&logoColor=white)](https://session-kit.pages.dev/docs/setups/expo)
[![Effect](https://img.shields.io/badge/Effect-20232a?logo=effect&logoColor=white)](https://session-kit.pages.dev/docs/effect)

**Your backend signs users in. Session kit handles everything after.**
**Every sign-in ends in a session. Make yours type-safe and predictable.**

Session kit is the session layer for React apps that have their own backend.
Hand it the tokens your sign-in endpoint returns, and it saves the session,
Give it the tokens your sign-in endpoint returns, and it saves the session,
restores it on reload, refreshes tokens before they expire, keeps every tab in
step, and guards your routes.
sync, and guards your routes. It never signs users in: your backend does, and
Session kit takes over from its response.

It works with TanStack Router, React Router, and Expo Router, renders on the
server with TanStack Start, Next.js, and React Router, and comes with an
[Effect](https://effect.website) service and an
[effetch](https://github.com/monarcode/effetch) plugin.

> **Alpha.** Early development: the API may change between releases, and it
> isn't ready for production. See the [release notes](./CHANGELOG.md).
> **Release candidate.** The API is frozen for 0.1, and later 0.1 releases
> only add to it. See the [release notes](./CHANGELOG.md).

**Documentation: [session-kit.pages.dev](https://session-kit.pages.dev)**

## Installation

```sh
pnpm add @monarcode/session-kit
npm install @monarcode/session-kit zod
```

Alpha releases are published to the `latest` distribution tag and may change
the public API, so pin an exact version and read the
[release notes](./CHANGELOG.md) before upgrading.

Any [Standard Schema](https://standardschema.dev) library describes users.
The examples use Zod:

```sh
pnpm add zod
```
The examples use Zod. Peer dependencies such as React and your router are
optional: install the ones your setup uses.
[Compatibility](https://session-kit.pages.dev/docs/reference/compatibility)
lists the supported versions.

Every peer dependency is optional: install React and the router your setup
uses. [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) lists the
supported versions.
Release candidates are published to the `latest` tag, so pin an exact version
and read the [release notes](./CHANGELOG.md) before upgrading.

## Quick start

Session kit never calls your backend. Write the requests you'd write anyway:
one that signs in, and one that exchanges a refresh token for new tokens.
Your backend keeps its sign-in and refresh endpoints. Session kit takes the
tokens they return and manages the session from there. A React app needs
three files.

**1. Create the client.** It checks every user against your schema, saves the
session, and calls your `refresh` before the access token expires:

<!-- from: site/content/docs/(latest)/getting-started.mdx -->
<!-- file: src/auth.ts -->

```ts
/** 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) };
}
import { createAuth, webStorage } from "@monarcode/session-kit";
import { z } from "zod";

/**
* 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());
export const auth = createAuth({
// Keeps this app's saved session apart from others on the same origin.
name: "my-app",
// Every user is checked against this schema, and typed by it.
user: z.object({ id: z.string(), name: z.string() }),
// Saves the session in localStorage, so it survives reloads.
storage: webStorage(),
refresh: async ({ refreshToken, signal }) => {
const response = await fetch("/api/auth/refresh", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
signal,
});
if (response.status === 401) return null; // rejected: sign out
if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
return response.json();
},
});

// Types the React hooks with this client's user.
declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
```

Then create the client. It saves the session, restores it on reload, and
refreshes the tokens with your `refresh`:
**2. Sign in.** Pass `signIn` what your backend's sign-in returned, the tokens
and the user:

<!-- from: site/content/docs/(latest)/getting-started.mdx -->
<!-- file: src/sign-in.ts -->

```ts
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),
});
import { auth } from "./auth.js";

export async function signIn(email: string, password: string) {
const response = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (!response.ok) throw new Error(`Sign-in failed (${response.status})`);
// { accessToken, refreshToken, expiresIn, user }
const tokens = await response.json();
await auth.signIn(tokens);
}
```

And render by the session's status:
**3. Render by the session's status.** `useAuth` re-renders when it changes,
in this tab or another:

<!-- from: site/content/docs/(latest)/getting-started.mdx -->
<!-- file: src/app.tsx -->

```tsx
function Screen() {
const { status, user } = useAuth();
import {
AuthProvider,
useAuth,
useAuthClient,
} from "@monarcode/session-kit/react";

import { auth } from "./auth.js";
import { SignInForm } from "./sign-in-form.js"; // your form, calling signIn

export function App() {
return (
<AuthProvider client={auth}>
<Home />
</AuthProvider>
);
}

function Home() {
const session = useAuth();
const client = useAuthClient();

switch (status) {
case "initializing":
return <p>Restoring your session…</p>;
case "unauthenticated":
return <SignIn />;
case "unavailable":
// Access couldn't be restored or refreshed: offer another try.
return (
<button onClick={() => void client.retry().catch(() => {})}>
Try again
</button>
);
default:
// Signed in: "authenticated", or "refreshing" with the user on screen.
return (
<main>
<h1>Welcome, {user.firstName}</h1>
<button onClick={() => void client.signOut().catch(() => {})}>
Sign out
</button>
</main>
);
if (session.status === "initializing") return <p>Restoring your session…</p>;
if (session.status === "unauthenticated") return <SignInForm />;
if (session.status === "unavailable") {
// The session couldn't be restored or refreshed, say while offline.
return (
<button onClick={() => client.retry().catch(console.error)}>
Try again
</button>
);
}
return (
<main>
<h1>Welcome, {session.user.name}</h1>
<button onClick={() => client.signOut().catch(console.error)}>
Sign out
</button>
</main>
);
}
```

[Getting started](https://session-kit.pages.dev/docs/getting-started) builds this into a working app
one step at a time, against a real test backend.
To call your API, `createAuthFetch` from `@monarcode/session-kit/http` adds
the access token to each request and refreshes it after a 401.
[Getting started](https://session-kit.pages.dev/docs/getting-started) builds
this app step by step against a real test backend, and the guides below add
your router's guards or server rendering.

## Pick your setup

| Setup | Guide |
| ----------------------------------------------- | ----------------------------------------------------------------------------------- |
| React without a router | [Getting started](https://session-kit.pages.dev/docs/getting-started) |
| TanStack Router, and TanStack Start in SPA mode | [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router) |
| TanStack Start with server rendering | [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start) |
| React Router: declarative, data, framework SPA | [React Router](https://session-kit.pages.dev/docs/setups/react-router) |
| React Router, framework mode with SSR | [React Router with SSR](https://session-kit.pages.dev/docs/setups/react-router-ssr) |
| Next.js 16, App Router | [Next.js](https://session-kit.pages.dev/docs/setups/next) |
| Expo Router on iOS and Android, SDK 53+ | [Expo Router](https://session-kit.pages.dev/docs/setups/expo) |
| Effect and effetch, with any of the above | [Effect and effetch](https://session-kit.pages.dev/docs/effect) |
Each setup has a guide:

| Setup | Guide |
| -------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| React without a router | [Getting started](https://session-kit.pages.dev/docs/getting-started) |
| TanStack Router, and TanStack Start as a single-page app (SPA) | [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router) |
| TanStack Start with server rendering | [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start) |
| React Router: declarative, data, framework SPA | [React Router](https://session-kit.pages.dev/docs/setups/react-router) |
| React Router, framework mode with server rendering | [React Router with SSR](https://session-kit.pages.dev/docs/setups/react-router-ssr) |
| Next.js 16, App Router | [Next.js](https://session-kit.pages.dev/docs/setups/next) |
| Expo Router on iOS and Android, SDK 53+ | [Expo Router](https://session-kit.pages.dev/docs/setups/expo) |
| Effect and effetch, with any setup | [Effect and effetch](https://session-kit.pages.dev/docs/effect) |

All but the first have a runnable app in [`examples/`](./examples).

Expand Down
19 changes: 11 additions & 8 deletions RELEASING.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Releasing session-kit

The `Release alpha` workflow is manually triggered. It releases an alpha version
already committed to `main`; it does not change versions or commit files.
The `Release` workflow is manually triggered. It releases an alpha or release
candidate version already committed to `main`; it does not change versions or
commit files.
It checks and packs with pnpm, publishes the verified tarball to npm using `latest`,
then creates a Git tag and GitHub prerelease at the workflow's commit.

Expand All @@ -25,19 +26,21 @@ See [npm's trusted publishing documentation](https://docs.npmjs.com/trusted-publ
The workflow runs on GitHub-hosted runners with Node.js 24 and npm >=11.5.1.
For this public repository/package, trusted publishing also generates provenance.

## Release an alpha
## Release an alpha or release candidate

1. Make the intended package changes. Set `package.json` to a new alpha version,
such as `0.1.0-alpha.1`, and add its `## 0.1.0-alpha.1` section to `CHANGELOG.md`.
1. Make the intended package changes. Set `package.json` to the new version,
such as `0.1.0-rc.0`, and rename `CHANGELOG.md`'s `## Unreleased` heading
to `## 0.1.0-rc.0`.
2. Run `pnpm run check`, then commit and push those changes to `main`.
3. Open GitHub Actions → **Release alpha** → **Run workflow**. Choose `main`
3. Open GitHub Actions → **Release** → **Run workflow**. Choose `main`
and enter the exact package version, without a `v` prefix.
4. Verify the run succeeds, npm exposes the version through `latest`, and the
matching GitHub prerelease exists.

The workflow rejects a different branch, invalid or mismatched versions, missing
release notes, an existing npm version, and an existing Git tag. It does not
support stable releases yet. The published `0.1.0-alpha.0` cannot be republished.
release notes, an existing npm version, and an existing Git tag. It takes
`-alpha.N` and `-rc.N` versions only, not stable releases yet. The published
`0.1.0-alpha.0` cannot be republished.

The build job has read-only repository permissions. Only the publishing job
receives OIDC and release-write permissions. Its tarball and release notes come
Expand Down
Binary file modified assets/sk-banner.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading