Use Effect in the browser
Read the session as an Effect service, call your API with effetch, and cache each account's data with effetch-query, in a browser or Expo app.
Your app runs its logic as Effect programs, and
they need to know who is signed in and to send the access token with every
API call. This guide sets that up in a single-page app or an Expo app. Your
Effects read the session as the Auth service, call your API with
effetch, and, if you want, cache each
account's data with
effetch-query.
The guide builds the app from Getting started again,
with Effect Schemas and effetch. Effect and effetch explains
the two entry points it uses. The browser half of this guide, with TanStack
Router and a user read from the access token, runs in
examples/tanstack-start-spa-effetch.
With server rendering, your framework's guide creates and registers the browser's client in place of step 3. Build the layer and runtime of steps 4 and 7 where that client is created. Use Effect on the server covers the server's side.
Before you begin
- Read Getting started. Refresh and Errors explain how the client renews and fails.
- Know Effect's generators, services and layers.
- Effect asks for TypeScript 5.9 or newer.
- To cache with effetch-query, you need React 19: its React bindings don't support React 18. Compatibility lists every version.
Installation
To install the packages, run the following command:
npm install @monarcode/session-kit effect @monarcode/effetcheffect and @monarcode/effetch are optional peer dependencies of Session
kit. ./effect and ./effetch need effect 4.1 or newer, and ./effetch
also needs @monarcode/effetch 0.1.0-rc.4 or newer. effetch-query has its
own install, in Cache with effetch-query.
1. Describe your backend
Start with the backend from Getting started, as Effect Schemas: the user, the tokens, and the body DummyJSON explains a failure with. The file holds schemas only, with no client, so the rest of the app and the server can import them from one place:
import * as from "effect/Schema";
export const = "https://dummyjson.com";
export const = .({
: .,
: .,
: .,
: .,
});
/** The user, as Session kit's `user` option takes it. */
export const = .();
export const = .({
: .,
: .,
});
/** DummyJSON returns the user's fields beside the tokens. */
export const = .({
....,
....,
});
export const = .({ : . });2. Refresh with effetch
The refresh exchanges the refresh token for new tokens. It gets an effetch
client of its own, made with its own Fetch.make:
import { Fetch } from "@monarcode/effetch";
import * as from "effect/Effect";
import * as from "effect/http/FetchHttpClient";
import * as from "effect/http/HttpClient";
import { , } from "./backend.js";
// Not the app's API client: its session plugin waits for this refresh.
const = Fetch.({ : }).(
// No tracing headers, as for the API client in step 6.
.(., false),
);
/** New tokens. `null` signs out; a failure keeps the session for a retry. */
export const = (: string, : ) =>
.(
.(function* () {
const = yield* ;
return yield* .("/auth/refresh", {
: { },
: ,
});
}).(
Fetch.([401, 403], () => .(null)),
.(.),
),
{ },
);The refresh can't use the app's API client or its runtime, for two reasons:
- After a 401, the app's API client waits for a refresh. A refresh sent through it would wait for itself.
- The app's runtime is built on the session client this refresh belongs
to, so the refresh can't run in it. It provides its own
FetchHttpClient, which effetch sends requests with.
refreshSession resolves null when the backend rejects the refresh token,
which signs the user out. It fails for anything else, such as an outage, and
the session is kept for a retry. Refresh
explains both. The server uses this function too.
3. Register the client
Create the client as usual, then register its type once, so that every
Effect carries your user. The same registration types the hooks from
@monarcode/session-kit/react:
import { , } from "@monarcode/session-kit";
import { } from "./backend.js";
import { } from "./refresh.js";
export const = ({
: "app",
: ,
: (),
: ({ , }) => (, ),
});
declare module "@monarcode/session-kit" {
interface Register {
: typeof ;
}
}4. Provide the service
Auth.layer provides the client as the Auth service. Create the layer
once:
import { } from "@monarcode/session-kit/effect";
import { } from "./auth.js";
export const = .();The layer doesn't mount the client. AuthProvider, SessionGate or the
router adapters still do that, as your setup guide shows.
In tests, provide a layer over another createAuth client with the same
user, such as one that keeps the session in memory. After you register
your client, Auth.layer takes only a client of that type:
import { , } from "@monarcode/session-kit";
import { } from "@monarcode/session-kit/effect";
import { } from "./backend.js";
export const = ({
: "test",
: ,
: (),
});
export const = .();5. Read the session
Auth.session is the current session. If the access token has expired, it
refreshes first, and it fails with UNAUTHENTICATED when no one is signed
in. For code that also runs signed out, Auth.sessionOption gives
Option.none() instead:
import { } from "@monarcode/session-kit/effect";
import * as from "effect/Effect";
import * as from "effect/Option";
export const = ..(
.(
.({
: () => "Welcome",
: () => `Welcome back, ${..}`,
}),
),
);greeting needs the Auth service to run. Step 7 runs it with the rest of
the app's services.
6. Call your API with effetch
Make the app's API client as an effetch Fetch.Service: the backend's base
URL, its error body, and the plugins every call goes through. The
sessionBearer plugin sends the access token, and gets a new one after a
401:
import { Fetch } from "@monarcode/effetch";
import { } from "@monarcode/effetch/plugins";
import { } from "@monarcode/session-kit/effetch";
import * as from "effect/http/HttpClient";
import * as from "effect/Layer";
import { , } from "./backend.js";
export class extends Fetch.<>()("ApiClient", {
: ,
: ,
: [(), ({ : , : true })],
}) {}
/** The API client, over whichever `Auth` is provided. */
export const = ..(
// Effect adds tracing headers to every request, which fail the preflight
// of an API that doesn't allow them.
.(.(.)(false)),
);Here's what the plugin's options and place do:
- Last in
plugins. A retry then reads the current token. baseUrl. The token goes only to that origin, so give it the client'sbaseUrl.optional: true. One client here serves public and private endpoints. A call made while signed out is then sent without a token, and a private endpoint answers with its own 401. A locked client still fails withLOCKED.- The
Authservice. The client's layer needs it, once. Calls don't.
sessionBearer handles a 401 the way
Authenticated requests describes for
createAuthFetch. One rule matters most: if a GET or HEAD sent again
with the new token gets a 401 too, the user is signed out. For an API that
also answers 401 for other reasons, such as a missing permission, pass
signOutOnRepeated401: false. Its failures and a few other details differ
from createAuthFetch's, as
How sessionBearer differs from createAuthFetch
lists.
Effect code yields the client and calls its methods, such as get and
post. To read the current user and to sign in, add src/user.ts:
import * as from "effect/Effect";
import { } from "./api.js";
import { , } from "./backend.js";
export const = .(function* () {
const = yield* ;
return yield* .("/auth/me", { : });
});
export const = (: string, : string) =>
.(function* () {
const = yield* ;
return yield* .("/auth/login", {
: { , },
: ,
: { : false },
});
});The sign-in call skips the plugin with sessionBearer: false, because it's
how the user gets a token.
After a refresh, sessionBearer sends only a GET or HEAD again. A
POST or any other method that got the 401 fails with an HttpError whose
status is 401, after the token is renewed. Where sending it twice is safe,
catch that status with Fetch.catchStatus and call again, since the next
call reads the new token:
import { Fetch } from "@monarcode/effetch";
import * as from "effect/Effect";
import { } from "./api.js";
export const = (: number, : number) => {
const = .(function* () {
const = yield* ;
return yield* .("/auth/carts/add", {
: { , : [{ : , : 1 }] },
});
});
// The 401 refreshed the token, so one more try uses the new one.
return .(Fetch.(401, () => ));
};With another HTTP client, use
Auth.credentials, the access token. It's kept apart from Auth.session,
so code that only needs the user never holds a token. After a 401,
Auth.renew(credentials) gets new credentials once for every caller.
7. Run Effects in one runtime
Compose the app's layers in one place: the API client, the session, and the
FetchHttpClient effetch sends requests with, each made once:
import * as from "effect/http/FetchHttpClient";
import * as from "effect/Layer";
import * as from "effect/ManagedRuntime";
import { } from "./api.js";
import { } from "./layer.js";
const = .(
.(),
.(.),
);
/** One runtime for the app's lifetime. */
export const = .();
export type = typeof ;Run every Effect with this runtime. For example,
appRuntime.runPromise(greeting) resolves "Welcome back, Emily" while
emilys is signed in, and appRuntime.runPromise(currentUser) fetches her
profile.
8. Sign in and out
Session kit doesn't sign users in: your backend checks the password. Ask it
with login, then save what it returns with Auth.signIn, which takes what
the client's signIn takes. Auth.signOut signs out:
import { } from "@monarcode/session-kit/effect";
import * as from "effect/Effect";
import { } from "./runtime.js";
import { } from "./user.js";
export const = (: string, : string) =>
.(
.(function* () {
const = yield* (, );
const { , , ... } = ;
yield* .({ , , });
}),
);
export const = () => .(.);Your sign-in form calls signIn("emilys", "emilyspass"). A wrong password
fails login with an HttpError, and no one is signed in. When the
response can't be saved, Auth.signIn fails with an AuthFailure, such as
USER_VALIDATION_FAILED for a user your schema rejects.
Signing in and out explains what each
call does to the session.
That completes the setup. The rest of this page covers failures, the user and changes to the session, then optional caching.
Handle failures
Every Auth Effect fails with AuthFailure, whose code is the client's
AuthErrorCode, and misuse is a defect.
How Effects fail explains both. Handle it
with Effect.catchTag, as you do your own errors. For example, to show
"Guest" when no one is signed in:
import { } from "@monarcode/session-kit/effect";
import * as from "effect/Effect";
export const = ..(
.(() => ..),
.("AuthFailure", () =>
. === "UNAUTHENTICATED"
? .("Guest")
: .(),
),
);A client method that Auth doesn't wrap, such as auth.unlock(), rejects
with an AuthError. Auth.fromAuthError turns it into an AuthFailure.
Anything else it's given, such as a network error from createAuthFetch,
is a defect.
Update the user
Auth.updateUser takes the user, or an Effect that fetches it:
import { } from "@monarcode/session-kit/effect";
import { } from "./user.js";
export const = .();The client notes the session before the Effect runs, so a profile fetched for one account never lands on another:
- The session changes first. The fetch is interrupted, and the update
fails with
SESSION_CHANGED. - The fetch takes more than 15 seconds. It's interrupted, and the update
fails with
USER_VALIDATION_FAILED, whosecauseis the timeout. - The fetch fails. Its own failure, such as an
HttpError, comes through unchanged.
Updating the user covers the rest, such as a user your schema rejects.
Watch the session
Auth.changes is a Stream of the client's AuthState: the current state,
then every change, until the stream ends:
import { } from "@monarcode/session-kit/effect";
import * as from "effect/Effect";
import * as from "effect/Stream";
export const = ..(
.(() => .),
.,
.(() => .(`Auth is ${}`)),
);Cache with effetch-query
effetch-query keeps what your endpoints return in a cache, and your
components read it from there. The steps in this section are optional, and
need React 19. To install effetch-query 0.1.0-rc.4 or newer, with its
@effect/atom-react peer for React, run the following command:
npm install @monarcode/effetch-query @effect/atom-reactOptional: Create the query client
effetch-query calls endpoints, each a route and its schemas defined with
Fetch.endpoint, through the app's API client. Its queries and mutations
run with the app's runtime, so components never run an Effect by hand.
fromClient reads the client's defaultError from its class:
import { } from "@monarcode/effetch-query";
import { } from "@monarcode/effetch-query/effetch";
import type * as from "effect/ManagedRuntime";
import { } from "./api.js";
import { , type } from "./runtime.js";
declare module "@monarcode/effetch-query" {
interface Register {
readonly : .ManagedRuntime.<>;
}
}
export const = ();
export const = () => .({ : });Optional: Give each account its own cache
A cache must not outlive the account that filled it. Let QueryProvider own
its client (make instead of client) and pass the session ID as
resetKey. Signing out or switching accounts then disposes the client,
with its cache and any requests still running, and renders the tree with a
new one:
import type { } from "react";
import { } from "@monarcode/effetch-query/react";
import { } from "@monarcode/session-kit/react";
import { } from "./query.js";
export function ({ }: { : }) {
const = (() => . ?? "signed-out");
return (
< ={} ={}>
{}
</>
);
}Render Queries inside AuthProvider, above every Suspense boundary. On
Expo, that's inside the AuthProvider around SessionGate. With TanStack
Router, there's no AuthProvider: import useAuth from
@monarcode/session-kit/tanstack-router instead, and render Queries in
the root route, as the example app does.
The cache follows the session ID, so these keep it:
- A refresh, a failed refresh or a profile update. The session ID stays the same.
- Locking. The session ID stays the same. Queries that need a token
fail with
LOCKEDuntilunlock(), then refetch on their next trigger, such as the app coming back into focus.
Until a saved session is restored, the key is "signed-out", and the
restore replaces that client.
The owned client is for the browser and React Native. On the server, give
QueryProvider a client per request instead, as
Use Effect on the server
shows. In the browser, an app with server rendering keeps the owned client,
over its mirror client.
Optional: Query and mutate endpoints
A feature defines the endpoints it caches, and its components use the queries and mutations made of them:
import { Fetch } from "@monarcode/effetch";
import { , } from "@monarcode/effetch-query/react";
import { } from "@monarcode/session-kit/react";
import * as from "effect/Exit";
import * as from "effect/reactivity/AsyncResult";
import * as from "effect/Schema";
import { , } from "../backend.js";
import { } from "../query.js";
const = .(
Fetch.("POST /auth/login", {
: .({ : ., : . }),
: ,
}),
{ : { : false } },
);
const = .(
Fetch.("GET /auth/me", { : }),
);
export function () {
const = ();
const { , } = ();
async function () {
const = await ({
// DummyJSON's documented test user.
: { : "emilys", : "emilyspass" },
});
// A failed request shows in `result`.
if (.()) return;
const { , , ... } = .;
await .({ , , });
}
return (
<
={.}
={() => void ().(.)}
>
Sign in
</>
);
}
export function () {
const = (());
return .(, {
: () => <>Loading…</>,
: () => <>Couldn't load your profile.</>,
: ({ }) => <>{.}</>,
});
}The sign-in mutation saves the session with the client's own signIn,
which useAuthClient returns. With TanStack Router, import useAuthClient
from @monarcode/session-kit/tanstack-router too.
Next steps
- Use Effect on the server: run the same Effects in server functions and route handlers, with each request's session.
- Effect and effetch: what
Authcovers, and howsessionBearerdiffers fromcreateAuthFetch. - Other HTTP clients: the calls
sessionBeareris built on, for any other client. - Locking: lock a native app's session.
Auth.sessionandsessionBearerthen fail withLOCKEDuntil it's unlocked. ./effectreference and./effetchreference: every export.
Effect and effetch
Read the session as an Effect service, and call your API with effetch's sessionBearer plugin, which sends the access token and renews it after a 401.
Use Effect on the server
Run Effects with each request's session in server functions, actions and route handlers, sign in on the server, and render queries per request.