diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ded4828..080b9f0 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,4 +1,4 @@
-name: Release alpha
+name: Release
env:
HUSKY: 0
@@ -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
@@ -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
diff --git a/AGENTS.md b/AGENTS.md
index 14d0ad0..ddccf75 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -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
@@ -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 ``
- 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
+ `` is a file, compiled together like a page's
+ (`README.md` in `documents`). A README example marked
+ `` 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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dd94901..10e20d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,9 +1,272 @@
# Changelog
-## Unreleased
+## 0.1.0-rc.0
+
+The first release candidate for `0.1.0`. The public API is now frozen, and
+later `0.1` releases only add to it.
+
+### Added
+
+- `authFetch` takes a `URL` or a `Request` as well as a path, as `fetch`
+ does. An HTTP client with a `fetch` option can now send its requests
+ through it, and they keep its safeguards: the token stays on one origin, a
+ 401 refreshes once, and only a GET or HEAD is sent again. The
+ [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients)
+ page shows ky, axios with its `fetch` adapter, and openapi-fetch. It
+ replaces the ky recipe built on hooks, and keeps the axios interceptors for
+ an instance on axios's default adapter.
+- `UseMirrorAuthOptions`, the type of `useMirrorAuth`'s options.
+- Hooks without a hooks file. `@monarcode/session-kit/react` exports
+ `AuthProvider`, `useAuth` and `useAuthClient`, typed by the client you
+ register once in `Register`, from `@monarcode/session-kit`. Until you
+ register one, `AuthProvider` takes any client, and the user is `unknown`.
+ `ProvidedAuth` names the client they use.
+ `createAuthHooks` stays, for an app with several clients.
+
+ ```ts
+ declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: typeof auth;
+ }
+ }
+ ```
+
+- `@monarcode/session-kit/tanstack-router` exports `useAuth` and
+ `useAuthClient`, which read the client from Router context and are typed
+ by the Router you register. They need no `AuthProvider` and no
+ registration of their own.
+- One request's session on the server, without passing its cookie jar.
+ `startAuth(serverAuth)` in `@monarcode/session-kit/tanstack-start/server`
+ finds the request on each call, so it's made once, at module level, and
+ one `createAuthFetch` over it serves every request.
+ `routerAuth(serverAuth)` in `@monarcode/session-kit/react-router/server`
+ takes the route's `context`. The guides use these. The jar-first methods
+ stay, for servers without an adapter.
+
+ ```ts
+ // Before
+ await serverAuth.signIn(startJar(), tokens);
+ // After
+ export const session = startAuth(serverAuth);
+ await session.signIn(tokens);
+ ```
+
+- `serverAuth.forRequest(jar)` has every method now: `signIn`,
+ `updateUser`, `refreshIfDue` and `clientCredentials` join the rest.
+- `SessionOf` and `UserOf` in `@monarcode/session-kit` give the
+ session and user types of any client: one from `createAuth`,
+ `createMirrorAuth` or `createServerAuth`, or a request's session.
+
+ ```ts
+ type AppSession = SessionOf; // { sessionId, user }
+ ```
+
+- Middleware and server guards for the server-rendered setups, in place of
+ the code the guides had you copy. Each refreshes before rendering, while a
+ cookie can still be set, and ignores a failed refresh. The TanStack Start
+ and React Router middleware also mark each response that doesn't set its
+ own `Cache-Control` as `private, no-store` (`cacheControl` changes or
+ skips it). Next.js marks pages that read cookies `no-store` itself.
+ - TanStack Start: `refreshSession(serverAuth, options?)` in
+ `@monarcode/session-kit/tanstack-start/server`, a handler for Start's
+ `createMiddleware({ type: "request" }).server()`. Start strips what's in
+ `.server()` from the browser bundle, `serverAuth` included.
+ - React Router: `sessionMiddleware(serverAuth, options?)` for the root
+ route, `requireSession(serverAuth, { loginPath, basename })` for guarded
+ routes, whose `session(context)` gives their loaders a session that's
+ never `null`, and `redirectIfSignedIn(serverAuth, options?)` as the
+ sign-in page's loader, in `@monarcode/session-kit/react-router/server`.
+ - Next.js: `nextSession(serverAuth, { cookies, redirect })` in
+ `@monarcode/session-kit/next`, with `get()`, `require(path)` and
+ `redirectIfSignedIn(redirectTo)` for Server Components, `readOnly()` and
+ `writable()` for the request's session, and `refresh(request, response)`
+ for `proxy.ts`. You pass Next's own `cookies` and `redirect`.
+
+ ```ts
+ // app/root.tsx
+ export const middleware = sessionMiddleware(serverAuth);
+ // app/routes/protected.tsx
+ export const middleware = [signedIn]; // signedIn = requireSession(serverAuth)
+ ```
+
+- `loginHref(loginPath, returnTo)` in `@monarcode/session-kit` builds the
+ sign-in page's URL with `?redirectTo=`, for a guard of your own.
+- `SessionMiddlewareOptions` in `@monarcode/session-kit/server`: `within`
+ and `cacheControl`, for `refreshSession` and `sessionMiddleware`.
+- A session route, in place of the server functions, Server Functions and
+ resource routes the guides had you write for the browser's client. It
+ reads the session, signs out, and gets or renews the access token when
+ `createServerAuth` has `clientCredentials`. It answers your own site's
+ pages only (by `Sec-Fetch-Site`, or a `POST`'s `Origin` on plain http),
+ with `Cache-Control: no-store`. Signing in stays your own code.
+ - `createMirrorAuth({ endpoint })` calls it. `revalidate`, `signOut` and
+ `credentials` are optional now, and win over `endpoint` when given. The
+ options' type needs `endpoint`, or `revalidate` and `signOut`. A failure
+ the server reports rejects with its `AuthErrorCode`.
+ - `sessionHandler(serverAuth)` in `@monarcode/session-kit/server` answers
+ it, for a request and its cookie jar (`SessionHandler`).
+ - `sessionRoute(serverAuth)` wraps it for each framework: a server route's
+ `handlers` in `@monarcode/session-kit/tanstack-start/server`
+ (`StartSessionRoute`), a resource route's `loader` and `action` in
+ `@monarcode/session-kit/react-router/server` (`RouterSessionRoute`), and
+ a Route Handler's `GET` and `POST` in `@monarcode/session-kit/next`, with
+ Next's `cookies` in `NextSessionRouteOptions` (`NextSessionRoute`).
+
+ ```ts
+ // app/api/session/route.ts
+ export const { GET, POST } = sessionRoute(serverAuth, { cookies });
+ // lib/auth/client.ts
+ createMirrorAuth({ name: "app", session, endpoint: "/api/session", signIn });
+ ```
+
+- `isSignedIn(state)` in `@monarcode/session-kit`: `true` while
+ `authenticated` or `refreshing`, and `false` while `locked`. It narrows
+ `user`, and works as a selector: `useAuth(isSignedIn)`.
+- `requireSessionLoader(auth, options?)` and
+ `redirectIfSignedInLoader(auth, options?)` in
+ `@monarcode/session-kit/react-router` make the guards' loaders, for
+ `loader` or `clientLoader`. The second reads `?redirectTo=` from the URL.
+ Their options are `RequireSessionLoaderOptions` and
+ `RedirectIfSignedInLoaderOptions`, and they return `RequireSessionLoader`
+ and `RedirectIfSignedInLoader`. `requireSession` and `redirectIfSignedIn`
+ stay, for a loader that does more.
+
+ ```ts
+ export const clientLoader = requireSessionLoader(auth);
+ ```
+
+- `loginPath` defaults to `"/login"` in `requireSession` for TanStack Router
+ and React Router, and in React Router's `SessionOutlet`.
+- `deepLinkHandler(auth, options?)` in `@monarcode/session-kit/expo` makes
+ `redirectSystemPath` for `app/+native-intent.tsx` (`DeepLinkHandler`).
+ `rememberDeepLink` stays, for a `redirectSystemPath` that does more.
+- `AuthRouter` in `@monarcode/session-kit/tanstack-router`, the Router type
+ `connectAuth` takes, for typing a function that takes your Router.
+- `NextSession` has `signIn`, `signOut` and, with a user schema,
+ `updateUser`, so a Server Function writes `await session.signIn(tokens)`
+ rather than `await (await session.writable()).signIn(tokens)`. The Next.js
+ guide and example use them.
### Changed
+- **Breaking:** the session route answers 500, not 400, for an
+ `INVALID_OPTIONS` that comes from the server's setup, such as a missing
+ secret, `clientCredentials` not turned on, or React Router's middleware
+ not added. A request it can't read still answers 400.
+- A saved session past `maxAge`, or saved by another version, signs out
+ without an error, and `unlock()` resolves `null` for one. It set
+ `INVALID_SESSION` in `state.error`, which an app showing errors showed
+ after 30 idle days or an upgrade. A malformed saved session still does.
+- The Server sessions page says how to read the secret on Cloudflare
+ Workers.
+
+- **Breaking:** `createAuthFetch` takes the base URL as an option, as
+ `sessionBearer` does. A missing `baseUrl` throws `INVALID_OPTIONS`.
+
+ ```ts
+ // Before
+ createAuthFetch(auth, "https://api.example.com/", { optional: true });
+ // After
+ createAuthFetch(auth, {
+ baseUrl: "https://api.example.com/",
+ optional: true,
+ });
+ ```
+
+- **Breaking:** `AuthFetch`'s first parameter is `string | URL | Request`,
+ not `string`. Only code that implements the type is affected, such as a
+ test fake that declares `(path: string) => …`: widen its parameter.
+- `authFetch` rejects with `INVALID_OPTIONS` when called with no path. It
+ used to request `undefined` under the base URL.
+- `authFetch` asks for the credentials before it builds the request. Signed
+ out or locked, a call with an `init` that `Request` refuses now rejects
+ with `UNAUTHENTICATED` or `LOCKED`, not with `Request`'s `TypeError`.
+- **Breaking:** the `signIn` of a `createMirrorAuth` client rejects with what
+ your `signIn` option threw, unchanged, as a sign-in in a single-page app
+ does. It used to wrap it in a `USER_VALIDATION_FAILED` `AuthError`, so a
+ sign-in form had to read the message from `cause`. A result that isn't a
+ session still rejects with `INVALID_SESSION`.
+
+ ```ts
+ // Before
+ const reason = error instanceof Error ? error.cause : undefined;
+ setError(reason instanceof Error ? reason.message : "Could not sign in");
+ // After
+ setError(error instanceof Error ? error.message : "Could not sign in");
+ ```
+
+- **Breaking:** `useMirrorAuth` takes one options object, and throws
+ `INVALID_OPTIONS` without `create` or `onChange`.
+
+ ```ts
+ // Before
+ useMirrorAuth(createAppAuth, session, () => router.refresh());
+ // After
+ useMirrorAuth({
+ create: createAppAuth,
+ session,
+ onChange: () => router.refresh(),
+ });
+ ```
+
+- **Breaking:** TanStack Start's `connectSession(router)` replaces
+ `sessionHydration(auth)` and the `connectAuth(router)` beside it. It keeps
+ the router's own `dehydrate` and `hydrate`, which `...sessionHydration(auth)`
+ replaced, or was replaced by, depending on the order of the spread.
+ `sessionHydration`, `SessionHydration` and `DehydratedSession` are removed.
+
+ ```ts
+ // Before
+ const router = createRouter({
+ routeTree,
+ context: { auth },
+ ...sessionHydration(auth),
+ });
+ connectAuth(router);
+ // After
+ const router = createRouter({ routeTree, context: { auth } });
+ connectSession(router);
+ ```
+
+- **Breaking:** `Register` and `RegisteredAuth` moved from
+ `@monarcode/session-kit/effect` to `@monarcode/session-kit`, so one
+ registration types the hooks and the Effect service. Change the module you
+ augment. The other `Registered…` types stay in `./effect`. Register a
+ client from `createAuth` or `createMirrorAuth`: anything else now types the
+ hooks and the Effect service as `never`, where the Effect service used to
+ fall back to an `unknown` user.
+
+ ```ts
+ // Before
+ declare module "@monarcode/session-kit/effect" {
+ interface Register {
+ auth: typeof auth;
+ }
+ }
+ // After
+ declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: typeof auth;
+ }
+ }
+ ```
+
+- **Breaking:** in `@monarcode/session-kit/tanstack-router`, `useRouterAuth`
+ is now `useAuthClient`, and `RegisteredAuth` is now `RouterAuth`, so it
+ isn't confused with the main entry point's. When `auth` is optional in
+ Router context, `useAuthClient` returns the client without `undefined`, as
+ it throws when there's none. A hooks file made with
+ `createAuthHooks({ useClient: useRouterAuth })` can go: import `useAuth`
+ and `useAuthClient` from `@monarcode/session-kit/tanstack-router` instead.
+- **Breaking:** `RequestAuth` takes the user `signIn` accepts as a second
+ type parameter, as `ServerAuth` does: `RequestAuth`, or
+ `RequestAuth` when the user comes from the access token. Most
+ apps write `SessionOf` or `UserOf` instead.
+- Effect's `Auth.layer` binds a session from `startAuth` to the request
+ that's current when it's called, and throws `INVALID_OPTIONS` outside
+ one. `Auth.signIn` and `Auth.updateUser` still die on a request's session,
+ and now point at its own `signIn` and `updateUser`.
+
- The guides moved to the documentation site,
[session-kit.pages.dev](https://session-kit.pages.dev), with an API
reference for every entry point and every error code. The README is now a
@@ -22,10 +285,9 @@
`defaultError` to effetch-query's `endpoints`. `sessionBearer`'s example
calls the client's methods too.
- `AuthErrorCode`'s docs say which codes the browser client of a
- server-rendered app rejects with: `USER_VALIDATION_FAILED` when signing in
- on the server fails, `PERSISTENCE_FAILED` when signing out there fails, and
- `REFRESH_FAILED` when reading the session or the access token from the
- server fails.
+ server-rendered app rejects with: `PERSISTENCE_FAILED` when signing out on
+ the server fails, and `REFRESH_FAILED` when reading the session or the
+ access token from the server fails.
- The setup guides are corrected against the code and the example apps. The
TanStack Start guard renders `SessionOutlet`, the Next.js guard sends users
back to the page they asked for after sign-in, and the React Router layout
@@ -37,11 +299,100 @@
- The compatibility page lists `effect` as a peer of `./effetch` as well as
`./effect`, and the entry points page orders the entry points as the
reference does.
+- The router guides' sign-in pages no longer navigate after a sign-in. The
+ sign-in page's guard runs again and sends the user on, so a form only signs
+ in. The server-rendering guides call the API with `createAuthFetch` over the
+ request's session, and the Expo guide adds the profile screen its deep-link
+ steps open.
+- The hovers on a request's session say what `signIn` takes, that it never
+ calls your backend and trusts its input, and which errors `signIn` and
+ `updateUser` reject with. `getSession`, `signOut` and `credentials.get` say
+ where to use them.
+- The `tanstack-start-spa-effetch` example is laid out as the Effect guide
+ is, in `backend.ts`, `refresh.ts`, `auth.ts`, `layer.ts`, `api.ts` and
+ `runtime.ts`. Its `FetchLive` layer is gone: the API client and the
+ refresh client each turn off Effect's tracing headers themselves, and the
+ runtime provides plain `FetchHttpClient.layer`. The guide's refresh client
+ now turns them off too. It sent them, which fails the preflight of an API
+ that doesn't allow them.
+- The React Router guide's Guards in loaders section says when to use
+ `requireSessionLoader` (the whole loader, usually a layout's) and
+ `requireSession` (inside a loader that loads data too). A page's loader that
+ calls your API checks the session itself, since React Router runs nested
+ routes' loaders at the same time.
+- A Hybrid setup page, under Server rendering: the browser signs in with
+ your backend and calls your API, and the server keeps the session. It shows
+ a server function that checks the tokens with your backend before
+ `session.signIn`, and one that passes them on unchecked, with when that's
+ safe.
+- `createMirrorAuth`'s `endpoint`, `revalidate` and `signOut` options show
+ their docs in editor hovers, which showed none. `revalidate`'s say when the
+ client calls it: when the tab becomes visible after 10 seconds or more, and
+ when another tab signs in or out.
- The reference lists the members of `AuthStorage`, `Tokens` and
`CookieJar`, the types an app builds itself. The server-rendering guides'
sign-in shows the backend's own message for a failed sign-in, as the
example apps do, and the secret-rotation example works once the old secret
is removed.
+- The hovers and the guides are checked line by line against the code. The
+ hovers name errors they left out: `PERSISTENCE_FAILED` from `signIn`,
+ `getSession` and `unlock`, `REFRESH_FAILED` and `SESSION_CHANGED` from
+ `credentials.renew`, `createAuthFetch` and `sessionBearer`, a request's
+ `getSession` and `refreshIfDue` on the server, the `INVALID_OPTIONS` that
+ guards, outlets and `sessionRoute` throw, and the session route's status
+ codes. `AuthErrorCode`'s docs cover a saved session older than `maxAge`, a
+ `locking.seal` that fails, and a refresh that times out.
+- Corrected in the docs: `signOut()` waits for `revoke`.
+ `signOutOnRepeated401: false` only stops a second 401 from signing users
+ out, and without a refresh token the first one still does. A read-only
+ request's `getSession` resolves, and only `credentials.get` rejects once
+ the token has expired. React Router passes loaders `url` from 7.15, not
+ from 8. `AFTER_FIRST_UNLOCK` is for a refresh while the device is locked.
+ Remove an old `secret` once `maxAge` has passed since the change.
+- The guides gain what they lacked: a Sign out section for TanStack Start,
+ `cacheControl` and the two sets of guards for React Router with server
+ rendering, the session route's checks on the Security page, storage that
+ can't be read on the Errors page, and what `secureStorage`, `SessionGate`
+ and `deepLinkHandler` do on the Expo page. The Expo guide's locking example
+ throws when a change to the device's biometrics made the key unreadable,
+ as its comment says, where it made a new key. The Effect guide's sign-in
+ button awaits `auth.signIn`, where a failed sign-in went unhandled.
+
+### Fixed
+
+- With a user read from the access token, `ServerAuth`, `RequestAuth` and
+ `NextSession` keep their names in editors and declaration files. Editors
+ showed internal names, and exporting such a value from a module that emits
+ declarations failed with TS4023. A session with a user schema is no longer
+ assignable to a token user's type, such as `RequestAuth`,
+ since their `signIn` takes different input.
+- The guides and examples call `login` on its own line before `signIn`,
+ rather than nesting the `await`.
+- `signOut()` before the saved session is restored, such as with
+ asynchronous storage or before the first `mount()`, revokes the saved
+ tokens. It cleared them without revoking, so the refresh token stayed
+ valid at the backend. A locked session still isn't revoked.
+- `safeReturnTo` matches a `loginPath` that has a query, such as
+ `"/login?tab=1"`, by its path. It returned the sign-in page as safe.
+- `redirectIfSignedIn` (both routers) rejects a `loginPath` that doesn't start
+ with `/` for every visitor, and `redirectIfSignedInLoader` when the loader
+ is made. It failed only once someone signed in.
+- `connectAuth` throws `INVALID_OPTIONS` when the Router's context has no
+ client as `auth`, and `nextSession` when called without options, where
+ each threw a `TypeError`.
+- `authFetch` rejects a `Request` from another realm or a polyfill with
+ `INVALID_OPTIONS`. It was sent as the path `"[object Request]"` under
+ `baseUrl`.
+- The docs say that React Router's loader guards can't keep a `#fragment`,
+ and that a Next.js Route Handler should answer 401 rather than call
+ `require` under a `basePath`.
+- The example apps match their guides. React Router's data mode imports
+ `RouterProvider` from `react-router/dom`, and the framework apps generate
+ route types. The effetch app retries before `sessionBearer` and resets
+ per account. The TanStack apps read the user from the guarded route's
+ context and keep `disconnectAuth`. A failed sign-in in React Router with
+ server rendering returns status 400, in the example and the guide, so the
+ loaders don't run again. Stale comments are corrected.
## 0.1.0-alpha.8
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 531ec5c..413cf4f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -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 `` 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
diff --git a/README.md b/README.md
index 5d8d678..f281f1b 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,9 @@
-
+
[](https://www.npmjs.com/package/@monarcode/session-kit)
[](https://github.com/monarcode/session-kit/actions/workflows/ci.yml)
-[](https://bundlejs.com/?q=@monarcode/session-kit)
-[](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D)
+[](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D)
+[](https://www.npmjs.com/package/@monarcode/session-kit)
[](https://www.npmjs.com/package/@monarcode/session-kit#provenance)
[](./LICENSE)
@@ -15,142 +15,171 @@
[](https://session-kit.pages.dev/docs/setups/expo)
[](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:
-
+
```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:
-
+
```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:
-
+
```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 (
+
+
+
+ );
+}
+
+function Home() {
+ const session = 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}
-
-
- );
+ if (session.status === "initializing") return
Restoring your session…
;
+ if (session.status === "unauthenticated") return ;
+ if (session.status === "unavailable") {
+ // The session couldn't be restored or refreshed, say while offline.
+ return (
+
+ );
}
+ return (
+
+
Welcome, {session.user.name}
+
+
+ );
}
```
-[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).
diff --git a/RELEASING.md b/RELEASING.md
index 1e339e4..2af3f02 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -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.
@@ -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
diff --git a/assets/sk-banner.png b/assets/sk-banner.png
index 317c39d..468a1d7 100644
Binary files a/assets/sk-banner.png and b/assets/sk-banner.png differ
diff --git a/examples/README.md b/examples/README.md
index 91083ed..9c656b1 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -53,19 +53,21 @@ run ios` and `run android` build it natively. In CI it is only bundled, with
Tokens last one minute, so the early refresh runs after about 30 seconds.
Requests omit `credentials: "include"`, which DummyJSON's own snippets use,
because session-kit keeps tokens out of cookies.
-- **Guards**: `requireSession` and `SessionOutlet` for TanStack Router and
- Start, `SessionOutlet` alone in React Router's declarative mode, and loader
- guards with `useAuthRevalidation` in data and framework mode.
+- **Guards**: `requireSession`, `redirectIfSignedIn` and `SessionOutlet` for
+ TanStack Router and Start. `SessionOutlet` alone in React Router's
+ declarative mode. `requireSessionLoader`, `redirectIfSignedInLoader`,
+ `SessionOutlet` and `useAuthRevalidation` in data and framework mode.
- **TanStack Start** sets `defaultSsr: false` in `src/start.ts`. Start's own
server still renders requests in SPA mode, and the guards need the browser's
saved session.
- **TanStack Start with Effect** is the SPA app written with Effect,
[effetch](https://github.com/monarcode/effetch) and
- [effetch-query](https://github.com/monarcode/effetch-query). `src/auth.ts`
- describes the user with an Effect Schema and refreshes through effetch.
- `src/api-client.ts` is the API client, a service whose `sessionBearer`
- plugin sends the access token, and `src/runtime.ts` composes the app's
- layers into one runtime. `src/endpoints.ts` declares the sign-in mutation
+ [effetch-query](https://github.com/monarcode/effetch-query), laid out as
+ the guide is. `src/backend.ts` describes DummyJSON with Effect Schemas,
+ `src/refresh.ts` refreshes through effetch, and `src/auth.ts` reads the
+ user from the access token. `src/api.ts` is the API client, a service whose
+ `sessionBearer` plugin sends the access token, and `src/runtime.ts`
+ composes the app's layers into one runtime. `src/endpoints.ts` declares the sign-in mutation
and the profile query, which `src/ui.tsx` uses with `useMutation` and
`useQuery`, and the root route gives each session its own query cache. The
hooks and the guards are the SPA app's. See
@@ -74,31 +76,34 @@ run ios` and `run android` build it natively. In CI it is only bundled, with
`httpOnly` cookie with `createServerAuth` (`src/auth/server.ts`), signs in
with DummyJSON from a server function, and refreshes in request middleware
(`src/start.ts`). `createMirrorAuth` gives the routes and components a
- client, filled by `loadSession` on the server and `sessionHydration` in the
- browser. `auth/me` is called both from a server function and, with
- `clientCredentials`, from the browser. Set `SESSION_SECRET` (32 or more
- random characters) to run `vite preview`; `vite dev` uses a development
- secret. The cookie is `Secure` outside `vite dev`, which Safari refuses
- over `http://localhost`: try `vite preview` in another browser. See
+ client, filled by `loadSession` on the server and `connectSession` in the
+ browser. The browser signs out and gets the access token through the
+ session route (`src/routes/api/session.ts`). `auth/me` is called both from
+ a server function and, with `clientCredentials`, from the browser. Set
+ `SESSION_SECRET` (32 or more random characters) to run `vite preview`;
+ `vite dev` uses a development secret. The cookie is `Secure` outside
+ `vite dev`, which Safari refuses over `http://localhost`: try
+ `vite preview` in another browser. See
[the guide](https://session-kit.pages.dev/docs/setups/tanstack-start).
- **Next.js** keeps the session the same way: Proxy refreshes it
(`proxy.ts`), Server Components read it through `lib/auth/session.ts`, and
- Server Functions in `app/actions.ts` sign in and out. `useMirrorAuth` in
+ a Server Function in `app/actions.ts` signs in. `useMirrorAuth` in
`app/providers.tsx` gives Client Components the client and renders the
page again when the session changes in the browser, so the pages'
- redirects run. The browser gets the access token from a Route Handler.
+ redirects run. The browser reads the session, signs out and gets the
+ access token through the session route (`app/api/session/route.ts`).
`SESSION_SECRET` and Safari work as for TanStack Start, with `next start`
and `next dev`. See [the guide](https://session-kit.pages.dev/docs/setups/next).
- **React Router with server rendering** keeps the session the same way.
- Root middleware (`app/auth/middleware.server.ts`) gives each request a
- cookie jar and refreshes, the root loader reads the session, and the sign-in
- route's action signs in with a plain form that works before scripts load.
+ The root route's `sessionMiddleware` gives each request a cookie jar and
+ refreshes, the root loader reads the session, and the sign-in route's
+ action signs in with a plain form that works before scripts load.
`useMirrorAuth` in `app/root.tsx` gives the components the client and runs
the loaders again when the session changes in the browser, so the
- protected route's middleware redirects. The browser signs out, revalidates
- and gets the access token through the resource routes in
- `app/routes/auth.*.ts`. `SESSION_SECRET` and Safari work as for TanStack
- Start, with `pnpm start` (after `pnpm build`) and `react-router dev`. See
+ protected route's `requireSession` guard redirects. The browser reads the
+ session, signs out and gets the access token through the session route in
+ `app/routes/auth.session.ts`. `SESSION_SECRET` and Safari work as for
+ TanStack Start, with `pnpm start` (after `pnpm build`) and `react-router dev`. See
[the guide](https://session-kit.pages.dev/docs/setups/react-router-ssr).
- **Expo Router** saves the session with `secureStorage()`. `SessionGate` in
`app/_layout.tsx` holds the splash screen, shows `src/unavailable.tsx`
@@ -108,7 +113,8 @@ run ios` and `run android` build it natively. In CI it is only bundled, with
`expo-secure-store` config plugin keeps the session out of Android backups.
Each app is self-contained, so it can be copied out on its own. That is why
-the client-side web apps have the same `ui.tsx` rather than sharing one. The
+the client-side web apps have the same `ui.tsx`, apart from where the hooks
+come from, rather than sharing one. The
server-rendered apps have their own, since they sign in on the server, and so
does the Effect app, whose handlers run Effects. The apps differ in where the
user comes from on purpose, so both user sources appear: the login response,
diff --git a/examples/expo-router/app/(app)/index.tsx b/examples/expo-router/app/(app)/index.tsx
index 8a51498..a3caeaa 100644
--- a/examples/expo-router/app/(app)/index.tsx
+++ b/examples/expo-router/app/(app)/index.tsx
@@ -1,9 +1,8 @@
import { Button, Text, View } from "react-native";
+import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
import { Link } from "expo-router";
-import { useAuth, useAuthClient } from "../../src/auth";
-
export default function Home() {
const firstName = useAuth((state) => state.user?.firstName);
const auth = useAuthClient();
diff --git a/examples/expo-router/app/+native-intent.tsx b/examples/expo-router/app/+native-intent.tsx
index fc97214..6681e7a 100644
--- a/examples/expo-router/app/+native-intent.tsx
+++ b/examples/expo-router/app/+native-intent.tsx
@@ -1,18 +1,10 @@
-import { rememberDeepLink } from "@monarcode/session-kit/expo";
+import { deepLinkHandler } from "@monarcode/session-kit/expo";
import { auth } from "../src/auth";
/**
* Expo Router calls this with every URL that opens the app, before routing.
- * Remembers the link, so SessionGate can open it after a sign-in if
+ * It remembers the link, so SessionGate can open it after a sign-in if
* Stack.Protected turns it away now, and routes it unchanged.
*/
-export function redirectSystemPath({
- path,
-}: {
- path: string;
- initial: boolean;
-}) {
- rememberDeepLink(auth, path);
- return path;
-}
+export const redirectSystemPath = deepLinkHandler(auth);
diff --git a/examples/expo-router/app/_layout.tsx b/examples/expo-router/app/_layout.tsx
index 4ac89dd..4180f4d 100644
--- a/examples/expo-router/app/_layout.tsx
+++ b/examples/expo-router/app/_layout.tsx
@@ -1,9 +1,19 @@
+import { isSignedIn } from "@monarcode/session-kit";
import { SessionGate } from "@monarcode/session-kit/expo";
+import { AuthProvider, useAuth } from "@monarcode/session-kit/react";
import { SplashScreen, Stack } from "expo-router";
-import { auth, AuthProvider, useAuth } from "../src/auth";
+import { auth } from "../src/auth";
import { Unavailable } from "../src/unavailable";
+// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react`
+// with this client.
+declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: typeof auth;
+ }
+}
+
// Keeps the splash screen up until SessionGate hides it.
void SplashScreen.preventAutoHideAsync();
@@ -18,12 +28,9 @@ export default function RootLayout() {
}
function RootStack() {
- // Check `status`, not `user`: a locked session keeps its user. SessionGate
+ // A locked session isn't signed in, though it keeps its user. SessionGate
// handles `initializing` and `unavailable` before this renders.
- const signedIn = useAuth(
- (state) =>
- state.status === "authenticated" || state.status === "refreshing",
- );
+ const signedIn = useAuth(isSignedIn);
return (
diff --git a/examples/expo-router/src/auth.ts b/examples/expo-router/src/auth.ts
index 64daf06..aea131d 100644
--- a/examples/expo-router/src/auth.ts
+++ b/examples/expo-router/src/auth.ts
@@ -1,7 +1,6 @@
import { createAuth } from "@monarcode/session-kit";
import { secureStorage } from "@monarcode/session-kit/expo";
import { createAuthFetch } from "@monarcode/session-kit/http";
-import { createAuthHooks } from "@monarcode/session-kit/react";
import { z } from "zod";
/** DummyJSON's auth API: https://dummyjson.com/docs/auth */
@@ -29,9 +28,10 @@ export const auth = createAuth({
name: "expo-example",
user: userSchema,
// The iOS keychain, or Keystore-encrypted storage on Android. Two JWTs and
- // a user exceed SecureStore's 2048-byte value limit, so the value is split
- // across keys. The defaults are `clearOnReinstall: true` and SecureStore's
- // own `keychainAccessible` (`WHEN_UNLOCKED`).
+ // a user can pass 2048 bytes, which some iOS releases refuse to store in
+ // one value, so the value is split across keys. The defaults are
+ // `clearOnReinstall: true` and SecureStore's own `keychainAccessible`
+ // (`WHEN_UNLOCKED`).
storage: secureStorage(),
// Logs restores, refreshes, timers, and the gate's decisions to Metro in
// development. Tokens and user fields stay out of the log.
@@ -55,14 +55,11 @@ export const auth = createAuth({
},
});
-export const { AuthProvider, useAuth, useAuthClient } =
- createAuthHooks();
-
/**
* Sends requests to DummyJSON with the access token. After a 401 it
* refreshes, then replays a GET or HEAD once.
*/
-export const authFetch = createAuthFetch(auth, `${API}/`);
+export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
/** Signs in with DummyJSON, then saves the tokens and the user it returned. */
export async function signInWithPassword(username: string, password: string) {
diff --git a/examples/next-app/app/actions.ts b/examples/next-app/app/actions.ts
index bafbdeb..f0e5509 100644
--- a/examples/next-app/app/actions.ts
+++ b/examples/next-app/app/actions.ts
@@ -1,22 +1,12 @@
"use server";
-// Server Functions the browser calls. Each is a public endpoint: Next checks
-// that calls come from this site, and each one checks its own input.
-import { nextJar } from "@monarcode/session-kit/next";
-import { cookies } from "next/headers";
+// The sign-in the browser calls: a public endpoint. Next checks that calls
+// come from this site, and it checks its own input. The session route in
+// `api/session/route.ts` does the rest.
import { z } from "zod";
import { login } from "../lib/auth/backend";
-import { serverAuth } from "../lib/auth/server";
-
-async function jar() {
- return nextJar(await cookies(), { writable: true });
-}
-
-/** Who is signed in, from the cookie. Holds no tokens. */
-export async function getSessionAction() {
- return serverAuth.getSession(await jar());
-}
+import { session } from "../lib/auth/session";
const credentials = z.object({ username: z.string(), password: z.string() });
@@ -28,20 +18,11 @@ const credentials = z.object({ username: z.string(), password: z.string() });
export async function signInAction(input: unknown) {
const { username, password } = credentials.parse(input);
try {
- return {
- session: await serverAuth.signIn(
- await jar(),
- await login(username, password),
- ),
- };
+ const tokens = await login(username, password);
+ return { session: await session.signIn(tokens) };
} catch (error) {
return {
error: error instanceof Error ? error.message : "Could not sign in",
};
}
}
-
-/** Clears the cookie. */
-export async function signOutAction() {
- await serverAuth.signOut(await jar());
-}
diff --git a/examples/next-app/app/api/auth/credentials/route.ts b/examples/next-app/app/api/auth/credentials/route.ts
deleted file mode 100644
index 6a9d4d1..0000000
--- a/examples/next-app/app/api/auth/credentials/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { nextJar } from "@monarcode/session-kit/next";
-import { cookies } from "next/headers";
-import { z } from "zod";
-
-import { serverAuth } from "../../../../lib/auth/server";
-
-const rejected = z.object({ sessionId: z.string(), accessToken: z.string() });
-
-/**
- * The access token for the browser's own requests, never the refresh token:
- * a POST with no body gets it, and one with the token DummyJSON rejected
- * renews it. A route handler rather than a Server Function, so these calls
- * don't wait behind other Server Functions or render the page again.
- */
-export async function POST(request: Request) {
- // Route handlers get no CSRF check from Next: accept this site only.
- if (request.headers.get("sec-fetch-site") !== "same-origin")
- return new Response(null, { status: 403 });
- const jar = nextJar(await cookies(), { writable: true });
- const body = rejected.safeParse(await request.json().catch(() => null));
- const credentials = body.success
- ? await serverAuth.clientCredentials.renew(jar, body.data)
- : await serverAuth.clientCredentials.get(jar);
- return Response.json(credentials, {
- headers: { "Cache-Control": "no-store" },
- });
-}
diff --git a/examples/next-app/app/api/session/route.ts b/examples/next-app/app/api/session/route.ts
new file mode 100644
index 0000000..7c82f2b
--- /dev/null
+++ b/examples/next-app/app/api/session/route.ts
@@ -0,0 +1,10 @@
+import { sessionRoute } from "@monarcode/session-kit/next";
+import { cookies } from "next/headers";
+
+import { serverAuth } from "../../../lib/auth/server";
+
+/**
+ * The session route the browser's client calls: it reads the session, signs
+ * out, and gets the access token. It answers this site's own pages only.
+ */
+export const { GET, POST } = sessionRoute(serverAuth, { cookies });
diff --git a/examples/next-app/app/hooks.ts b/examples/next-app/app/hooks.ts
deleted file mode 100644
index ad697b9..0000000
--- a/examples/next-app/app/hooks.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-
-import type { AppAuth } from "../lib/auth/client";
-
-export const { AuthProvider, useAuth, useAuthClient } =
- createAuthHooks();
diff --git a/examples/next-app/app/layout.tsx b/examples/next-app/app/layout.tsx
index 93950ac..54ff386 100644
--- a/examples/next-app/app/layout.tsx
+++ b/examples/next-app/app/layout.tsx
@@ -1,6 +1,6 @@
import type { ReactNode } from "react";
-import { getSession } from "../lib/auth/session";
+import { session } from "../lib/auth/session";
import { Providers } from "./providers";
export const metadata = { title: "session-kit with Next.js" };
@@ -10,11 +10,11 @@ export default async function RootLayout({
}: {
children: ReactNode;
}) {
- const session = await getSession();
+ const current = await session.get();
return (
- {children}
+ {children}
);
diff --git a/examples/next-app/app/login/page.tsx b/examples/next-app/app/login/page.tsx
index 8751832..c620fc2 100644
--- a/examples/next-app/app/login/page.tsx
+++ b/examples/next-app/app/login/page.tsx
@@ -1,7 +1,4 @@
-import { safeReturnTo } from "@monarcode/session-kit";
-import { redirect } from "next/navigation";
-
-import { getSession } from "../../lib/auth/session";
+import { session } from "../../lib/auth/session";
import { LoginForm } from "../ui";
export default async function Login({
@@ -10,7 +7,6 @@ export default async function Login({
searchParams: Promise>;
}) {
// Signed in, before or after the form: the server sends the user on.
- if (await getSession())
- redirect(safeReturnTo((await searchParams).redirectTo));
+ await session.redirectIfSignedIn((await searchParams).redirectTo);
return ;
}
diff --git a/examples/next-app/app/page.tsx b/examples/next-app/app/page.tsx
index 1696a39..d79fff5 100644
--- a/examples/next-app/app/page.tsx
+++ b/examples/next-app/app/page.tsx
@@ -1,29 +1,24 @@
-import { nextJar } from "@monarcode/session-kit/next";
-import { cookies } from "next/headers";
+import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";
import { API } from "../lib/auth/api";
-import { serverAuth } from "../lib/auth/server";
-import { requireSession } from "../lib/auth/session";
+import { session } from "../lib/auth/session";
import { Profile } from "./ui";
/** Calls DummyJSON's `auth/me` while rendering, with the cookie's token. */
async function profileEmail() {
// Read-only: Proxy refreshed the token before this render.
- const credentials = await serverAuth.credentials.get(
- nextJar(await cookies()),
- );
- if (!credentials) return "Signed out";
- const response = await fetch(`${API}/auth/me`, {
- headers: { Authorization: `Bearer ${credentials.accessToken}` },
+ const apiFetch = createAuthFetch(await session.readOnly(), {
+ baseUrl: `${API}/`,
});
+ const response = await apiFetch("auth/me");
if (!response.ok) return `HTTP ${response.status}`;
const profile = z.object({ email: z.string() }).parse(await response.json());
return profile.email;
}
export default async function Home() {
- await requireSession("/");
+ await session.require("/");
const fromServer = await profileEmail().catch(
(error: unknown) => (error as Error).message,
);
diff --git a/examples/next-app/app/providers.tsx b/examples/next-app/app/providers.tsx
index 7203995..2e7aaca 100644
--- a/examples/next-app/app/providers.tsx
+++ b/examples/next-app/app/providers.tsx
@@ -2,17 +2,28 @@
import type { ReactNode } from "react";
-import { useMirrorAuth } from "@monarcode/session-kit/react";
+import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react";
import { useRouter } from "next/navigation";
-import { createAppAuth, type AppSession } from "../lib/auth/client";
-import { AuthProvider } from "./hooks";
+import {
+ createAppAuth,
+ type AppAuth,
+ type AppSession,
+} from "../lib/auth/client";
+
+// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react`
+// with this client.
+declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: AppAuth;
+ }
+}
/**
* Gives Client Components the session the layout read. `useMirrorAuth`
* follows the server's session when the page renders again, and renders it
- * again with `router.refresh()` when the session changes in the browser, as after a sign-out here
- * or in another tab, so the pages' redirects run.
+ * again with `router.refresh()` when the session changes in the browser, as
+ * after a sign-out here or in another tab, so the pages' redirects run.
*/
export function Providers({
session,
@@ -22,6 +33,10 @@ export function Providers({
children: ReactNode;
}) {
const router = useRouter();
- const auth = useMirrorAuth(createAppAuth, session, () => router.refresh());
+ const auth = useMirrorAuth({
+ create: createAppAuth,
+ session,
+ onChange: () => router.refresh(),
+ });
return {children};
}
diff --git a/examples/next-app/app/ui.tsx b/examples/next-app/app/ui.tsx
index 6de59f1..1cbfa69 100644
--- a/examples/next-app/app/ui.tsx
+++ b/examples/next-app/app/ui.tsx
@@ -3,9 +3,9 @@
import { useMemo, useState, type FormEvent } from "react";
import { createAuthFetch } from "@monarcode/session-kit/http";
+import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
import { API } from "../lib/auth/api";
-import { useAuth, useAuthClient } from "./hooks";
/**
* The sign-in form, prefilled with DummyJSON's documented test user. Once
@@ -29,10 +29,7 @@ export function LoginForm() {
});
} catch (cause) {
// The Server Function's own message, such as a wrong password.
- const reason = cause instanceof Error ? cause.cause : undefined;
- setError(
- reason instanceof Error ? reason.message : "Could not sign in",
- );
+ setError(cause instanceof Error ? cause.message : "Could not sign in");
setPending(false);
}
}
@@ -80,7 +77,10 @@ export function Profile({ fromServer }: { fromServer: string }) {
const user = useAuth((state) => state.user);
const auth = useAuthClient();
// The browser's requests get the access token from the server, in memory.
- const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]);
+ const authFetch = useMemo(
+ () => createAuthFetch(auth, { baseUrl: `${API}/` }),
+ [auth],
+ );
const [fromBrowser, setFromBrowser] = useState("");
async function loadProfile() {
@@ -107,7 +107,9 @@ export function Profile({ fromServer }: { fromServer: string }) {
Load profile in the browser
{fromBrowser &&
auth/me in the browser: {fromBrowser}
}
-
+
);
}
diff --git a/examples/next-app/lib/auth/client.ts b/examples/next-app/lib/auth/client.ts
index 68f1ae7..e41f603 100644
--- a/examples/next-app/lib/auth/client.ts
+++ b/examples/next-app/lib/auth/client.ts
@@ -1,48 +1,27 @@
-import {
- createMirrorAuth,
- type ClientCredentials,
-} from "@monarcode/session-kit";
+import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit";
-import {
- getSessionAction,
- signInAction,
- signOutAction,
-} from "../../app/actions";
+import { signInAction } from "../../app/actions";
+// Types only: erased from the browser's bundle.
+import type { serverAuth } from "./server";
-export type AppSession = NonNullable<
- Awaited>
->;
-
-/** Asks the route handler for the access token, or renews `rejected`. */
-async function credentials(rejected?: object) {
- const response = await fetch("/api/auth/credentials", {
- method: "POST",
- body: JSON.stringify(rejected ?? null),
- });
- if (!response.ok) throw new Error(`Credentials failed (${response.status})`);
- return (await response.json()) as ClientCredentials | null;
-}
+export type AppSession = SessionOf;
/**
* The client the components use. It mirrors the session the server keeps in
- * its cookie, starting from the one the layout rendered. `useMirrorAuth`
- * creates it, once per request on the server and once in the browser.
+ * its cookie, starting from the one the layout rendered, and calls the
+ * session route in `app/api/session/route.ts`. `useMirrorAuth` creates it,
+ * once per request on the server and once in the browser.
*/
export function createAppAuth(session: AppSession | null) {
return createMirrorAuth({
name: "session-kit-example",
session,
- revalidate: getSessionAction,
+ 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;
},
- signOut: signOutAction,
- credentials: {
- get: () => credentials(),
- renew: (rejected) => credentials(rejected),
- },
});
}
diff --git a/examples/next-app/lib/auth/server.ts b/examples/next-app/lib/auth/server.ts
index 3d82a8a..00abba8 100644
--- a/examples/next-app/lib/auth/server.ts
+++ b/examples/next-app/lib/auth/server.ts
@@ -21,7 +21,7 @@ function sessionSecret(): string {
/**
* Keeps both tokens and the user in an encrypted, httpOnly cookie. With
* `clientCredentials`, the browser can ask for the access token too, through
- * the route handler in `app/api/auth/credentials`; the refresh token stays
+ * the session route in `app/api/session`; the refresh token stays
* here.
*/
export const serverAuth = createServerAuth({
diff --git a/examples/next-app/lib/auth/session.ts b/examples/next-app/lib/auth/session.ts
index 9d5fa3c..9fb40fd 100644
--- a/examples/next-app/lib/auth/session.ts
+++ b/examples/next-app/lib/auth/session.ts
@@ -1,26 +1,19 @@
-// The data access layer: how Server Components read the session.
+// How server code reads and changes the session.
import "server-only";
-import { cache } from "react";
-
-import { safeReturnTo } from "@monarcode/session-kit";
-import { nextJar } from "@monarcode/session-kit/next";
+import { nextSession } from "@monarcode/session-kit/next";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { serverAuth } from "./server";
/**
- * The session from the cookie, once per render. The jar is read-only, as
- * Server Components can't set cookies: Proxy refreshed it first.
+ * The session for Server Components, Server Functions, Route Handlers and
+ * Proxy. Server Components read it with `get` and `require`, which can't set
+ * cookies: Proxy refreshed it first, with `refresh`.
*/
-export const getSession = cache(async () =>
- serverAuth.getSession(nextJar(await cookies())),
-);
-
-/** The session, or a redirect to the sign-in page that comes back to `path`. */
-export async function requireSession(path: string) {
- const session = await getSession();
- if (!session)
- redirect(`/login?redirectTo=${encodeURIComponent(safeReturnTo(path))}`);
- return session;
-}
+export const session = nextSession(serverAuth, {
+ cookies,
+ redirect,
+ // The example's tokens live a minute: refresh in their last 15 seconds.
+ within: 15,
+});
diff --git a/examples/next-app/proxy.ts b/examples/next-app/proxy.ts
index ee0a211..11d9465 100644
--- a/examples/next-app/proxy.ts
+++ b/examples/next-app/proxy.ts
@@ -1,21 +1,15 @@
-import { proxyJar } from "@monarcode/session-kit/next";
import { NextResponse, type NextRequest } from "next/server";
-import { serverAuth } from "./lib/auth/server";
+import { session } from "./lib/auth/session";
/**
- * Refreshes access that is about to expire before Server Components and
- * Server Functions read it: they can't set cookies while rendering, but
- * Proxy can, and Next passes the new cookie on to them. A failed refresh is
+ * Refreshes access that is about to expire before any page or Server
+ * Function reads it. Server Components can't set cookies while rendering, so
+ * Proxy sets the new one, and Next passes it on to them. A failed refresh is
* left for the page, which then reads the session as it was.
*/
-export async function proxy(request: NextRequest) {
- const response = NextResponse.next();
- // The example's tokens live a minute: refresh in their last 15 seconds.
- await serverAuth
- .refreshIfDue(proxyJar(request, response), { within: 15 })
- .catch(() => {});
- return response;
+export function proxy(request: NextRequest) {
+ return session.refresh(request, NextResponse.next());
}
export const config = {
diff --git a/examples/react-router-data/src/auth.ts b/examples/react-router-data/src/auth.ts
index f509524..aeab929 100644
--- a/examples/react-router-data/src/auth.ts
+++ b/examples/react-router-data/src/auth.ts
@@ -38,7 +38,8 @@ export const auth = createAuth({
/** Signs in with DummyJSON and saves the tokens, which carry the user. */
export async function signInWithPassword(username: string, password: string) {
- await auth.signIn(tokens.parse(await login(username, password)));
+ const response = await login(username, password);
+ await auth.signIn(tokens.parse(response));
}
/**
@@ -88,4 +89,4 @@ async function login(username: string, password: string): Promise {
* Sends requests to DummyJSON with the access token. After a 401 it
* refreshes, then replays a GET or HEAD once.
*/
-export const authFetch = createAuthFetch(auth, `${API}/`);
+export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
diff --git a/examples/react-router-data/src/hooks.ts b/examples/react-router-data/src/hooks.ts
deleted file mode 100644
index 615afc3..0000000
--- a/examples/react-router-data/src/hooks.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-
-import type { auth } from "./auth";
-
-export const { AuthProvider, useAuth, useAuthClient } =
- createAuthHooks();
diff --git a/examples/react-router-data/src/main.tsx b/examples/react-router-data/src/main.tsx
index 629d8e5..0a2f53a 100644
--- a/examples/react-router-data/src/main.tsx
+++ b/examples/react-router-data/src/main.tsx
@@ -1,26 +1,27 @@
import { StrictMode } from "react";
-import {
- createBrowserRouter,
- Outlet,
- RouterProvider,
- useNavigate,
- useRouteError,
- useSearchParams,
-} from "react-router";
+import { createBrowserRouter, Outlet, useRouteError } from "react-router";
-import { safeReturnTo } from "@monarcode/session-kit";
+import { AuthProvider } from "@monarcode/session-kit/react";
import {
- redirectIfSignedIn,
- requireSession,
+ redirectIfSignedInLoader,
+ requireSessionLoader,
SessionOutlet,
useAuthRevalidation,
} from "@monarcode/session-kit/react-router";
import { createRoot } from "react-dom/client";
+import { RouterProvider } from "react-router/dom";
import { auth } from "./auth";
-import { AuthProvider } from "./hooks";
import { LoginForm, Pending, Profile, Unavailable } from "./ui";
+// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react`
+// with this client.
+declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: typeof auth;
+ }
+}
+
/**
* Re-runs the guards in loaders after a sign-in, sign-out, account switch,
* profile update, or a refresh that fails once access has expired. Token
@@ -31,18 +32,6 @@ function Root() {
return ;
}
-function Login() {
- const navigate = useNavigate();
- const [search] = useSearchParams();
- return (
-
- navigate(safeReturnTo(search.get("redirectTo")), { replace: true })
- }
- />
- );
-}
-
function RouteError() {
return ;
}
@@ -54,20 +43,13 @@ const router = createBrowserRouter([
children: [
{
path: "/login",
- loader: async ({ request }) => {
- const redirectTo = new URL(request.url).searchParams.get(
- "redirectTo",
- );
- await redirectIfSignedIn(auth, { redirectTo });
- return null;
- },
- element: ,
+ loader: redirectIfSignedInLoader(auth),
+ element: ,
},
{
- loader: ({ request }) =>
- requireSession(auth, { request, loginPath: "/login" }),
+ loader: requireSessionLoader(auth),
errorElement: ,
- element: } />,
+ element: } />,
children: [{ index: true, element: }],
},
],
diff --git a/examples/react-router-data/src/ui.tsx b/examples/react-router-data/src/ui.tsx
index c368f48..38d17ff 100644
--- a/examples/react-router-data/src/ui.tsx
+++ b/examples/react-router-data/src/ui.tsx
@@ -1,10 +1,15 @@
import { useState, type FormEvent } from "react";
+import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
+
import { authFetch, signInWithPassword } from "./auth";
-import { useAuth, useAuthClient } from "./hooks";
-/** The sign-in form, prefilled with DummyJSON's documented test user. */
-export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
+/**
+ * The sign-in form, prefilled with DummyJSON's documented test user. It
+ * doesn't navigate: a sign-in runs the guards again, and the sign-in page's
+ * guard sends the user on.
+ */
+export function LoginForm() {
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
@@ -18,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
String(form.get("username")),
String(form.get("password")),
);
- await onSignedIn();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
} finally {
@@ -90,7 +94,9 @@ export function Profile() {
Load profile
{fromApi &&
auth/me: {fromApi}
}
-
+
);
}
diff --git a/examples/react-router-declarative/src/auth.ts b/examples/react-router-declarative/src/auth.ts
index 9ec9c05..95a7da4 100644
--- a/examples/react-router-declarative/src/auth.ts
+++ b/examples/react-router-declarative/src/auth.ts
@@ -31,9 +31,8 @@ export const auth = createAuth({
/** Signs in with DummyJSON, then saves the tokens and the user it returned. */
export async function signInWithPassword(username: string, password: string) {
- const { accessToken, refreshToken, ...user } = loginResponse.parse(
- await login(username, password),
- );
+ const response = await login(username, password);
+ const { accessToken, refreshToken, ...user } = loginResponse.parse(response);
await auth.signIn({ accessToken, refreshToken, user });
}
@@ -84,4 +83,4 @@ async function login(username: string, password: string): Promise {
* Sends requests to DummyJSON with the access token. After a 401 it
* refreshes, then replays a GET or HEAD once.
*/
-export const authFetch = createAuthFetch(auth, `${API}/`);
+export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
diff --git a/examples/react-router-declarative/src/hooks.ts b/examples/react-router-declarative/src/hooks.ts
deleted file mode 100644
index 615afc3..0000000
--- a/examples/react-router-declarative/src/hooks.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-
-import type { auth } from "./auth";
-
-export const { AuthProvider, useAuth, useAuthClient } =
- createAuthHooks();
diff --git a/examples/react-router-declarative/src/main.tsx b/examples/react-router-declarative/src/main.tsx
index de5e719..1fb8cb5 100644
--- a/examples/react-router-declarative/src/main.tsx
+++ b/examples/react-router-declarative/src/main.tsx
@@ -7,27 +7,32 @@ import {
useSearchParams,
} from "react-router";
-import { safeReturnTo } from "@monarcode/session-kit";
+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";
-import { AuthProvider, useAuth } from "./hooks";
import { LoginForm, Pending, Profile, Unavailable } from "./ui";
+// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react`
+// with this client.
+declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: typeof auth;
+ }
+}
+
/**
* Doesn't navigate after `signIn`: the state change re-renders this page,
* which then redirects.
*/
function Login() {
- const signedIn = useAuth(
- (state) =>
- state.status === "authenticated" || state.status === "refreshing",
- );
+ const signedIn = useAuth(isSignedIn);
const [search] = useSearchParams();
if (signedIn)
return ;
- return {}} />;
+ return ;
}
createRoot(document.getElementById("root")!).render(
@@ -39,7 +44,6 @@ createRoot(document.getElementById("root")!).render(
}
unavailable={({ error }) => (
diff --git a/examples/react-router-declarative/src/ui.tsx b/examples/react-router-declarative/src/ui.tsx
index c368f48..38d17ff 100644
--- a/examples/react-router-declarative/src/ui.tsx
+++ b/examples/react-router-declarative/src/ui.tsx
@@ -1,10 +1,15 @@
import { useState, type FormEvent } from "react";
+import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
+
import { authFetch, signInWithPassword } from "./auth";
-import { useAuth, useAuthClient } from "./hooks";
-/** The sign-in form, prefilled with DummyJSON's documented test user. */
-export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
+/**
+ * The sign-in form, prefilled with DummyJSON's documented test user. It
+ * doesn't navigate: a sign-in runs the guards again, and the sign-in page's
+ * guard sends the user on.
+ */
+export function LoginForm() {
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
@@ -18,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
String(form.get("username")),
String(form.get("password")),
);
- await onSignedIn();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
} finally {
@@ -90,7 +94,9 @@ export function Profile() {
Load profile
{fromApi &&
auth/me: {fromApi}
}
-
+
);
}
diff --git a/examples/react-router-framework-spa/app/auth.ts b/examples/react-router-framework-spa/app/auth.ts
index 9ec9c05..95a7da4 100644
--- a/examples/react-router-framework-spa/app/auth.ts
+++ b/examples/react-router-framework-spa/app/auth.ts
@@ -31,9 +31,8 @@ export const auth = createAuth({
/** Signs in with DummyJSON, then saves the tokens and the user it returned. */
export async function signInWithPassword(username: string, password: string) {
- const { accessToken, refreshToken, ...user } = loginResponse.parse(
- await login(username, password),
- );
+ const response = await login(username, password);
+ const { accessToken, refreshToken, ...user } = loginResponse.parse(response);
await auth.signIn({ accessToken, refreshToken, user });
}
@@ -84,4 +83,4 @@ async function login(username: string, password: string): Promise {
* Sends requests to DummyJSON with the access token. After a 401 it
* refreshes, then replays a GET or HEAD once.
*/
-export const authFetch = createAuthFetch(auth, `${API}/`);
+export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
diff --git a/examples/react-router-framework-spa/app/hooks.ts b/examples/react-router-framework-spa/app/hooks.ts
deleted file mode 100644
index 615afc3..0000000
--- a/examples/react-router-framework-spa/app/hooks.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-
-import type { auth } from "./auth";
-
-export const { AuthProvider, useAuth, useAuthClient } =
- createAuthHooks();
diff --git a/examples/react-router-framework-spa/app/root.tsx b/examples/react-router-framework-spa/app/root.tsx
index 5aaf93d..cd0b337 100644
--- a/examples/react-router-framework-spa/app/root.tsx
+++ b/examples/react-router-framework-spa/app/root.tsx
@@ -1,12 +1,20 @@
import type { ReactNode } from "react";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
+import { AuthProvider } from "@monarcode/session-kit/react";
import { useAuthRevalidation } from "@monarcode/session-kit/react-router";
import { auth } from "./auth";
-import { AuthProvider } from "./hooks";
import { Pending } from "./ui";
+// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react`
+// with this client.
+declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: typeof auth;
+ }
+}
+
export function Layout({ children }: { children: ReactNode }) {
return (
diff --git a/examples/react-router-framework-spa/app/routes/login.tsx b/examples/react-router-framework-spa/app/routes/login.tsx
index 9494bd1..e2be783 100644
--- a/examples/react-router-framework-spa/app/routes/login.tsx
+++ b/examples/react-router-framework-spa/app/routes/login.tsx
@@ -1,25 +1,9 @@
-import { useNavigate, useSearchParams } from "react-router";
-
-import { safeReturnTo } from "@monarcode/session-kit";
-import { redirectIfSignedIn } from "@monarcode/session-kit/react-router";
+import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router";
import { auth } from "../auth";
import { LoginForm } from "../ui";
-export async function clientLoader({ request }: { request: Request }) {
- const redirectTo = new URL(request.url).searchParams.get("redirectTo");
- await redirectIfSignedIn(auth, { redirectTo });
- return null;
-}
+// Runs again after a sign-in, as useAuthRevalidation runs the loaders again.
+export const clientLoader = redirectIfSignedInLoader(auth);
-export default function Login() {
- const navigate = useNavigate();
- const [search] = useSearchParams();
- return (
-
- navigate(safeReturnTo(search.get("redirectTo")), { replace: true })
- }
- />
- );
-}
+export default LoginForm;
diff --git a/examples/react-router-framework-spa/app/routes/protected.tsx b/examples/react-router-framework-spa/app/routes/protected.tsx
index f40eea3..3cda2ed 100644
--- a/examples/react-router-framework-spa/app/routes/protected.tsx
+++ b/examples/react-router-framework-spa/app/routes/protected.tsx
@@ -1,19 +1,17 @@
import { useRouteError } from "react-router";
import {
- requireSession,
+ requireSessionLoader,
SessionOutlet,
} from "@monarcode/session-kit/react-router";
import { auth } from "../auth";
import { Pending, Unavailable } from "../ui";
-export function clientLoader({ request }: { request: Request }) {
- return requireSession(auth, { request, loginPath: "/login" });
-}
+export const clientLoader = requireSessionLoader(auth);
export default function Protected() {
- return } />;
+ return } />;
}
export function ErrorBoundary() {
diff --git a/examples/react-router-framework-spa/app/ui.tsx b/examples/react-router-framework-spa/app/ui.tsx
index c368f48..38d17ff 100644
--- a/examples/react-router-framework-spa/app/ui.tsx
+++ b/examples/react-router-framework-spa/app/ui.tsx
@@ -1,10 +1,15 @@
import { useState, type FormEvent } from "react";
+import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
+
import { authFetch, signInWithPassword } from "./auth";
-import { useAuth, useAuthClient } from "./hooks";
-/** The sign-in form, prefilled with DummyJSON's documented test user. */
-export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
+/**
+ * The sign-in form, prefilled with DummyJSON's documented test user. It
+ * doesn't navigate: a sign-in runs the guards again, and the sign-in page's
+ * guard sends the user on.
+ */
+export function LoginForm() {
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
@@ -18,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
String(form.get("username")),
String(form.get("password")),
);
- await onSignedIn();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
} finally {
@@ -90,7 +94,9 @@ export function Profile() {
Load profile
{fromApi &&
auth/me: {fromApi}
}
-
+
);
}
diff --git a/examples/react-router-framework-spa/tsconfig.json b/examples/react-router-framework-spa/tsconfig.json
index a10bd69..2a32730 100644
--- a/examples/react-router-framework-spa/tsconfig.json
+++ b/examples/react-router-framework-spa/tsconfig.json
@@ -9,7 +9,8 @@
"skipLibCheck": true,
"noEmit": true,
"isolatedModules": true,
+ "rootDirs": [".", "./.react-router/types"],
"types": ["vite/client"]
},
- "include": ["app", "*.ts"]
+ "include": ["app", "*.ts", ".react-router/types/**/*"]
}
diff --git a/examples/react-router-framework-ssr/app/auth/client.ts b/examples/react-router-framework-ssr/app/auth/client.ts
index eac0160..5410bc0 100644
--- a/examples/react-router-framework-ssr/app/auth/client.ts
+++ b/examples/react-router-framework-ssr/app/auth/client.ts
@@ -1,46 +1,21 @@
-import {
- createMirrorAuth,
- type ClientCredentials,
- type Session,
-} from "@monarcode/session-kit";
+import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit";
-import type { User } from "./backend";
+// Types only: erased from the browser's bundle.
+import type { serverAuth } from "./session.server";
-export type AppSession = Session;
-
-/** Calls one of the resource routes in `routes/auth.*.ts`. */
-async function call(method: "GET" | "POST", path: string, body?: object) {
- const response = await fetch(path, {
- method,
- ...(body && {
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- }),
- });
- if (!response.ok) throw new Error(`${path} failed (${response.status})`);
- return (await response.json()) as T;
-}
+export type AppSession = SessionOf;
/**
* The client the components use. It mirrors the session the server keeps in
- * its cookie, starting from the one the root loader read. `useMirrorAuth`
- * creates it, once per request on the server and once in the browser.
+ * its cookie, starting from the one the root loader read, and calls the
+ * session route in `routes/auth.session.ts`. `useMirrorAuth` creates it,
+ * once per request on the server and once in the browser.
*/
export function createAppAuth(session: AppSession | null) {
return createMirrorAuth({
name: "session-kit-example",
session,
- revalidate: () => call("GET", "/auth/session"),
- signOut: () => call("POST", "/auth/session"),
- credentials: {
- get: () => call("POST", "/auth/credentials"),
- renew: (rejected) =>
- call(
- "POST",
- "/auth/credentials",
- rejected,
- ),
- },
+ endpoint: "/auth/session",
});
}
diff --git a/examples/react-router-framework-ssr/app/auth/middleware.server.ts b/examples/react-router-framework-ssr/app/auth/middleware.server.ts
deleted file mode 100644
index d07b597..0000000
--- a/examples/react-router-framework-ssr/app/auth/middleware.server.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { redirect, type MiddlewareFunction } from "react-router";
-
-import {
- cookieJarMiddleware,
- routerJar,
-} from "@monarcode/session-kit/react-router/server";
-
-import { serverAuth } from "./session.server";
-
-/**
- * Refreshes access that is about to expire before loaders and actions read
- * it, while the response can still set the cookie. A failed refresh is left
- * for the loaders, which then read the session as it was.
- */
-const refreshSession: MiddlewareFunction = async (
- { context },
- next,
-) => {
- // The example's tokens live a minute: refresh in their last 15 seconds.
- await serverAuth
- .refreshIfDue(routerJar(context), { within: 15 })
- .catch(() => {});
- const response = await next();
- // Every page and resource route here depends on who is signed in. A
- // copy: some responses, such as `fetch`'s, can't change their headers.
- const page = new Response(response.body, response);
- page.headers.set("Cache-Control", "private, no-store");
- return page;
-};
-
-/**
- * The root route's middleware. The jar comes first: it sets the cookies the
- * rest write on the response.
- */
-export const sessionMiddleware = [cookieJarMiddleware, refreshSession];
-
-/**
- * Sends signed-out users to the sign-in page, which brings them back. As
- * middleware, it runs on the server before any loader or action below the
- * route, for documents and for data requests alike.
- */
-export const requireSession: MiddlewareFunction = async ({
- context,
- url,
-}) => {
- if (!(await serverAuth.getSession(routerJar(context))))
- throw redirect(
- `/login?redirectTo=${encodeURIComponent(url.pathname + url.search)}`,
- );
-};
diff --git a/examples/react-router-framework-ssr/app/auth/session.server.ts b/examples/react-router-framework-ssr/app/auth/session.server.ts
index dd4c1e6..27ced94 100644
--- a/examples/react-router-framework-ssr/app/auth/session.server.ts
+++ b/examples/react-router-framework-ssr/app/auth/session.server.ts
@@ -1,5 +1,9 @@
// Holds the secret and the tokens: the `.server` name keeps it out of the
// browser's bundle, and the build fails if browser code imports it.
+import {
+ requireSession,
+ routerAuth,
+} from "@monarcode/session-kit/react-router/server";
import { createServerAuth } from "@monarcode/session-kit/server";
import { refresh, userSchema } from "./backend";
@@ -19,7 +23,7 @@ function sessionSecret(): string {
/**
* Keeps both tokens and the user in an encrypted, httpOnly cookie. With
* `clientCredentials`, the browser can ask for the access token too, through
- * the resource route in `routes/auth.credentials.ts`; the refresh token stays
+ * the session route in `routes/auth.session.ts`; the refresh token stays
* here.
*/
export const serverAuth = createServerAuth({
@@ -31,3 +35,17 @@ export const serverAuth = createServerAuth({
// `react-router dev` serves plain http; Safari drops Secure cookies there.
cookie: { secure: !import.meta.env.DEV },
});
+
+/**
+ * The session of the request React Router is handling, by its `context`:
+ * `auth(context).getSession()` in a loader, action or middleware.
+ */
+export const auth = routerAuth(serverAuth);
+
+/**
+ * Lets only signed-in users through to the routes it guards, as middleware:
+ * it runs on the server before their loaders and actions, for page loads and
+ * navigation alike. Signed-out users go to the sign-in page, which brings
+ * them back. `signedIn.session(context)` gives those loaders the session.
+ */
+export const signedIn = requireSession(serverAuth);
diff --git a/examples/react-router-framework-ssr/app/hooks.ts b/examples/react-router-framework-ssr/app/hooks.ts
deleted file mode 100644
index 7a7c0b9..0000000
--- a/examples/react-router-framework-ssr/app/hooks.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-
-import type { AppAuth } from "./auth/client";
-
-export const { AuthProvider, useAuth, useAuthClient } =
- createAuthHooks();
diff --git a/examples/react-router-framework-ssr/app/root.tsx b/examples/react-router-framework-ssr/app/root.tsx
index fd3d839..7a9caee 100644
--- a/examples/react-router-framework-ssr/app/root.tsx
+++ b/examples/react-router-framework-ssr/app/root.tsx
@@ -11,19 +11,34 @@ import {
type LoaderFunctionArgs,
} from "react-router";
-import { useMirrorAuth } from "@monarcode/session-kit/react";
-import { routerJar } from "@monarcode/session-kit/react-router/server";
+import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react";
+import { sessionMiddleware } from "@monarcode/session-kit/react-router/server";
-import { createAppAuth } from "./auth/client";
-import { sessionMiddleware } from "./auth/middleware.server";
-import { serverAuth } from "./auth/session.server";
-import { AuthProvider } from "./hooks";
+import { createAppAuth, type AppAuth } from "./auth/client";
+import { auth, serverAuth } from "./auth/session.server";
-export const middleware = sessionMiddleware;
+// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react`
+// with this client.
+declare module "@monarcode/session-kit" {
+ interface Register {
+ auth: AppAuth;
+ }
+}
+
+/**
+ * Gives each request its cookies, then refreshes access that is about to
+ * expire before loaders and actions read it, while the response can still
+ * set the cookie. Every response is marked private, as each one depends on
+ * who is signed in.
+ */
+export const middleware = sessionMiddleware(serverAuth, {
+ // The example's tokens live a minute: refresh in their last 15 seconds.
+ within: 15,
+});
/** Who is signed in, from the cookie. Holds no tokens. */
export async function loader({ context }: LoaderFunctionArgs) {
- return { session: await serverAuth.getSession(routerJar(context)) };
+ return { session: await auth(context).getSession() };
}
export function Layout({ children }: { children: ReactNode }) {
@@ -57,7 +72,11 @@ export function Layout({ children }: { children: ReactNode }) {
export default function App() {
const { session } = useLoaderData();
const { revalidate } = useRevalidator();
- const auth = useMirrorAuth(createAppAuth, session, revalidate);
+ const auth = useMirrorAuth({
+ create: createAppAuth,
+ session,
+ onChange: revalidate,
+ });
return (
diff --git a/examples/react-router-framework-ssr/app/routes.ts b/examples/react-router-framework-ssr/app/routes.ts
index 4a6f0db..9bf6255 100644
--- a/examples/react-router-framework-ssr/app/routes.ts
+++ b/examples/react-router-framework-ssr/app/routes.ts
@@ -8,7 +8,6 @@ import {
export default [
route("login", "routes/login.tsx"),
layout("routes/protected.tsx", [index("routes/home.tsx")]),
- // Resource routes the browser's client calls.
+ // The session route the browser's client calls.
route("auth/session", "routes/auth.session.ts"),
- route("auth/credentials", "routes/auth.credentials.ts"),
] satisfies RouteConfig;
diff --git a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts b/examples/react-router-framework-ssr/app/routes/auth.credentials.ts
deleted file mode 100644
index 444d489..0000000
--- a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { ActionFunctionArgs } from "react-router";
-
-import { routerJar } from "@monarcode/session-kit/react-router/server";
-import { z } from "zod";
-
-import { serverAuth } from "../auth/session.server";
-
-const rejected = z.object({ sessionId: z.string(), accessToken: z.string() });
-
-/**
- * The access token for the browser's own requests, never the refresh token:
- * a POST with no body gets it, and one with the token DummyJSON rejected
- * renews it. React Router checks no origin for resource routes: accept this
- * site only.
- */
-export async function action({ request, context }: ActionFunctionArgs) {
- if (request.headers.get("sec-fetch-site") !== "same-origin")
- return new Response(null, { status: 403 });
- const jar = routerJar(context);
- const body = rejected.safeParse(await request.json().catch(() => null));
- return Response.json(
- body.success
- ? await serverAuth.clientCredentials.renew(jar, body.data)
- : await serverAuth.clientCredentials.get(jar),
- );
-}
diff --git a/examples/react-router-framework-ssr/app/routes/auth.session.ts b/examples/react-router-framework-ssr/app/routes/auth.session.ts
index 2dedf40..aa4efa8 100644
--- a/examples/react-router-framework-ssr/app/routes/auth.session.ts
+++ b/examples/react-router-framework-ssr/app/routes/auth.session.ts
@@ -1,21 +1,13 @@
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-
-import { routerJar } from "@monarcode/session-kit/react-router/server";
+import { sessionRoute } from "@monarcode/session-kit/react-router/server";
import { serverAuth } from "../auth/session.server";
-/** Who is signed in, from the cookie, for the client's `revalidate`. */
-export async function loader({ context }: LoaderFunctionArgs) {
- return Response.json(await serverAuth.getSession(routerJar(context)));
-}
-
/**
- * Signs out, for the client's `signOut`. React Router checks the origin of
- * route actions, but not of resource routes': accept this site only.
+ * The session route the browser's client calls: it reads the session, signs
+ * out, and gets the access token. It answers this site's own pages only.
*/
-export async function action({ request, context }: ActionFunctionArgs) {
- if (request.headers.get("sec-fetch-site") !== "same-origin")
- return new Response(null, { status: 403 });
- await serverAuth.signOut(routerJar(context));
- return Response.json(null);
-}
+const route = sessionRoute(serverAuth);
+
+// One by one: React Router's build can't remove a destructured export.
+export const loader = route.loader;
+export const action = route.action;
diff --git a/examples/react-router-framework-ssr/app/routes/home.tsx b/examples/react-router-framework-ssr/app/routes/home.tsx
index a4ced29..069df04 100644
--- a/examples/react-router-framework-ssr/app/routes/home.tsx
+++ b/examples/react-router-framework-ssr/app/routes/home.tsx
@@ -1,35 +1,22 @@
import { useLoaderData, type LoaderFunctionArgs } from "react-router";
-import { routerJar } from "@monarcode/session-kit/react-router/server";
+import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";
import { API } from "../auth/api";
-import { serverAuth } from "../auth/session.server";
+import { auth } from "../auth/session.server";
import { Profile } from "../ui";
/** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */
export async function loader({ context }: LoaderFunctionArgs) {
- const jar = routerJar(context);
- const credentials = await serverAuth.credentials.get(jar);
- if (!credentials) return { email: "Signed out" };
- let response = await me(credentials.accessToken);
- if (response.status === 401) {
- // Refreshes once, then tries again.
- const renewed = await serverAuth.credentials.renew(jar, credentials);
- if (!renewed) return { email: "Signed out" };
- response = await me(renewed.accessToken);
- }
+ // After a 401, it renews the token, saves it in the cookie, and tries again.
+ const apiFetch = createAuthFetch(auth(context), { baseUrl: `${API}/` });
+ const response = await apiFetch("auth/me");
if (!response.ok) return { email: `HTTP ${response.status}` };
const profile = z.object({ email: z.string() }).parse(await response.json());
return { email: profile.email };
}
-function me(accessToken: string) {
- return fetch(`${API}/auth/me`, {
- headers: { Authorization: `Bearer ${accessToken}` },
- });
-}
-
export default function Home() {
const { email } = useLoaderData();
return ;
diff --git a/examples/react-router-framework-ssr/app/routes/login.tsx b/examples/react-router-framework-ssr/app/routes/login.tsx
index e1352a2..0026ad1 100644
--- a/examples/react-router-framework-ssr/app/routes/login.tsx
+++ b/examples/react-router-framework-ssr/app/routes/login.tsx
@@ -1,44 +1,42 @@
import {
+ data,
redirect,
useActionData,
useNavigation,
type ActionFunctionArgs,
- type LoaderFunctionArgs,
} from "react-router";
import { safeReturnTo } from "@monarcode/session-kit";
-import { routerJar } from "@monarcode/session-kit/react-router/server";
+import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server";
import { login } from "../auth/backend";
-import { serverAuth } from "../auth/session.server";
+import { auth, serverAuth } from "../auth/session.server";
import { LoginForm } from "../ui";
-/** Signed in, before or after the form: the server sends the user on. */
-export async function loader({ context, url }: LoaderFunctionArgs) {
- if (await serverAuth.getSession(routerJar(context)))
- throw redirect(safeReturnTo(url.searchParams.get("redirectTo")));
- return null;
-}
+/** Signed in already: the server sends the user on to `redirectTo`. */
+export const loader = redirectIfSignedIn(serverAuth);
/**
* Signs in with DummyJSON on the server and sets the cookie. React Router
* checks that the form came from this site. A failure is returned for the
- * form to show.
+ * form to show, with status 400, so React Router skips running the loaders
+ * again.
*/
export async function action({ request, context, url }: ActionFunctionArgs) {
const form = await request.formData();
try {
- await serverAuth.signIn(
- routerJar(context),
- await login(
- String(form.get("username")),
- String(form.get("password")),
- ),
+ const tokens = await login(
+ String(form.get("username")),
+ String(form.get("password")),
);
+ await auth(context).signIn(tokens);
} catch (error) {
- return {
- error: error instanceof Error ? error.message : "Could not sign in",
- };
+ return data(
+ {
+ error: error instanceof Error ? error.message : "Could not sign in",
+ },
+ { status: 400 },
+ );
}
throw redirect(safeReturnTo(url.searchParams.get("redirectTo")));
}
diff --git a/examples/react-router-framework-ssr/app/routes/protected.tsx b/examples/react-router-framework-ssr/app/routes/protected.tsx
index 9d2050f..351fd3d 100644
--- a/examples/react-router-framework-ssr/app/routes/protected.tsx
+++ b/examples/react-router-framework-ssr/app/routes/protected.tsx
@@ -1,8 +1,12 @@
import { Outlet } from "react-router";
-import { requireSession } from "../auth/middleware.server";
+import { signedIn } from "../auth/session.server";
-export const middleware = [requireSession];
+export const middleware = [signedIn];
+
+// So navigation in the browser runs the middleware, whatever the routes
+// nested here load.
+export const loader = () => null;
export default function Protected() {
return ;
diff --git a/examples/react-router-framework-ssr/app/ui.tsx b/examples/react-router-framework-ssr/app/ui.tsx
index 80ea9f4..bbc3ebd 100644
--- a/examples/react-router-framework-ssr/app/ui.tsx
+++ b/examples/react-router-framework-ssr/app/ui.tsx
@@ -2,9 +2,9 @@ import { useMemo, useState } from "react";
import { Form } from "react-router";
import { createAuthFetch } from "@monarcode/session-kit/http";
+import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
import { API } from "./auth/api";
-import { useAuth, useAuthClient } from "./hooks";
/**
* The sign-in form, prefilled with DummyJSON's documented test user. It
@@ -60,7 +60,10 @@ export function Profile({ fromServer }: { fromServer: string }) {
const user = useAuth((state) => state.user);
const auth = useAuthClient();
// The browser's requests get the access token from the server, in memory.
- const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]);
+ const authFetch = useMemo(
+ () => createAuthFetch(auth, { baseUrl: `${API}/` }),
+ [auth],
+ );
const [fromBrowser, setFromBrowser] = useState("");
async function loadProfile() {
@@ -87,7 +90,9 @@ export function Profile({ fromServer }: { fromServer: string }) {
Load profile in the browser
{fromBrowser &&
auth/me in the browser: {fromBrowser}
}
-
+
);
}
diff --git a/examples/react-router-framework-ssr/tsconfig.json b/examples/react-router-framework-ssr/tsconfig.json
index 5af911a..a125136 100644
--- a/examples/react-router-framework-ssr/tsconfig.json
+++ b/examples/react-router-framework-ssr/tsconfig.json
@@ -9,7 +9,8 @@
"skipLibCheck": true,
"noEmit": true,
"isolatedModules": true,
+ "rootDirs": [".", "./.react-router/types"],
"types": ["vite/client", "node"]
},
- "include": ["app", "*.ts"]
+ "include": ["app", "*.ts", ".react-router/types/**/*"]
}
diff --git a/examples/tanstack-router/src/auth.ts b/examples/tanstack-router/src/auth.ts
index 9ec9c05..95a7da4 100644
--- a/examples/tanstack-router/src/auth.ts
+++ b/examples/tanstack-router/src/auth.ts
@@ -31,9 +31,8 @@ export const auth = createAuth({
/** Signs in with DummyJSON, then saves the tokens and the user it returned. */
export async function signInWithPassword(username: string, password: string) {
- const { accessToken, refreshToken, ...user } = loginResponse.parse(
- await login(username, password),
- );
+ const response = await login(username, password);
+ const { accessToken, refreshToken, ...user } = loginResponse.parse(response);
await auth.signIn({ accessToken, refreshToken, user });
}
@@ -84,4 +83,4 @@ async function login(username: string, password: string): Promise {
* Sends requests to DummyJSON with the access token. After a 401 it
* refreshes, then replays a GET or HEAD once.
*/
-export const authFetch = createAuthFetch(auth, `${API}/`);
+export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
diff --git a/examples/tanstack-router/src/hooks.ts b/examples/tanstack-router/src/hooks.ts
deleted file mode 100644
index a6294ae..0000000
--- a/examples/tanstack-router/src/hooks.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-import { useRouterAuth } from "@monarcode/session-kit/tanstack-router";
-
-// Reads the client from Router context, so no provider is needed.
-export const { useAuth, useAuthClient } = createAuthHooks({
- useClient: useRouterAuth,
-});
diff --git a/examples/tanstack-router/src/router.tsx b/examples/tanstack-router/src/router.tsx
index 2465c7f..bc704ba 100644
--- a/examples/tanstack-router/src/router.tsx
+++ b/examples/tanstack-router/src/router.tsx
@@ -11,8 +11,9 @@ export const router = createRouter({
defaultPendingComponent: Pending,
});
-// Restores the session, runs expiry timers and tab sync, and re-runs guards.
-connectAuth(router);
+// 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 {
diff --git a/examples/tanstack-router/src/routes/_authenticated.tsx b/examples/tanstack-router/src/routes/_authenticated.tsx
index eef8802..11e5f0c 100644
--- a/examples/tanstack-router/src/routes/_authenticated.tsx
+++ b/examples/tanstack-router/src/routes/_authenticated.tsx
@@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
- requireSession(context.auth, { location, loginPath: "/login" }),
+ requireSession(context.auth, { location }),
errorComponent: ({ error }) => ,
component: () => } />,
});
diff --git a/examples/tanstack-router/src/routes/login.tsx b/examples/tanstack-router/src/routes/login.tsx
index 06976a2..2806f36 100644
--- a/examples/tanstack-router/src/routes/login.tsx
+++ b/examples/tanstack-router/src/routes/login.tsx
@@ -1,6 +1,6 @@
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router";
-import { createFileRoute, useRouter } from "@tanstack/react-router";
+import { createFileRoute } from "@tanstack/react-router";
import { LoginForm } from "../ui";
@@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({
validateSearch: (search: Record) => ({
redirectTo: safeReturnTo(search.redirectTo),
}),
+ // Runs again after a sign-in, which runs the guards again.
beforeLoad: ({ context, search }) =>
redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
- component: Login,
+ component: LoginForm,
});
-
-function Login() {
- const router = useRouter();
- const { redirectTo } = Route.useSearch();
- return (
- router.navigate({ href: redirectTo, replace: true })}
- />
- );
-}
diff --git a/examples/tanstack-router/src/ui.tsx b/examples/tanstack-router/src/ui.tsx
index c368f48..6d8c893 100644
--- a/examples/tanstack-router/src/ui.tsx
+++ b/examples/tanstack-router/src/ui.tsx
@@ -1,10 +1,16 @@
import { useState, type FormEvent } from "react";
+import { useAuthClient } from "@monarcode/session-kit/tanstack-router";
+import { getRouteApi } from "@tanstack/react-router";
+
import { authFetch, signInWithPassword } from "./auth";
-import { useAuth, useAuthClient } from "./hooks";
-/** The sign-in form, prefilled with DummyJSON's documented test user. */
-export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
+/**
+ * The sign-in form, prefilled with DummyJSON's documented test user. It
+ * doesn't navigate: a sign-in runs the guards again, and the sign-in page's
+ * guard sends the user on.
+ */
+export function LoginForm() {
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
@@ -18,7 +24,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
String(form.get("username")),
String(form.get("password")),
);
- await onSignedIn();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
} finally {
@@ -61,9 +66,14 @@ const emailOf = (value: unknown) =>
? String(value.email)
: "";
-/** The signed-in user, a request using the access token, and sign-out. */
+const authenticated = getRouteApi("/_authenticated");
+
+/**
+ * The signed-in user, a request using the access token, and sign-out. It
+ * renders under the guarded layout, whose route context holds the session.
+ */
export function Profile() {
- const user = useAuth((state) => state.user);
+ const { user } = authenticated.useRouteContext().session;
const auth = useAuthClient();
const [fromApi, setFromApi] = useState("");
@@ -78,8 +88,8 @@ export function Profile() {
return (
-
Welcome, {user?.firstName}
-
Signed in as {user?.username}
+
Welcome, {user.firstName}
+
Signed in as {user.username}
{fromApi &&
auth/me: {fromApi}
}
-
+
);
}
diff --git a/examples/tanstack-start-spa-effetch/src/api-client.ts b/examples/tanstack-start-spa-effetch/src/api-client.ts
deleted file mode 100644
index 83f289c..0000000
--- a/examples/tanstack-start-spa-effetch/src/api-client.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import * as Fetch from "@monarcode/effetch";
-import { sessionBearer } from "@monarcode/session-kit/effetch";
-import * as Context from "effect/Context";
-import type * as Effect from "effect/Effect";
-import * as Layer from "effect/Layer";
-import * as Schema from "effect/Schema";
-
-import { API_BASE_URL } from "./auth";
-
-/** DummyJSON explains an error in its body: `{ "message": "…" }`. */
-export const ApiErrorBody = Schema.Struct({ message: Schema.String });
-export type ApiErrorBody = Schema.Schema.Type;
-
-const make = Fetch.make({
- baseUrl: API_BASE_URL,
- defaultError: ApiErrorBody,
- // Sends the access token to DummyJSON only. After a 401 it refreshes, then
- // replays a GET or HEAD once. `optional`: a call made while signed out,
- // such as the sign-in itself, goes without a token.
- plugins: [sessionBearer({ baseUrl: API_BASE_URL, optional: true })],
-});
-
-/** The app's API client: effetch's `get`, `post` and the rest, for DummyJSON. */
-export class ApiClient extends Context.Service<
- ApiClient,
- Effect.Success
->()("ApiClient") {}
-
-export const ApiClientLive = Layer.effect(ApiClient, make);
diff --git a/examples/tanstack-start-spa-effetch/src/api.ts b/examples/tanstack-start-spa-effetch/src/api.ts
new file mode 100644
index 0000000..7d465af
--- /dev/null
+++ b/examples/tanstack-start-spa-effetch/src/api.ts
@@ -0,0 +1,33 @@
+import * as Fetch from "@monarcode/effetch";
+import { retry } from "@monarcode/effetch/plugins";
+import { sessionBearer } from "@monarcode/session-kit/effetch";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as HttpClient from "effect/http/HttpClient";
+import * as Layer from "effect/Layer";
+
+import { API_BASE_URL, ApiError } from "./backend";
+
+const make = Fetch.make({
+ baseUrl: API_BASE_URL,
+ defaultError: ApiError,
+ // `retry` resends a GET after a network error or a status such as 503.
+ // `sessionBearer` comes after it, so each attempt reads the current token.
+ // It sends the token to DummyJSON only. After a 401 it refreshes, then
+ // sends a GET or HEAD again once. `optional`: a call made while signed out
+ // goes without a token.
+ plugins: [retry(), sessionBearer({ baseUrl: API_BASE_URL, optional: true })],
+}).pipe(
+ // Effect adds tracing headers to every request, which fail the preflight
+ // of an API that doesn't allow them.
+ Effect.provideService(HttpClient.TracerPropagationEnabled, false),
+);
+
+/** The app's API client: effetch's `get`, `post` and the rest, for DummyJSON. */
+export class ApiClient extends Context.Service<
+ ApiClient,
+ Effect.Success
+>()("ApiClient") {}
+
+/** The API client, over whichever `Auth` is provided. */
+export const ApiClientLive = Layer.effect(ApiClient, make);
diff --git a/examples/tanstack-start-spa-effetch/src/auth.ts b/examples/tanstack-start-spa-effetch/src/auth.ts
index 1bc6a65..3222067 100644
--- a/examples/tanstack-start-spa-effetch/src/auth.ts
+++ b/examples/tanstack-start-spa-effetch/src/auth.ts
@@ -1,84 +1,24 @@
-import * as Fetch from "@monarcode/effetch";
import {
createAuth,
fromAccessToken,
webStorage,
} from "@monarcode/session-kit";
-import { Auth } from "@monarcode/session-kit/effect";
-import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
-import { FetchLive } from "./fetch";
-
-/** DummyJSON's auth API: https://dummyjson.com/docs/auth */
-export const API_BASE_URL = "https://dummyjson.com";
-
-/** One-minute tokens make the early refresh visible after about 30 seconds. */
-export const expiresInMins = 1;
-
-export const SessionTokens = Schema.Struct({
- accessToken: Schema.String,
- refreshToken: Schema.String,
-});
-
-/**
- * DummyJSON's access tokens are JWTs carrying the user, so this app reads the
- * user from the token instead of the login response. A struct drops the
- * claims it doesn't list, such as `exp` and `iat`, which change on every
- * refresh.
- */
-export const SessionUser = Schema.Struct({
- id: Schema.Finite,
- username: Schema.String,
- email: Schema.String,
- firstName: Schema.String,
- lastName: Schema.String,
- image: Schema.String,
-});
-
-// Not the app's API client: its session plugin waits for this refresh.
-const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL });
-
-/**
- * Exchanges the refresh token for new tokens. DummyJSON answers 403 for an
- * invalid or expired refresh token and 401 for a missing one: both mean
- * "sign in again", so succeed with `null`. Other failures fail: the session
- * is kept and the error shows in `state.error`.
- */
-const refreshSession = (refreshToken: string) =>
- Effect.gen(function* () {
- const client = yield* makeRefreshClient;
- return yield* client.post("/auth/refresh", {
- body: { refreshToken, expiresInMins },
- output: SessionTokens,
- });
- }).pipe(
- Effect.catchTag("HttpError", (error) =>
- error.status === 401 || error.status === 403
- ? Effect.succeed(null)
- : Effect.fail(error),
- ),
- Effect.provide(FetchLive),
- );
+import { SessionUser } from "./backend";
+import { refreshSession } from "./refresh";
export const auth = createAuth({
name: "session-kit-example",
user: fromAccessToken(Schema.toStandardSchemaV1(SessionUser)),
storage: webStorage(),
- refresh: ({ refreshToken, signal }) =>
- Effect.runPromise(refreshSession(refreshToken), { signal }),
+ refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal),
});
-// Registered once, so every `Auth` Effect is typed with this client's user.
-declare module "@monarcode/session-kit/effect" {
+// Registered once, so every `Auth` Effect, and the hooks, carry this
+// client's user.
+declare module "@monarcode/session-kit" {
interface Register {
auth: typeof auth;
}
}
-
-/**
- * The client as the `Auth` service, which the API client's `sessionBearer`
- * reads the access token from. It doesn't mount the client: `connectAuth`
- * does, in `router.tsx`.
- */
-export const AuthLive = Auth.layer(auth);
diff --git a/examples/tanstack-start-spa-effetch/src/backend.ts b/examples/tanstack-start-spa-effetch/src/backend.ts
new file mode 100644
index 0000000..b94eef0
--- /dev/null
+++ b/examples/tanstack-start-spa-effetch/src/backend.ts
@@ -0,0 +1,31 @@
+import * as Schema from "effect/Schema";
+
+/** DummyJSON's auth API: https://dummyjson.com/docs/auth */
+export const API_BASE_URL = "https://dummyjson.com";
+
+/** One-minute tokens make the early refresh visible after about 30 seconds. */
+export const expiresInMins = 1;
+
+/**
+ * DummyJSON's access tokens are JWTs carrying the user, so this app reads the
+ * user from the token instead of the login response. A struct drops the
+ * claims it doesn't list, such as `exp` and `iat`, which change on every
+ * refresh.
+ */
+export const SessionUser = Schema.Struct({
+ id: Schema.Finite,
+ username: Schema.String,
+ email: Schema.String,
+ firstName: Schema.String,
+ lastName: Schema.String,
+ image: Schema.String,
+});
+
+export const SessionTokens = Schema.Struct({
+ accessToken: Schema.String,
+ refreshToken: Schema.String,
+});
+
+/** DummyJSON explains an error in its body: `{ "message": "…" }`. */
+export const ApiError = Schema.Struct({ message: Schema.String });
+export type ApiError = Schema.Schema.Type;
diff --git a/examples/tanstack-start-spa-effetch/src/endpoints.ts b/examples/tanstack-start-spa-effetch/src/endpoints.ts
index 4e47240..81fbafc 100644
--- a/examples/tanstack-start-spa-effetch/src/endpoints.ts
+++ b/examples/tanstack-start-spa-effetch/src/endpoints.ts
@@ -1,10 +1,10 @@
import * as Fetch from "@monarcode/effetch";
import * as Schema from "effect/Schema";
-import { SessionTokens } from "./auth";
+import { SessionTokens } from "./backend";
import { api } from "./query";
-/** Signs in with DummyJSON. Sent without a token: nobody is signed in yet. */
+/** Signs in with DummyJSON. Sent without a token, as it's how one is got. */
export const signInMutation = api.mutation(
Fetch.endpoint("POST /auth/login", {
input: Schema.Struct({
@@ -14,6 +14,7 @@ export const signInMutation = api.mutation(
}),
output: SessionTokens,
}),
+ { plugins: { sessionBearer: false } },
);
/** The signed-in user's profile, requested with the access token. */
diff --git a/examples/tanstack-start-spa-effetch/src/error-message.ts b/examples/tanstack-start-spa-effetch/src/error-message.ts
index d659a61..770f77c 100644
--- a/examples/tanstack-start-spa-effetch/src/error-message.ts
+++ b/examples/tanstack-start-spa-effetch/src/error-message.ts
@@ -4,10 +4,10 @@ import * as Cause from "effect/Cause";
import * as Match from "effect/Match";
import * as Option from "effect/Option";
-import type { ApiErrorBody } from "./api-client";
+import type { ApiError } from "./backend";
type ApiCallError =
- | HttpError.With
+ | HttpError.With
| NetworkError
| DecodeError
| AuthFailure;
diff --git a/examples/tanstack-start-spa-effetch/src/fetch.ts b/examples/tanstack-start-spa-effetch/src/fetch.ts
deleted file mode 100644
index 7449f61..0000000
--- a/examples/tanstack-start-spa-effetch/src/fetch.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import * as FetchHttpClient from "effect/http/FetchHttpClient";
-import * as HttpClient from "effect/http/HttpClient";
-import * as Layer from "effect/Layer";
-
-/**
- * `fetch`, without the tracing headers Effect adds to every request: from a
- * browser, they fail the preflight of an API that doesn't allow them.
- */
-export const FetchLive = Layer.merge(
- FetchHttpClient.layer,
- Layer.succeed(HttpClient.TracerPropagationEnabled, false),
-);
diff --git a/examples/tanstack-start-spa-effetch/src/hooks.ts b/examples/tanstack-start-spa-effetch/src/hooks.ts
deleted file mode 100644
index a6294ae..0000000
--- a/examples/tanstack-start-spa-effetch/src/hooks.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-import { useRouterAuth } from "@monarcode/session-kit/tanstack-router";
-
-// Reads the client from Router context, so no provider is needed.
-export const { useAuth, useAuthClient } = createAuthHooks({
- useClient: useRouterAuth,
-});
diff --git a/examples/tanstack-start-spa-effetch/src/layer.ts b/examples/tanstack-start-spa-effetch/src/layer.ts
new file mode 100644
index 0000000..cc97ac2
--- /dev/null
+++ b/examples/tanstack-start-spa-effetch/src/layer.ts
@@ -0,0 +1,10 @@
+import { Auth } from "@monarcode/session-kit/effect";
+
+import { auth } from "./auth";
+
+/**
+ * The client as the `Auth` service, which the API client's `sessionBearer`
+ * reads the access token from. It doesn't mount the client: `connectAuth`
+ * does, in `router.tsx`.
+ */
+export const AuthLive = Auth.layer(auth);
diff --git a/examples/tanstack-start-spa-effetch/src/query.ts b/examples/tanstack-start-spa-effetch/src/query.ts
index f1ae09e..3d0972b 100644
--- a/examples/tanstack-start-spa-effetch/src/query.ts
+++ b/examples/tanstack-start-spa-effetch/src/query.ts
@@ -2,7 +2,8 @@ import { QueryClient } from "@monarcode/effetch-query";
import { endpoints } from "@monarcode/effetch-query/effetch";
import type * as ManagedRuntime from "effect/ManagedRuntime";
-import { ApiClient, ApiErrorBody } from "./api-client";
+import { ApiClient } from "./api";
+import { ApiError } from "./backend";
import { appRuntime, type AppRuntime } from "./runtime";
declare module "@monarcode/effetch-query" {
@@ -12,7 +13,7 @@ declare module "@monarcode/effetch-query" {
}
/** Turns endpoints of the API client into queries and mutations. */
-export const api = endpoints(ApiClient, { defaultError: ApiErrorBody });
+export const api = endpoints(ApiClient, { defaultError: ApiError });
/**
* Makes the query cache, which runs queries and mutations with `appRuntime`'s
diff --git a/examples/tanstack-start-spa-effetch/src/refresh.ts b/examples/tanstack-start-spa-effetch/src/refresh.ts
new file mode 100644
index 0000000..7ee2a68
--- /dev/null
+++ b/examples/tanstack-start-spa-effetch/src/refresh.ts
@@ -0,0 +1,37 @@
+import * as 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, expiresInMins, SessionTokens } from "./backend";
+
+// 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.
+ Effect.provideService(HttpClient.TracerPropagationEnabled, false),
+);
+
+/**
+ * Exchanges the refresh token for new tokens. DummyJSON answers 403 for an
+ * invalid or expired refresh token and 401 for a missing one: both mean
+ * "sign in again", so it resolves `null`. Other failures reject, so the
+ * session is kept and the error shows in `state.error`.
+ */
+export const refreshSession = (refreshToken: string, signal: AbortSignal) =>
+ Effect.runPromise(
+ Effect.gen(function* () {
+ const client = yield* makeRefreshClient;
+ return yield* client.post("/auth/refresh", {
+ body: { refreshToken, expiresInMins },
+ output: SessionTokens,
+ });
+ }).pipe(
+ Effect.catchTag("HttpError", (error) =>
+ error.status === 401 || error.status === 403
+ ? Effect.succeed(null)
+ : Effect.fail(error),
+ ),
+ Effect.provide(FetchHttpClient.layer),
+ ),
+ { signal },
+ );
diff --git a/examples/tanstack-start-spa-effetch/src/routes/__root.tsx b/examples/tanstack-start-spa-effetch/src/routes/__root.tsx
index 41ed42d..6d3a957 100644
--- a/examples/tanstack-start-spa-effetch/src/routes/__root.tsx
+++ b/examples/tanstack-start-spa-effetch/src/routes/__root.tsx
@@ -2,6 +2,7 @@
import type { ReactNode } from "react";
import { QueryProvider } from "@monarcode/effetch-query/react";
+import { useAuth } from "@monarcode/session-kit/tanstack-router";
import {
createRootRouteWithContext,
HeadContent,
@@ -10,7 +11,6 @@ import {
} from "@tanstack/react-router";
import type { auth } from "../auth";
-import { useAuth } from "../hooks";
import { makeQueryClient } from "../query";
export const Route = createRootRouteWithContext<{ auth: typeof auth }>()({
@@ -27,9 +27,9 @@ export const Route = createRootRouteWithContext<{ auth: typeof auth }>()({
/** A query cache for each session, so no account sees another's data. */
function Root() {
- const sessionId = useAuth((state) => state.sessionId);
+ const account = useAuth((state) => state.sessionId ?? "signed-out");
return (
-
+
);
diff --git a/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx b/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx
index eef8802..11e5f0c 100644
--- a/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx
+++ b/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx
@@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
- requireSession(context.auth, { location, loginPath: "/login" }),
+ requireSession(context.auth, { location }),
errorComponent: ({ error }) => ,
component: () => } />,
});
diff --git a/examples/tanstack-start-spa-effetch/src/routes/login.tsx b/examples/tanstack-start-spa-effetch/src/routes/login.tsx
index 06976a2..2806f36 100644
--- a/examples/tanstack-start-spa-effetch/src/routes/login.tsx
+++ b/examples/tanstack-start-spa-effetch/src/routes/login.tsx
@@ -1,6 +1,6 @@
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router";
-import { createFileRoute, useRouter } from "@tanstack/react-router";
+import { createFileRoute } from "@tanstack/react-router";
import { LoginForm } from "../ui";
@@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({
validateSearch: (search: Record) => ({
redirectTo: safeReturnTo(search.redirectTo),
}),
+ // Runs again after a sign-in, which runs the guards again.
beforeLoad: ({ context, search }) =>
redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
- component: Login,
+ component: LoginForm,
});
-
-function Login() {
- const router = useRouter();
- const { redirectTo } = Route.useSearch();
- return (
- router.navigate({ href: redirectTo, replace: true })}
- />
- );
-}
diff --git a/examples/tanstack-start-spa-effetch/src/runtime.ts b/examples/tanstack-start-spa-effetch/src/runtime.ts
index 08890bf..e5fa748 100644
--- a/examples/tanstack-start-spa-effetch/src/runtime.ts
+++ b/examples/tanstack-start-spa-effetch/src/runtime.ts
@@ -1,17 +1,18 @@
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
-import { ApiClientLive } from "./api-client";
-import { AuthLive } from "./auth";
-import { FetchLive } from "./fetch";
+import { ApiClientLive } from "./api";
+import { AuthLive } from "./layer";
/**
- * The composition root: the app's services and what they depend on. A new
- * service is added here.
+ * The composition root: the API client, the session, and the
+ * `FetchHttpClient` effetch sends with, each made once. A new service is
+ * added here.
*/
const AppLayer = ApiClientLive.pipe(
Layer.provideMerge(AuthLive),
- Layer.provide(FetchLive),
+ Layer.provide(FetchHttpClient.layer),
);
/** One runtime for the app's lifetime. */
diff --git a/examples/tanstack-start-spa-effetch/src/ui.tsx b/examples/tanstack-start-spa-effetch/src/ui.tsx
index 07b81d5..732f9da 100644
--- a/examples/tanstack-start-spa-effetch/src/ui.tsx
+++ b/examples/tanstack-start-spa-effetch/src/ui.tsx
@@ -1,16 +1,21 @@
import { useState, type FormEvent } from "react";
import { useMutation, useQuery } from "@monarcode/effetch-query/react";
+import { useAuthClient } from "@monarcode/session-kit/tanstack-router";
+import { getRouteApi } from "@tanstack/react-router";
import * as Exit from "effect/Exit";
import * as AsyncResult from "effect/reactivity/AsyncResult";
-import { expiresInMins } from "./auth";
+import { expiresInMins } from "./backend";
import { profileQuery, signInMutation } from "./endpoints";
import { apiErrorMessage } from "./error-message";
-import { useAuth, useAuthClient } from "./hooks";
-/** The sign-in form, prefilled with DummyJSON's documented test user. */
-export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
+/**
+ * The sign-in form, prefilled with DummyJSON's documented test user. It
+ * doesn't navigate: a sign-in runs the guards again, and the sign-in page's
+ * guard sends the user on.
+ */
+export function LoginForm() {
const auth = useAuthClient();
const signIn = useMutation(signInMutation);
const [error, setError] = useState("");
@@ -33,7 +38,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
try {
// The tokens carry the user, so they are all the client needs.
await auth.signIn(exit.value);
- await onSignedIn();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
}
@@ -81,19 +85,26 @@ function ProfileEmail() {
});
}
-/** The signed-in user, a request using the access token, and sign-out. */
+const authenticated = getRouteApi("/_authenticated");
+
+/**
+ * The signed-in user, a request using the access token, and sign-out. It
+ * renders under the guarded layout, whose route context holds the session.
+ */
export function Profile() {
- const user = useAuth((state) => state.user);
+ const { user } = authenticated.useRouteContext().session;
const auth = useAuthClient();
const [showEmail, setShowEmail] = useState(false);
return (
-
Welcome, {user?.firstName}
-
Signed in as {user?.username}
+
Welcome, {user.firstName}
+
Signed in as {user.username}
{showEmail && }
-
+
);
}
diff --git a/examples/tanstack-start-spa/src/auth.ts b/examples/tanstack-start-spa/src/auth.ts
index f509524..aeab929 100644
--- a/examples/tanstack-start-spa/src/auth.ts
+++ b/examples/tanstack-start-spa/src/auth.ts
@@ -38,7 +38,8 @@ export const auth = createAuth({
/** Signs in with DummyJSON and saves the tokens, which carry the user. */
export async function signInWithPassword(username: string, password: string) {
- await auth.signIn(tokens.parse(await login(username, password)));
+ const response = await login(username, password);
+ await auth.signIn(tokens.parse(response));
}
/**
@@ -88,4 +89,4 @@ async function login(username: string, password: string): Promise {
* Sends requests to DummyJSON with the access token. After a 401 it
* refreshes, then replays a GET or HEAD once.
*/
-export const authFetch = createAuthFetch(auth, `${API}/`);
+export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });
diff --git a/examples/tanstack-start-spa/src/hooks.ts b/examples/tanstack-start-spa/src/hooks.ts
deleted file mode 100644
index a6294ae..0000000
--- a/examples/tanstack-start-spa/src/hooks.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-import { useRouterAuth } from "@monarcode/session-kit/tanstack-router";
-
-// Reads the client from Router context, so no provider is needed.
-export const { useAuth, useAuthClient } = createAuthHooks({
- useClient: useRouterAuth,
-});
diff --git a/examples/tanstack-start-spa/src/routes/_authenticated.tsx b/examples/tanstack-start-spa/src/routes/_authenticated.tsx
index eef8802..11e5f0c 100644
--- a/examples/tanstack-start-spa/src/routes/_authenticated.tsx
+++ b/examples/tanstack-start-spa/src/routes/_authenticated.tsx
@@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
- requireSession(context.auth, { location, loginPath: "/login" }),
+ requireSession(context.auth, { location }),
errorComponent: ({ error }) => ,
component: () => } />,
});
diff --git a/examples/tanstack-start-spa/src/routes/login.tsx b/examples/tanstack-start-spa/src/routes/login.tsx
index 06976a2..2806f36 100644
--- a/examples/tanstack-start-spa/src/routes/login.tsx
+++ b/examples/tanstack-start-spa/src/routes/login.tsx
@@ -1,6 +1,6 @@
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router";
-import { createFileRoute, useRouter } from "@tanstack/react-router";
+import { createFileRoute } from "@tanstack/react-router";
import { LoginForm } from "../ui";
@@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({
validateSearch: (search: Record) => ({
redirectTo: safeReturnTo(search.redirectTo),
}),
+ // Runs again after a sign-in, which runs the guards again.
beforeLoad: ({ context, search }) =>
redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
- component: Login,
+ component: LoginForm,
});
-
-function Login() {
- const router = useRouter();
- const { redirectTo } = Route.useSearch();
- return (
- router.navigate({ href: redirectTo, replace: true })}
- />
- );
-}
diff --git a/examples/tanstack-start-spa/src/ui.tsx b/examples/tanstack-start-spa/src/ui.tsx
index c368f48..6d8c893 100644
--- a/examples/tanstack-start-spa/src/ui.tsx
+++ b/examples/tanstack-start-spa/src/ui.tsx
@@ -1,10 +1,16 @@
import { useState, type FormEvent } from "react";
+import { useAuthClient } from "@monarcode/session-kit/tanstack-router";
+import { getRouteApi } from "@tanstack/react-router";
+
import { authFetch, signInWithPassword } from "./auth";
-import { useAuth, useAuthClient } from "./hooks";
-/** The sign-in form, prefilled with DummyJSON's documented test user. */
-export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
+/**
+ * The sign-in form, prefilled with DummyJSON's documented test user. It
+ * doesn't navigate: a sign-in runs the guards again, and the sign-in page's
+ * guard sends the user on.
+ */
+export function LoginForm() {
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
@@ -18,7 +24,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
String(form.get("username")),
String(form.get("password")),
);
- await onSignedIn();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not sign in");
} finally {
@@ -61,9 +66,14 @@ const emailOf = (value: unknown) =>
? String(value.email)
: "";
-/** The signed-in user, a request using the access token, and sign-out. */
+const authenticated = getRouteApi("/_authenticated");
+
+/**
+ * The signed-in user, a request using the access token, and sign-out. It
+ * renders under the guarded layout, whose route context holds the session.
+ */
export function Profile() {
- const user = useAuth((state) => state.user);
+ const { user } = authenticated.useRouteContext().session;
const auth = useAuthClient();
const [fromApi, setFromApi] = useState("");
@@ -78,8 +88,8 @@ export function Profile() {
return (
-
Welcome, {user?.firstName}
-
Signed in as {user?.username}
+
Welcome, {user.firstName}
+
Signed in as {user.username}
{fromApi &&
auth/me: {fromApi}
}
-
+
);
}
diff --git a/examples/tanstack-start-ssr/src/auth/client.ts b/examples/tanstack-start-ssr/src/auth/client.ts
index b3bb1a8..0417a9a 100644
--- a/examples/tanstack-start-ssr/src/auth/client.ts
+++ b/examples/tanstack-start-ssr/src/auth/client.ts
@@ -1,31 +1,22 @@
import { createMirrorAuth } from "@monarcode/session-kit";
-import {
- getCredentialsFn,
- getSessionFn,
- renewCredentialsFn,
- signInFn,
- signOutFn,
-} from "./functions";
+import { getSessionFn, signInFn } from "./functions";
/**
* The client the routes and components use. It mirrors the session the
* server keeps in its cookie: `loadSession` fills it on the server, and
- * `sessionHydration` carries that to the browser. Create one per router: on
- * the server, that is one per request.
+ * `connectSession` carries that to the browser. It signs out and gets the
+ * access token through the session route in `routes/api/session.ts`. Create
+ * one per router: on the server, that is one per request.
*/
export function createAppAuth() {
return createMirrorAuth({
name: "session-kit-example",
session: null,
+ endpoint: "/api/session",
revalidate: () => getSessionFn(),
signIn: (data: { username: string; password: string }) =>
signInFn({ data }),
- signOut: () => signOutFn(),
- credentials: {
- get: () => getCredentialsFn(),
- renew: (rejected) => renewCredentialsFn({ data: rejected }),
- },
});
}
diff --git a/examples/tanstack-start-ssr/src/auth/functions.ts b/examples/tanstack-start-ssr/src/auth/functions.ts
index 8171c47..e48b1ea 100644
--- a/examples/tanstack-start-ssr/src/auth/functions.ts
+++ b/examples/tanstack-start-ssr/src/auth/functions.ts
@@ -1,60 +1,33 @@
-import { startJar } from "@monarcode/session-kit/tanstack-start/server";
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
-import { API } from "./api";
import { login } from "./backend";
-import { serverAuth } from "./server";
+import { apiFetch, session } from "./server";
// Each handler runs on the server; Start's compiler replaces it with a fetch
-// in the browser, and leaves `startJar` and `serverAuth` out of that bundle.
+// in the browser, and leaves `session` out of that bundle.
-/** Who is signed in, from the cookie. Holds no tokens. */
+/**
+ * Who is signed in, from the cookie. Holds no tokens. The client's
+ * `revalidate`: `loadSession` calls it while Start renders on the server,
+ * where the client can't call the session route.
+ */
export const getSessionFn = createServerFn().handler(() =>
- serverAuth.getSession(startJar()),
+ session.getSession(),
);
/** Signs in with DummyJSON on the server and sets the cookie. */
export const signInFn = createServerFn({ method: "POST" })
.validator(z.object({ username: z.string(), password: z.string() }))
- .handler(async ({ data }) =>
- serverAuth.signIn(startJar(), await login(data.username, data.password)),
- );
-
-/** Clears the cookie. */
-export const signOutFn = createServerFn({ method: "POST" }).handler(() =>
- serverAuth.signOut(startJar()),
-);
-
-/** The access token for the browser's own requests, never the refresh token. */
-export const getCredentialsFn = createServerFn({ method: "POST" }).handler(() =>
- serverAuth.clientCredentials.get(startJar()),
-);
-
-/** New access after DummyJSON rejected the browser's token. */
-export const renewCredentialsFn = createServerFn({ method: "POST" })
- .validator(z.object({ sessionId: z.string(), accessToken: z.string() }))
- .handler(({ data }) => serverAuth.clientCredentials.renew(startJar(), data));
+ .handler(async ({ data }) => {
+ const tokens = await login(data.username, data.password);
+ return session.signIn(tokens);
+ });
/** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */
export const getProfileFn = createServerFn().handler(async () => {
- const jar = startJar();
- const credentials = await serverAuth.credentials.get(jar);
- if (!credentials) return { email: "Signed out" };
- let response = await me(credentials.accessToken);
- if (response.status === 401) {
- // Refreshes once, then tries again.
- const renewed = await serverAuth.credentials.renew(jar, credentials);
- if (!renewed) return { email: "Signed out" };
- response = await me(renewed.accessToken);
- }
+ const response = await apiFetch("auth/me");
if (!response.ok) return { email: `HTTP ${response.status}` };
const profile = z.object({ email: z.string() }).parse(await response.json());
return { email: profile.email };
});
-
-function me(accessToken: string) {
- return fetch(`${API}/auth/me`, {
- headers: { Authorization: `Bearer ${accessToken}` },
- });
-}
diff --git a/examples/tanstack-start-ssr/src/auth/server.ts b/examples/tanstack-start-ssr/src/auth/server.ts
index e6a21a0..c113df4 100644
--- a/examples/tanstack-start-ssr/src/auth/server.ts
+++ b/examples/tanstack-start-ssr/src/auth/server.ts
@@ -1,7 +1,10 @@
// Holds the secret and the tokens: Start refuses to bundle it for the browser.
import "@tanstack/react-start/server-only";
+import { createAuthFetch } from "@monarcode/session-kit/http";
import { createServerAuth } from "@monarcode/session-kit/server";
+import { startAuth } from "@monarcode/session-kit/tanstack-start/server";
+import { API } from "./api";
import { refresh, userSchema } from "./backend";
/**
@@ -19,7 +22,7 @@ function sessionSecret(): string {
/**
* Keeps both tokens and the user in an encrypted, httpOnly cookie. With
* `clientCredentials`, the browser can ask for the access token too, through
- * the server functions in `functions.ts`; the refresh token stays here.
+ * the session route in `routes/api/session.ts`; the refresh token stays here.
*/
export const serverAuth = createServerAuth({
name: "session-kit-example",
@@ -30,3 +33,15 @@ export const serverAuth = createServerAuth({
// `vite dev` serves plain http; Safari drops Secure cookies there.
cookie: { secure: !import.meta.env.DEV },
});
+
+/**
+ * The session of the request Start is handling: each call finds it, so one
+ * object serves every request.
+ */
+export const session = startAuth(serverAuth);
+
+/**
+ * Calls DummyJSON with the cookie's access token. After a 401, it renews the
+ * token, saves it in the cookie, and sends a `GET` again.
+ */
+export const apiFetch = createAuthFetch(session, { baseUrl: `${API}/` });
diff --git a/examples/tanstack-start-ssr/src/hooks.ts b/examples/tanstack-start-ssr/src/hooks.ts
deleted file mode 100644
index a6294ae..0000000
--- a/examples/tanstack-start-ssr/src/hooks.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { createAuthHooks } from "@monarcode/session-kit/react";
-import { useRouterAuth } from "@monarcode/session-kit/tanstack-router";
-
-// Reads the client from Router context, so no provider is needed.
-export const { useAuth, useAuthClient } = createAuthHooks({
- useClient: useRouterAuth,
-});
diff --git a/examples/tanstack-start-ssr/src/router.tsx b/examples/tanstack-start-ssr/src/router.tsx
index 777d5bb..66fcbf5 100644
--- a/examples/tanstack-start-ssr/src/router.tsx
+++ b/examples/tanstack-start-ssr/src/router.tsx
@@ -1,5 +1,4 @@
-import { connectAuth } from "@monarcode/session-kit/tanstack-router";
-import { sessionHydration } from "@monarcode/session-kit/tanstack-start";
+import { connectSession } from "@monarcode/session-kit/tanstack-start";
import { createRouter } from "@tanstack/react-router";
import { createAppAuth } from "./auth/client";
@@ -13,11 +12,10 @@ export function getRouter() {
context: { auth },
defaultPendingComponent: Pending,
scrollRestoration: true,
- // Sends the session the server read to the browser, without tokens.
- ...sessionHydration(auth),
});
- // Re-runs guards when the session changes. Does nothing on the server.
- connectAuth(router);
+ // Sends the session the server read to the browser, without tokens, and
+ // re-runs guards when it changes there.
+ connectSession(router);
return router;
}
diff --git a/examples/tanstack-start-ssr/src/routes/_authenticated.tsx b/examples/tanstack-start-ssr/src/routes/_authenticated.tsx
index eef8802..11e5f0c 100644
--- a/examples/tanstack-start-ssr/src/routes/_authenticated.tsx
+++ b/examples/tanstack-start-ssr/src/routes/_authenticated.tsx
@@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
- requireSession(context.auth, { location, loginPath: "/login" }),
+ requireSession(context.auth, { location }),
errorComponent: ({ error }) => ,
component: () => } />,
});
diff --git a/examples/tanstack-start-ssr/src/routes/api/session.ts b/examples/tanstack-start-ssr/src/routes/api/session.ts
new file mode 100644
index 0000000..7dd014e
--- /dev/null
+++ b/examples/tanstack-start-ssr/src/routes/api/session.ts
@@ -0,0 +1,13 @@
+import { sessionRoute } from "@monarcode/session-kit/tanstack-start/server";
+import { createFileRoute } from "@tanstack/react-router";
+
+import { serverAuth } from "../../auth/server";
+
+/**
+ * The session route the browser's client calls to sign out and get the
+ * access token. It answers this site's own pages only. Start keeps
+ * `server.handlers` out of the browser bundle, `serverAuth` included.
+ */
+export const Route = createFileRoute("/api/session")({
+ server: { handlers: sessionRoute(serverAuth) },
+});
diff --git a/examples/tanstack-start-ssr/src/routes/login.tsx b/examples/tanstack-start-ssr/src/routes/login.tsx
index 06976a2..2806f36 100644
--- a/examples/tanstack-start-ssr/src/routes/login.tsx
+++ b/examples/tanstack-start-ssr/src/routes/login.tsx
@@ -1,6 +1,6 @@
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router";
-import { createFileRoute, useRouter } from "@tanstack/react-router";
+import { createFileRoute } from "@tanstack/react-router";
import { LoginForm } from "../ui";
@@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({
validateSearch: (search: Record) => ({
redirectTo: safeReturnTo(search.redirectTo),
}),
+ // Runs again after a sign-in, which runs the guards again.
beforeLoad: ({ context, search }) =>
redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
- component: Login,
+ component: LoginForm,
});
-
-function Login() {
- const router = useRouter();
- const { redirectTo } = Route.useSearch();
- return (
- router.navigate({ href: redirectTo, replace: true })}
- />
- );
-}
diff --git a/examples/tanstack-start-ssr/src/start.ts b/examples/tanstack-start-ssr/src/start.ts
index 05942ed..50a67f1 100644
--- a/examples/tanstack-start-ssr/src/start.ts
+++ b/examples/tanstack-start-ssr/src/start.ts
@@ -1,27 +1,21 @@
-import { startJar } from "@monarcode/session-kit/tanstack-start/server";
+import { refreshSession } from "@monarcode/session-kit/tanstack-start/server";
import {
createCsrfMiddleware,
createMiddleware,
createStart,
} from "@tanstack/react-start";
-import { setResponseHeader } from "@tanstack/react-start/server";
import { serverAuth } from "./auth/server";
/**
* Refreshes access that is about to expire before routes and server
- * functions read it, while the response can still set the cookie. A failed
- * refresh is left for the route: `loadSession` then rejects, and the root
- * route's error component offers a retry.
+ * functions read it, while the response can still set the cookie. Start
+ * keeps what's inside `.server()` out of the browser bundle, `serverAuth`
+ * included.
*/
const sessionMiddleware = createMiddleware({ type: "request" }).server(
- async ({ next }) => {
- // Every page and server function here depends on who is signed in.
- setResponseHeader("Cache-Control", "private, no-store");
- // The example's tokens live a minute: refresh in their last 15 seconds.
- await serverAuth.refreshIfDue(startJar(), { within: 15 }).catch(() => {});
- return next();
- },
+ // The example's tokens live a minute: refresh in their last 15 seconds.
+ refreshSession(serverAuth, { within: 15 }),
);
export const startInstance = createStart(() => ({
diff --git a/examples/tanstack-start-ssr/src/ui.tsx b/examples/tanstack-start-ssr/src/ui.tsx
index 6a7f602..36f3de3 100644
--- a/examples/tanstack-start-ssr/src/ui.tsx
+++ b/examples/tanstack-start-ssr/src/ui.tsx
@@ -1,13 +1,17 @@
import { useMemo, useState, type FormEvent } from "react";
import { createAuthFetch } from "@monarcode/session-kit/http";
+import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router";
import { useRouter } from "@tanstack/react-router";
import { API } from "./auth/api";
-import { useAuth, useAuthClient } from "./hooks";
-/** The sign-in form, prefilled with DummyJSON's documented test user. */
-export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
+/**
+ * The sign-in form, prefilled with DummyJSON's documented test user. It
+ * doesn't navigate: a sign-in runs the guards again, and the sign-in page's
+ * guard sends the user on.
+ */
+export function LoginForm() {
const auth = useAuthClient();
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
@@ -23,13 +27,9 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) {
username: String(form.get("username")),
password: String(form.get("password")),
});
- await onSignedIn();
} catch (cause) {
// The server function's own message, such as a wrong password.
- const reason = cause instanceof Error ? cause.cause : undefined;
- setError(
- reason instanceof Error ? reason.message : "Could not sign in",
- );
+ setError(cause instanceof Error ? cause.message : "Could not sign in");
} finally {
setPending(false);
}
@@ -78,7 +78,10 @@ export function Profile({ fromServer }: { fromServer: string }) {
const user = useAuth((state) => state.user);
const auth = useAuthClient();
// The browser's requests get the access token from the server, in memory.
- const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]);
+ const authFetch = useMemo(
+ () => createAuthFetch(auth, { baseUrl: `${API}/` }),
+ [auth],
+ );
const [fromBrowser, setFromBrowser] = useState("");
async function loadProfile() {
@@ -105,7 +108,9 @@ export function Profile({ fromServer }: { fromServer: string }) {
Load profile in the browser
{fromBrowser &&
@@ -101,10 +109,7 @@ function Private() {
/** Signing in changes the state, which renders this again and redirects. */
function Login() {
- const signedIn = useAuth(
- (state) =>
- state.status === "authenticated" || state.status === "refreshing",
- );
+ const signedIn = useAuth(isSignedIn);
const [search] = useSearchParams();
if (signedIn)
return ;
@@ -128,9 +133,10 @@ createRoot(document.getElementById("root")!).render(
```
`SessionOutlet` shows `pending` while the saved session is restored, sends
-signed-out users to `loginPath` with `redirectTo` set to where they were
-going, and renders `unavailable` after a failed refresh. Without
-`unavailable`, the error is thrown to the nearest error boundary.
+signed-out users to `loginPath` (`/login` unless you pass another) with
+`redirectTo` set to where they were going, and renders `unavailable` after a
+failed refresh. Without `unavailable`, the error is thrown to the nearest
+error boundary.
`safeReturnTo` accepts only same-origin paths and returns `/` for anything
else, including the sign-in page itself, so a stale `redirectTo` can't loop.
@@ -141,28 +147,21 @@ A complete app is in
## Data mode
In data mode, loaders run before a route renders, so the guard goes there. A
-private route's data is never fetched for a signed-out user:
+signed-out user is redirected before a private route renders:
```tsx title="src/router.tsx"
-import {
- createBrowserRouter,
- Outlet,
- useNavigate,
- useRouteError,
- useSearchParams,
-} from "react-router";
+import { createBrowserRouter, Outlet, useRouteError } from "react-router";
-import { safeReturnTo } from "@monarcode/session-kit";
+import { useAuthClient } from "@monarcode/session-kit/react";
import {
- redirectIfSignedIn,
- requireSession,
+ redirectIfSignedInLoader,
+ requireSessionLoader,
SessionOutlet,
useAuthRevalidation,
} from "@monarcode/session-kit/react-router";
import { auth } from "./auth.js";
import { Home } from "./home.js";
-import { useAuthClient } from "./hooks.js";
import { SignIn } from "./sign-in.js";
/** Runs the loaders again when auth changes, and with them the guards. */
@@ -171,18 +170,6 @@ function Root() {
return ;
}
-function Login() {
- const navigate = useNavigate();
- const [search] = useSearchParams();
- return (
-
- navigate(safeReturnTo(search.get("redirectTo")), { replace: true })
- }
- />
- );
-}
-
/** Shown after a failed refresh; a repeated failure shows here again. */
function SessionError() {
const error = useRouteError();
@@ -202,25 +189,13 @@ export const router = createBrowserRouter([
children: [
{
path: "/login",
- loader: async ({ request }) => {
- const redirectTo = new URL(request.url).searchParams.get(
- "redirectTo",
- );
- await redirectIfSignedIn(auth, { redirectTo });
- return null;
- },
- element: ,
+ loader: redirectIfSignedInLoader(auth),
+ element: ,
},
{
- loader: ({ request }) =>
- requireSession(auth, { request, loginPath: "/login" }),
+ loader: requireSessionLoader(auth),
errorElement: ,
- element: (
- Checking session…}
- />
- ),
+ element: Checking session…} />,
children: [{ index: true, element: }],
},
],
@@ -232,14 +207,21 @@ Then render the router inside the provider, in `src/main.tsx`:
```tsx
import { StrictMode } from "react";
-import { RouterProvider } from "react-router";
+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 { AuthProvider } from "./hooks.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(
@@ -251,10 +233,13 @@ createRoot(document.getElementById("root")!).render(
Three pieces work together:
-- **`requireSession`** redirects signed-out users to `loginPath` with
- `redirectTo`, and returns `{ session }` as the route's loader data. A failed
- refresh is rethrown for the route's error element instead: the user is still
- signed in.
+- **`requireSessionLoader(auth)`** is the route's loader. It redirects
+ signed-out users to `/login` with `redirectTo`, and returns `{ session }`
+ as the route's loader data. Pass `{ loginPath }` for another sign-in page.
+ A failed refresh is rethrown for the route's error element instead,
+ because the user is still signed in. A loader that does more calls
+ `requireSession` instead, as [Guards in loaders](#guards-in-loaders)
+ shows.
- **`useAuthRevalidation`** runs the loaders again after a sign-in, a
sign-out, an account switch, or a profile update, so the guards run again.
Call it once, in the root route.
@@ -267,9 +252,11 @@ A complete app is in [`examples/react-router-data`](https://github.com/monarcode
## Framework mode with `ssr: false`
-Framework mode without a server is data mode with route modules: the guards
+Framework mode without a server is data mode with route modules. The guards
are the same, in `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.
Turn server rendering off:
@@ -286,10 +273,17 @@ Provide the client, and watch for auth changes, in the root route:
import type { ReactNode } from "react";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
+import { AuthProvider } from "@monarcode/session-kit/react";
import { useAuthRevalidation } from "@monarcode/session-kit/react-router";
import { auth } from "./auth.js";
-import { AuthProvider } from "./hooks.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 (
@@ -333,22 +327,18 @@ Guard a layout route, and nest the private routes under it:
```tsx title="app/routes/protected.tsx"
import { useRouteError } from "react-router";
+import { useAuthClient } from "@monarcode/session-kit/react";
import {
- requireSession,
+ requireSessionLoader,
SessionOutlet,
} from "@monarcode/session-kit/react-router";
import { auth } from "../auth.js";
-import { useAuthClient } from "../hooks.js";
-export function clientLoader({ request }: { request: Request }) {
- return requireSession(auth, { request, loginPath: "/login" });
-}
+export const clientLoader = requireSessionLoader(auth);
export default function Protected() {
- return (
- Checking session…} />
- );
+ return Checking session…} />;
}
/** Shown after a failed refresh; a repeated failure shows here again. */
@@ -364,34 +354,18 @@ export function ErrorBoundary() {
}
```
-Add the sign-in route, which sends signed-in users on to `redirectTo`:
+Add the sign-in route, which sends signed-in users on to `redirectTo`. Its
+loader runs again after a sign-in, so the form doesn't navigate:
```tsx title="app/routes/login.tsx"
-import { useNavigate, useSearchParams } from "react-router";
-
-import { safeReturnTo } from "@monarcode/session-kit";
-import { redirectIfSignedIn } from "@monarcode/session-kit/react-router";
+import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router";
import { auth } from "../auth.js";
import { SignIn } from "../sign-in.js";
-export async function clientLoader({ request }: { request: Request }) {
- const redirectTo = new URL(request.url).searchParams.get("redirectTo");
- await redirectIfSignedIn(auth, { redirectTo });
- return null;
-}
+export const clientLoader = redirectIfSignedInLoader(auth);
-export default function Login() {
- const navigate = useNavigate();
- const [search] = useSearchParams();
- return (
-
- navigate(safeReturnTo(search.get("redirectTo")), { replace: true })
- }
- />
- );
-}
+export default SignIn;
```
In `app/routes.ts`, nest the routes the layout protects:
@@ -419,6 +393,54 @@ the root route starts nothing, and the browser restores the session.
A complete app is in
[`examples/react-router-framework-spa`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-spa).
+## 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 only a signed-in user may
+ 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}.
+
+ );
+}
+```
+
+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
@@ -426,10 +448,9 @@ 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";
-import { useAuth } from "./hooks.js";
-
/** The guarded route's element: `element: `. */
export function Dashboard() {
// From state, not loader data: this stays mounted through a sign-out.
@@ -441,7 +462,7 @@ export function Dashboard() {
{/* Keyed by session, so one account's choices never show for the next. */}
- Checking session…} />
+ Checking session…} />
);
@@ -463,10 +484,15 @@ Three things follow from where `SessionOutlet` sits:
## Things to know
-- **A router `basename`.** Pass the same `basename` to `requireSession`, so
- `redirectTo` leaves it out. Redirects add it again.
-- **A failed refresh is not a redirect.** In declarative mode it renders
- `unavailable`. In data and framework mode, `requireSession` rethrows it for
+- **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.** In declarative mode,
+ `SessionOutlet` renders `unavailable`, or throws to the nearest error
+ boundary without it. In data and framework mode, the guard rethrows it for
the route's error element, which can offer `auth.retry()`.
- **Locked sessions.** [Locking](/docs/client/locking) is for native apps, so
the guards treat a locked session as signed out.
@@ -476,7 +502,9 @@ Three things follow from where `SessionOutlet` sits:
## Next steps
- [Call your API](/docs/getting-started#5-call-your-api) with `authFetch`, as
- in Getting started. It works unchanged with the router.
+ in Getting started, or with
+ [ky, axios or openapi-fetch](/docs/client/other-http-clients). It works
+ unchanged with the router.
- [Using the client](/docs/client): updating the user, signing out, and the
client's other methods.
- [Effect and effetch](/docs/effect): the same client as an Effect service.
diff --git a/site/content/docs/(latest)/setups/tanstack-router.mdx b/site/content/docs/(latest)/setups/tanstack-router.mdx
index 15b2cde..759ffcc 100644
--- a/site/content/docs/(latest)/setups/tanstack-router.mdx
+++ b/site/content/docs/(latest)/setups/tanstack-router.mdx
@@ -6,12 +6,14 @@ description: Keep the client in Router context, guard private routes before they
In this guide, you add TanStack Router to the app from Getting started: a
sign-in route, private routes that redirect signed-out users, and hooks that
read the client from the Router. Guards run in `beforeLoad`, before a private
-route loads or renders, and the hooks need no `AuthProvider`.
+route loads or renders. The hooks come from
+`@monarcode/session-kit/tanstack-router`, typed by the Router you register,
+and need no `AuthProvider`.
A complete app is in
[`examples/tanstack-router`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-router).
-[TanStack Start in SPA mode](#tanstack-start-in-spa-mode) differs in two
-places. For TanStack Start with server rendering, follow
+[TanStack Start in SPA mode](#tanstack-start-in-spa-mode) lists what changes
+for Start. For TanStack Start with server rendering, follow
[TanStack Start](/docs/setups/tanstack-start) instead.
## Before you begin
@@ -46,34 +48,16 @@ export default defineConfig({
The plugin generates `src/routeTree.gen.ts` from the files under `src/routes`.
-## 1. Create the hooks
-
-Create hooks that read the client from Router context. They replace Getting
-started's `src/hooks.ts`:
-
-```ts title="src/hooks.ts"
-import { createAuthHooks } from "@monarcode/session-kit/react";
-import { useRouterAuth } from "@monarcode/session-kit/tanstack-router";
-
-// Reads the client from Router context, so no provider is needed.
-export const { useAuth, useAuthClient } = createAuthHooks({
- useClient: useRouterAuth,
-});
-```
-
-Routes take the place of Getting started's `src/app.tsx`. Registering the
-Router in step 5 gives the hooks your user type.
-
-## 2. Type the root route
+## 1. Type the root route
The root route declares that Router context holds the client, so every guard
gets a typed `context.auth`:
```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";
-import { useAuth } from "../hooks.js";
export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({
component: Root,
@@ -92,15 +76,16 @@ function Root() {
}
```
-## 3. Add the sign-in route
+## 2. Add the sign-in route
-The sign-in route renders the form from Getting started, and sends the user
-on to the page they asked for:
+The sign-in route renders the form from Getting started. Its guard sends a
+signed-in user on to the page they asked for, and it runs again after a
+sign-in, so the form doesn't navigate:
```tsx title="src/routes/login.tsx"
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router";
-import { createFileRoute, useRouter } from "@tanstack/react-router";
+import { createFileRoute } from "@tanstack/react-router";
import { SignIn } from "../sign-in.js";
@@ -110,27 +95,18 @@ export const Route = createFileRoute("/login")({
}),
beforeLoad: ({ context, search }) =>
redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
- component: Login,
+ component: SignIn,
});
-
-function Login() {
- const router = useRouter();
- const { redirectTo } = Route.useSearch();
- return (
- router.navigate({ href: redirectTo, replace: true })}
- />
- );
-}
```
`safeReturnTo` accepts only same-origin paths and returns `/` for anything
else, including the sign-in page itself, so a stale `redirectTo` can't loop.
-Pass `{ loginPath }` if sign-in lives somewhere other than `/login`.
+If sign-in isn't at `/login`, pass the same `{ loginPath }` to
+`safeReturnTo`, `redirectIfSignedIn` and `requireSession`.
`redirectIfSignedIn` sends signed-in users on to `redirectTo`, checked the
-same way.
+same way. `connectAuth` runs it again after a sign-in.
-## 4. Guard private routes
+## 3. Guard private routes
Guard private routes with a pathless layout. Its child routes are guarded
without `authenticated` appearing in their URLs:
@@ -139,17 +115,16 @@ without `authenticated` appearing in their URLs:
import {
requireSession,
SessionOutlet,
+ useAuthClient,
} from "@monarcode/session-kit/tanstack-router";
import {
createFileRoute,
type ErrorComponentProps,
} from "@tanstack/react-router";
-import { useAuthClient } from "../hooks.js";
-
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
- requireSession(context.auth, { location, loginPath: "/login" }),
+ requireSession(context.auth, { location }),
errorComponent: SessionError,
component: () => Checking session…} />,
});
@@ -166,8 +141,9 @@ function SessionError({ error }: ErrorComponentProps) {
}
```
-`requireSession` redirects signed-out users to `loginPath` with `redirectTo`
-set to where they were going, and puts `{ session }` in route context. A
+`requireSession` redirects signed-out users to `/login`, or the `loginPath`
+you pass, with `redirectTo` set to where they were going, and puts
+`{ session }` in route context. A
failed refresh reaches the error component instead of a redirect, because the
user is still signed in.
@@ -181,10 +157,9 @@ 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";
-import { useAuthClient } from "../../hooks.js";
-
export const Route = createFileRoute("/_authenticated/")({
component: Home,
});
@@ -203,7 +178,7 @@ function Home() {
}
```
-## 5. Create and connect the Router
+## 4. Create and connect the Router
Create the Router with the client in its context, then connect the two:
@@ -232,10 +207,13 @@ declare module "@tanstack/react-router" {
```
`connectAuth` does for the Router what `AuthProvider` does for a plain React
-app, and one thing more: when the session changes, it runs the guards again,
+app, and one thing more. When the session changes, it runs the guards again,
so a sign-out in another tab redirects this one.
-## 6. Render the app
+Registering the Router also types `useAuth` and `useAuthClient` with your
+client. Until it's registered, they're typed `never`.
+
+## 5. Render the app
Render the Router:
@@ -269,9 +247,7 @@ the pages go:
```tsx title="src/dashboard.tsx"
import { useState } from "react";
-import { SessionOutlet } from "@monarcode/session-kit/tanstack-router";
-
-import { useAuth } from "./hooks.js";
+import { SessionOutlet, useAuth } from "@monarcode/session-kit/tanstack-router";
/** The guarded route's component: `component: Dashboard`. */
export function Dashboard() {
@@ -302,9 +278,8 @@ function Sidebar() {
}
```
-`SessionOutlet` finds the session its guard accepted from the nearest route,
-which is still the guarded one anywhere in that route's component. Three
-things follow from where it sits:
+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
@@ -320,8 +295,16 @@ things follow from where it sits:
## TanStack Start in SPA mode
-TanStack Start's SPA mode is TanStack Router with a build-time shell, so every
-step on this page applies, with two changes.
+TanStack Start's SPA mode is TanStack Router with a build-time shell. Steps 2
+and 3 apply as they are. Installation, step 1, step 4 and step 5 change:
+
+- Install `@tanstack/react-start` instead of `@tanstack/router-plugin`.
+- In `vite.config.ts`, use Start's plugin, with SPA mode on, instead of the
+ Router plugin:
+ `plugins: [tanstackStart({ spa: { enabled: true } }), react()]`.
+- Give the root route a `shellComponent` that renders ``,
+ `` and ``, as the example app does. Start renders
+ the app from it, so there is no `src/main.tsx`.
In `src/router.tsx`, create the Router and connect auth inside
`getRouter()`, which Start calls:
@@ -375,7 +358,8 @@ written with Effect and effetch, in
`connectAuth` restores the saved session before the first render, so a
signed-in user never sees the sign-in page.
- **Stopping.** Call `disconnectAuth` on app teardown or hot-module disposal.
- It stops background work without signing out.
+ It stops background work without signing out. In Start's SPA mode,
+ `getRouter()` doesn't keep it, as the Router lasts as long as the page.
- **A failed refresh is not a redirect.** `requireSession` rethrows it for the
route's error component, which can offer `auth.retry()`. The user is still
signed in.
@@ -387,7 +371,9 @@ written with Effect and effetch, in
## Next steps
- [Call your API](/docs/getting-started#5-call-your-api) with `authFetch`, as
- in Getting started. It works unchanged with the Router.
+ in Getting started, or with
+ [ky, axios or openapi-fetch](/docs/client/other-http-clients). It works
+ unchanged with the Router.
- [Using the client](/docs/client): updating the user, signing out, and the
client's other methods.
- [Effect and effetch](/docs/effect): the same client as an Effect service.
diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx
index edb81f0..2c5d0dd 100644
--- a/site/content/docs/(latest)/setups/tanstack-start.mdx
+++ b/site/content/docs/(latest)/setups/tanstack-start.mdx
@@ -8,8 +8,7 @@ Start. The server signs in, refreshes the tokens before rendering, and sends
the signed-in page first, so the browser never shows a "Checking session…"
state or a flash of signed-out content. The browser holds a small client that
mirrors the session, and the
-[hooks](/docs/getting-started#4-read-the-session-in-react)
-and the [TanStack Router guards](/docs/setups/tanstack-router) work with it.
+[TanStack Router hooks and guards](/docs/setups/tanstack-router) work with it.
[Server rendering](/docs/server-rendering) explains how the pieces fit.
For TanStack Start in SPA mode, where the browser keeps the session, follow
@@ -29,18 +28,20 @@ instead. A complete app is in
To install the packages, run the following command:
```npm
-npm install @monarcode/session-kit @tanstack/react-start zod
+npm install @monarcode/session-kit @tanstack/react-start @tanstack/react-router zod
```
## 1. Create the server engine
`createServerAuth` from `@monarcode/session-kit/server` keeps the session in
-a cookie sealed with your `secret`, and refreshes it with your backend. Create
-it in a server-only module, so Start refuses to bundle it for the browser:
+a cookie sealed with your `secret`, and refreshes it with your backend.
+`startAuth` gives 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";
const API = "https://api.example.com";
@@ -66,6 +67,9 @@ export const serverAuth = createServerAuth({
},
});
+/** 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`, {
@@ -91,38 +95,54 @@ export async function login(username: string, password: string) {
its other options, rotating the secret, signing out, and the limits every
setup shares.
-## 2. Add server functions
+## 2. Add the session route and server functions
+
+The browser's client signs out and gets the access token through a session
+route. `sessionRoute` from `@monarcode/session-kit/tanstack-start/server`
+makes its `GET` and `POST` handlers, for a server route. Start leaves
+`server.handlers` out of the browser bundle, `serverAuth` included:
+
+```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) },
+});
+```
+
+It answers your own site's pages only, so another site can't sign the user
+out: see [The session route](/docs/security#the-session-route).
-Every `serverAuth` method takes the request's cookie jar, and `startJar()`
-from `@monarcode/session-kit/tanstack-start/server` gives it. Your server
-functions decide what the browser may ask for:
+Two server functions do the rest. Signing in takes your form's input. Reading
+the session is a server function too, because `loadSession` reads it while
+Start renders on the server, where the client can't call a route on its own
+site. `session` finds the request each time it's called, so one object
+serves every request:
```ts title="src/auth/functions.ts"
-import { startJar } from "@monarcode/session-kit/tanstack-start/server";
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
-import { login, serverAuth } from "./server";
+import { login, session } from "./server";
export const getSessionFn = createServerFn().handler(() =>
- serverAuth.getSession(startJar()),
+ session.getSession(),
);
export const signInFn = createServerFn({ method: "POST" })
.validator(z.object({ username: z.string(), password: z.string() }))
- .handler(async ({ data }) =>
- serverAuth.signIn(startJar(), await login(data.username, data.password)),
- );
-
-export const signOutFn = createServerFn({ method: "POST" }).handler(() =>
- serverAuth.signOut(startJar()),
-);
+ .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 `startJar` and
-`serverAuth` out of it.
+handler with a request in the browser bundle, and leaves `session` out of it.
## 3. Refresh before rendering
@@ -130,10 +150,15 @@ Request middleware refreshes access that is about to expire before any route
or server function reads it, while the response can still set the cookie.
Once Start starts streaming a page, a cookie set later is lost, so a refresh
then, such as in a deferred loader's promise, would spend the refresh token
-and drop the new one:
+and drop the new one.
+
+`refreshSession` from `@monarcode/session-kit/tanstack-start/server` does
+the refresh. Pass it to Start's own `createMiddleware().server()`. Start
+bundles `src/start.ts` for the browser too, but strips what's inside
+`.server()`, so `serverAuth` stays on the server:
```ts title="src/start.ts"
-import { startJar } from "@monarcode/session-kit/tanstack-start/server";
+import { refreshSession } from "@monarcode/session-kit/tanstack-start/server";
import {
createCsrfMiddleware,
createMiddleware,
@@ -143,11 +168,7 @@ import {
import { serverAuth } from "./auth/server";
const sessionMiddleware = createMiddleware({ type: "request" }).server(
- async ({ next }) => {
- // A failed refresh shows up when a route reads the session.
- await serverAuth.refreshIfDue(startJar()).catch(() => {});
- return next();
- },
+ refreshSession(serverAuth),
);
export const startInstance = createStart(() => ({
@@ -160,35 +181,44 @@ export const startInstance = createStart(() => ({
}));
```
+It refreshes access that expires within 60 seconds. Access tokens that live
+a minute or less are refreshed on every request, so pass a smaller `within`
+for them, such as `refreshSession(serverAuth, { within: 15 })`.
+
+A failed refresh doesn't fail the request. Routes read the session as
+usual, and an error there reaches the route's error component.
+
An app that defines `createStart` has no CSRF protection for its server
functions until it adds `createCsrfMiddleware`. Its `filter` keeps the check
-to server-function calls: unfiltered, it also refuses page loads from links
-on other sites and from the address bar. Server routes are left out too, so
-a server route that changes the session must refuse other sites itself:
-compare its `Sec-Fetch-Site` header to `same-origin`.
+to server-function calls. Unfiltered, it also refuses page loads from links
+on other sites and from the address bar. It leaves out server routes.
+`sessionRoute` refuses other sites itself, and a server route of your own
+that changes the session must too: see
+[The session route](/docs/security#the-session-route).
## 4. Create the browser client
`createMirrorAuth` makes the client that routes and components use. Create it
in `getRouter`, which Start calls once per request on the server and once in
-the browser, never at module level. `sessionHydration` sends the session the
-server read to the browser with the page.
+the browser, never at module level. `connectSession` sends the session the
+server read to the browser with the page, and runs guards again when it
+changes there.
First, the client:
```ts title="src/auth/client.ts"
import { createMirrorAuth } from "@monarcode/session-kit";
-import { getSessionFn, signInFn, signOutFn } from "./functions";
+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 }),
- signOut: () => signOutFn(),
});
}
@@ -198,8 +228,7 @@ export type AppAuth = ReturnType;
Then the Router, which creates it and connects it:
```tsx title="src/router.tsx"
-import { connectAuth } from "@monarcode/session-kit/tanstack-router";
-import { sessionHydration } from "@monarcode/session-kit/tanstack-start";
+import { connectSession } from "@monarcode/session-kit/tanstack-start";
import { createRouter } from "@tanstack/react-router";
import { createAppAuth } from "./auth/client";
@@ -207,12 +236,8 @@ import { routeTree } from "./routeTree.gen";
export function getRouter() {
const auth = createAppAuth();
- const router = createRouter({
- routeTree,
- context: { auth },
- ...sessionHydration(auth),
- });
- connectAuth(router);
+ const router = createRouter({ routeTree, context: { auth } });
+ connectSession(router);
return router;
}
@@ -223,8 +248,10 @@ declare module "@tanstack/react-router" {
}
```
-Let TypeScript infer the client's types from its options: with
-`createMirrorAuth(…)`, `signIn` would be left out.
+Let TypeScript infer the client's types from its options. With
+`createMirrorAuth(…)`, `signIn` would be left out. 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
@@ -244,6 +271,11 @@ export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({
});
```
+When the server can't read the session, such as after a failed refresh,
+`loadSession` rejects, and the root route's `errorComponent` shows. In the
+example app, it offers a retry with `router.invalidate()`, which runs
+`loadSession` again.
+
Guards are the ones from `@monarcode/session-kit/tanstack-router`. On the
server, a redirect is a real HTTP redirect:
@@ -256,17 +288,18 @@ import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) =>
- requireSession(context.auth, { location, loginPath: "/login" }),
+ requireSession(context.auth, { location }),
component: () => Loading…} />,
});
```
-[Guard private routes](/docs/setups/tanstack-router#4-guard-private-routes)
-explains `SessionOutlet`, and an error component for a failed refresh.
+[Guard private routes](/docs/setups/tanstack-router#3-guard-private-routes)
+explains `SessionOutlet`. Its error component isn't needed here, as
+`loadSession` reports a failed refresh first.
Guards decide what a page shows. Server functions that return private data
-must check the session themselves, with `serverAuth.getSession(startJar())`
-or `serverAuth.credentials.get(startJar())`.
+must check the session themselves, with `session.getSession()` or
+`session.credentials.get()`.
## Sign in
@@ -276,71 +309,114 @@ the session it returns, re-runs guards and tells other tabs:
```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) {
- // An AuthError; its cause is what signInFn threw.
- console.warn(error);
+ // What signInFn threw, such as your backend's message for a wrong
+ // password.
+ return error instanceof Error ? error.message : "Could not sign in";
}
}
```
+In a component, `useAuthClient` from `@monarcode/session-kit/tanstack-router`
+gives you `auth`, from Router context.
+
+Give the sign-in route the `redirectIfSignedIn` guard, as in TanStack Router's
+[Add the sign-in route](/docs/setups/tanstack-router#2-add-the-sign-in-route).
+`connectSession` runs it again after a sign-in, so the form doesn't navigate.
+
In this guide, the server signs in with your backend, so the user in the cookie
comes from the backend. If the browser signs in with the backend itself, for
-example through a provider's SDK, have `signInFn` take the tokens and the user
-instead and pass them to `serverAuth.signIn`. It seals what it's given: until a
-refresh or `updateUser` replaces it, the user in the cookie is what the browser
-sent. Use it to show who is signed in, and let your backend authorize requests
-with the access token, or check the tokens in `signInFn` first.
+example through a provider's SDK, have `signInFn` take the tokens instead, as
+[Hybrid setup](/docs/server-rendering/hybrid) shows.
+
+## Sign out
+
+The client's `signOut()` signs out on the server through the session route,
+which clears the cookie and calls your `revoke` option, when
+`createServerAuth` has one. It then signs out this tab and tells the others.
+Guards run again, so `requireSession` sends the user to the sign-in page:
+
+```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 (
+
+ );
+}
+```
## Call your API
-On the server, get the access token in a server function.
-`credentials.get` refreshes it first when it has expired:
+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 when it has expired. After a 401, it renews the token, saves
+it in the cookie, and sends a `GET` again. Make it once, in a server-only
+module:
+
+```ts title="src/auth/api-fetch.ts"
+import "@tanstack/react-start/server-only";
+import { createAuthFetch } from "@monarcode/session-kit/http";
+
+import { session } from "./server";
+
+export const apiFetch = createAuthFetch(session, {
+ baseUrl: "https://api.example.com/",
+});
+```
+
+Then call it in a server function. Signed out, it rejects with
+`UNAUTHENTICATED`:
```ts title="src/orders.ts"
-import { startJar } from "@monarcode/session-kit/tanstack-start/server";
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
-import { serverAuth } from "./auth/server";
+import { apiFetch } from "./auth/api-fetch";
export const getOrdersFn = createServerFn().handler(async () => {
- const credentials = await serverAuth.credentials.get(startJar());
- if (!credentials) throw new Error("Sign in first");
- const response = await fetch("https://api.example.com/orders", {
- headers: { Authorization: `Bearer ${credentials.accessToken}` },
- });
+ const response = await apiFetch("orders");
if (!response.ok) throw new Error(`Orders failed (${response.status})`);
return z.array(z.object({ id: z.number() })).parse(await response.json());
});
```
+With an HTTP client of your own, such as ky or axios, see
+[Other HTTP clients](/docs/client/other-http-clients). A client without a
+`fetch` option reads the token with `session.credentials.get()`.
+
To call the API from the browser too, with `createAuthFetch` or effetch's
`sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`.
-Expose `serverAuth.clientCredentials.get` and `.renew` through two POST server
-functions, and pass them as the client's `credentials`. The browser then
-keeps the access token in memory, never the refresh token. The example app
-does this.
+The session route then serves the access token, and the client's
+`credentials` get it there. The browser keeps the access token in memory,
+never the refresh token. The example app does this.
## Things to know
-- **Signing out ends the session only with `revoke`.** A copy of the cookie
- works again ten seconds after sign-out: see
+- **Signing out ends the session only with `revoke`.** Without it, a copy of
+ the cookie made before sign-out still works: see
[Sign-out](/docs/server-rendering/server-sessions#sign-out).
-- **One jar per request.** `startJar()` returns the same jar for every call
- while Start handles a request.
+- **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, they reject with
+ `INVALID_OPTIONS`.
- **Caching.** Pages and server functions that read the session differ per
- user, and Start sends no `Cache-Control` for them. Behind a CDN or proxy
- that caches responses, mark them private, for example with
- `setResponseHeader("Cache-Control", "private, no-store")` from
- `@tanstack/react-start/server` in request middleware, as the example app
- does.
+ user. `refreshSession` sends `Cache-Control: private, no-store` with each
+ response that doesn't set its own, so a CDN or proxy doesn't cache them.
+ To leave every response as it is, pass `{ cacheControl: false }`.
- **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.
diff --git a/site/public/og.png b/site/public/og.png
index 484864d..5309dd9 100644
Binary files a/site/public/og.png and b/site/public/og.png differ
diff --git a/site/src/components/docs/how-it-works.tsx b/site/src/components/docs/how-it-works.tsx
new file mode 100644
index 0000000..79b9e75
--- /dev/null
+++ b/site/src/components/docs/how-it-works.tsx
@@ -0,0 +1,240 @@
+import { Fragment, useEffect, useRef, type CSSProperties } from "react";
+
+// The "How it works" figure on the Introduction: your backend, Session kit and
+// your components as three flat panels, with what crosses between them drawn
+// as hairline arrows. HTML rather than an image, so it reflows with the page,
+// stays selectable, and takes the site's own type and colours.
+
+type Direction = "left" | "right" | "both";
+
+type Crossing = { direction: Direction; label: string } | null;
+
+const COLUMNS = [
+ {
+ name: "Your backend",
+ note: "issues tokens",
+ items: ["POST /login", "POST /refresh", "GET /orders"],
+ },
+ {
+ name: "Session kit",
+ note: "keeps the session",
+ items: ["signIn()", "refresh, on time", "authFetch()"],
+ },
+ {
+ name: "Your components",
+ note: "state, never tokens",
+ items: ["useAuth()", "route guards", "loaders, queries"],
+ },
+] as const;
+
+// For each row, what crosses the gap after the backend and the gap after
+// Session kit. Tokens only ever cross the first.
+const CROSSINGS: readonly [Crossing, Crossing][] = [
+ [
+ { direction: "right", label: "tokens" },
+ { direction: "right", label: "state" },
+ ],
+ [{ direction: "both", label: "tokens" }, null],
+ [
+ { direction: "left", label: "token" },
+ { direction: "left", label: "request" },
+ ],
+];
+
+// When a packet sets off across each arrow, in ms, in the order a sign-in and
+// then a request travel: the login row, the refresh, then the request out.
+const DELAYS: readonly [number, number][] = [
+ [0, 450],
+ [900, 0],
+ [2250, 1800],
+];
+
+const HEADER = "h-16";
+const ROW = "h-12";
+
+/**
+ * Where tokens, state and requests travel between the backend, Session kit
+ * and the components, as a figure.
+ *
+ * The page puts a text diagram inside it. This component ignores that, and
+ * the page's Markdown keeps it.
+ */
+export function HowItWorks() {
+ const figure = useRef(null);
+
+ // Plays the packets once, when the figure first scrolls into view.
+ useEffect(function playWhenSeen() {
+ const node = figure.current;
+ if (!node || typeof IntersectionObserver === "undefined") return;
+ const observer = new IntersectionObserver(
+ function onIntersect([entry]) {
+ if (!entry?.isIntersecting) return;
+ node.dataset.play = "";
+ observer.disconnect();
+ },
+ { threshold: 0.4 },
+ );
+ observer.observe(node);
+ return function unwatch() {
+ observer.disconnect();
+ };
+ }, []);
+
+ return (
+
+
+ );
+}
+
+/** The square that crosses an arrow once; `app.css` plays it. */
+function Packet({
+ axis,
+ direction,
+ delay,
+}: {
+ axis: "x" | "y";
+ direction: Direction;
+ delay: number;
+}) {
+ return (
+
+ );
+}
+
+function Arrowhead({ className = "" }: { className?: string }) {
+ return (
+
+ );
+}
diff --git a/site/src/components/landing/closing.tsx b/site/src/components/landing/closing.tsx
index 085f5ed..0a04fab 100644
--- a/site/src/components/landing/closing.tsx
+++ b/site/src/components/landing/closing.tsx
@@ -1,5 +1,7 @@
import { Link } from "@tanstack/react-router";
+import { gitConfig } from "@/lib/shared";
+
import { COLUMN, PRIMARY_ACTION, SectionHead } from "./buffer";
import { Install } from "./install";
@@ -8,7 +10,7 @@ const INLINE_LINK =
/**
* Where the page ends: the hero's actions again, so a visitor who read to the
- * bottom doesn't scroll back for them, under two facts they can check.
+ * bottom doesn't scroll back for them, under three facts they can check.
*/
export function Closing() {
return (
@@ -28,6 +30,19 @@ export function Closing() {
.
+
+
+ {"// "}
+
+ Each one passes{" "}
+
+ the test suite
+ {" "}
+ twice, with synchronous and with asynchronous storage.
+
{"// "}
diff --git a/site/src/components/landing/features.tsx b/site/src/components/landing/features.tsx
index 9615296..ff25296 100644
--- a/site/src/components/landing/features.tsx
+++ b/site/src/components/landing/features.tsx
@@ -2,24 +2,32 @@ import { COLUMN, SectionHead } from "./buffer";
const FEATURES = [
[
- "Schema-driven users",
- "Any Standard Schema library, such as Zod, Valibot or ArkType, checks the user at sign-in, refresh, restore and in other tabs, and types it.",
+ "One refresh at a time",
+ "Open tabs take turns, so only one spends the refresh token and the rest reuse the tokens it saved. A sign-out in one tab signs out them all.",
+ ],
+ [
+ "A user you can trust",
+ "Your schema, from Zod, Valibot, ArkType or any Standard Schema library, types the user and checks it wherever it arrives: at sign-in, on refresh, on reload and from another tab.",
],
[
"Tokens kept out of state",
"The auth state holds no tokens, so it's safe to render and to put in route context. Only the code that sends your requests reads them.",
],
[
- "Guards for every router",
+ "Guards for your router",
"TanStack Router, React Router in all three modes, Expo Router and Next.js send signed-out users to sign in, then back to the page they asked for.",
],
+ [
+ "Your HTTP client",
+ "ky, axios, openapi-fetch and anything else that takes a fetch send the access token to your API's origin only, and refresh after a 401.",
+ ],
[
"Server rendering",
- "With TanStack Start, Next.js or React Router, the session lives in an encrypted httpOnly cookie.",
+ "With TanStack Start, Next.js or React Router, the session lives in an encrypted httpOnly cookie, so the first render is already signed in.",
],
[
"Native apps",
- "The iOS keychain and Android Keystore, a splash screen held while restoring, and biometric locking.",
+ "The session is saved in the iOS keychain or Android Keystore, the splash screen holds until it's restored, and it can lock behind biometrics.",
],
[
"Made to be debugged",
@@ -30,7 +38,7 @@ const FEATURES = [
export function Features() {
return (
-
+
{FEATURES.map(([title, text]) => (
{"// "}
- Your backend signs users in.{" "}
+ Every sign-in ends in a session.{" "}
@@ -37,19 +40,28 @@ export function Hero({
>
{"// "}
- Session kit handles everything after.
+ {/* "predictable." never wraps onto a line of its own. */}
+ Make yours{" "}
+ type-safe and
+ {"\u00a0"}predictable.
-
+
+
+ {"// "}
+
+ Define, validate, and manage application sessions with a
+ schema-driven toolkit built for React and meta frameworks.
+
+
{"// "}
- Hand it the tokens your sign-in endpoint returns. It saves,
- restores and refreshes the session, keeps tabs in step, and
- guards your routes.
+ With support for TanStack Router and Start, React Router,
+ Next.js, Expo Router on iOS and Android, and Effect.