Build your application
Effect Atom client
The auth client is an Effect service backed by Effect HttpClient. Effect Atom
owns queries, mutations, shared state, and workflows; React renders their state
and dispatches inputs.
- Your code: React
useAtom(auth. signIn) - Yielded Auth: Mutation atom
auth.signIn - Yielded Auth: Client service
AppClient - Yielded Auth: Session query
auth.session - Yielded Auth: Auth HTTP routes
Http.layer( AppAuth, …)
- React to Mutation atom
- Mutation atom to Client service
- Client service to Auth HTTP routes: Effect HttpClient
- Mutation atom to Session query: updates
- Session query to React: useAtomValue
- Browser: React, Mutation atom, Client service, Session query
- Server: Auth HTTP routes
This guide uses the AuthApi shared contract from
getting started, served through
the HTTP integration.
Create the client and atoms
Section titled “Create the client and atoms”import { Atom as AuthAtom, Client } from "@yielded/auth";
import { AuthApi } from "@app/domain/auth-contract";
export const AppClient = Client.make(AuthApi, { baseUrl: "https://app.example.com" });export const auth = AuthAtom.make(AppClient);auth.session is a query atom; auth.signIn and auth.signOut are mutation atoms.
The application registry acquires and closes the client. Fetch is configured by
default; declaring the client and atoms performs no I/O.
Read a session and sign out
Section titled “Read a session and sign out”Use ordinary @effect/atom-react hooks under your application’s RegistryProvider:
import { RegistryProvider, useAtom, useAtomValue } from "@effect/atom-react";
import { auth } from "./auth-client";
export function Account() { const session = useAtomValue(auth.session); const [signOutResult, signOut] = useAtom(auth.signOut);
if (session._tag === "Initial") return <p>Loading…</p>; if (session._tag === "Failure") return <p>Session unavailable</p>; if (session.value === null) return <p>Signed out</p>;
return ( <> <button disabled={signOutResult.waiting} onClick={() => signOut(undefined)}> Sign out {session.value.claims.displayName} </button> {signOutResult._tag === "Failure" && <p role="alert">Sign-out failed. Check your session.</p>} </> );}
export function App() { return ( <RegistryProvider> <Account /> </RegistryProvider> );}Reuse an existing provider if you have one. Successful authentication supplies
auth.session immediately after credential settlement; other successful mutations
refresh it automatically.
When the server enables cookie caching,
use auth.getSession({ fresh: true }) to bypass it. Define this atom outside React
renders. “Fresh” applies to each server fetch; Atom retention still applies between
fetches. Auth mutations update both queries.
Dispatch a sign-in
Section titled “Dispatch a sign-in”The password action takes the same input as its server method. In a component with email and password form values:
import { useAtom } from "@effect/atom-react";
const [result, signIn] = useAtom(auth.signIn);
// In the form's submit handler:signIn({ email, password });Render pending state from result.waiting and failures from its AsyncResult.
An Authenticated success supplies the typed session to auth.session and
auth.identity without waiting for another request. Complete any requested
additional factor before granting access. The account app’s
form
and Atom workflow
show complete handling. Keep multi-step logic in atoms, not component promise chains.
Compose queries
Section titled “Compose queries”Use the same client from auth.runtime:
import { Effect } from "effect";
import { AppClient, auth } from "./auth-client";
export const memberName = auth.runtime.atom( Effect.gen(function* () { const client = yield* AppClient; const session = yield* client.auth.getSession();
return session?.claims.displayName ?? null; }),);Refresh application queries
Section titled “Refresh application queries”To refresh application queries after auth mutations, use a shared runtime factory and declare reactivity keys on the mutations:
import { Atom } from "effect/reactivity";
export const appRuntime = Atom.context();export const auth = AuthAtom.make(AppClient, { runtime: appRuntime, reactivityKeys: { signIn: ["projects"], signOut: ["projects"] },});Subscribe an application query through that same factory:
import { Effect } from "effect";
import { appRuntime } from "./auth-client";import { ProjectsClient, ProjectsClientLive } from "./projects-client";
const projectsRuntime = appRuntime(ProjectsClientLive);
export const projects = projectsRuntime .atom( Effect.gen(function* () { const client = yield* ProjectsClient; return yield* client.list(); }), ) .pipe(appRuntime.withReactivity(["projects"]));ProjectsClient and its Layer are application-owned. Matching keys refresh this
query without a component calling refetch().
Keep work with its account
Section titled “Keep work with its account”Queries, workflows, and shared state in auth.runtime belong to the current
account. An account change disposes them before publishing the replacement, so a
pending query cannot populate the new account with the previous account’s data.
Separate application atoms such as projects keep their own lifetime: reactivity
keys refresh them but do not make them account-scoped. See the
account lifetime reference.
To reopen local account data before the server is reachable, opt into an identity cache. Use a key scoped to this application and auth server:
import { Atom as AuthAtom, Client } from "@yielded/auth";import type { SubjectId } from "@yielded/auth/Schema";import { Effect } from "effect";import { KeyValueStore } from "effect/persistence";
import { AuthApi } from "@app/domain/auth-contract";
export const AppClient = Client.make(AuthApi, { baseUrl: "https://app.example.com" });export const auth = AuthAtom.make(AppClient, { identityCache: { key: "app:app.example.com:identity:v1", storage: KeyValueStore.layerStorage(() => localStorage), },});
export const verifyAccount = auth.runtime.fn<SubjectId>()( Effect.fn("app.verifyAccount")(function* (expectedSubjectId, get) { return yield* get.result(auth.verifiedSession(expectedSubjectId), { suspendOnWaiting: true, }); }),);Read auth.identity with useAtomValue: Unknown has no known identity,
Remembered and Verified carry subjectId and the public session snapshot, and
SignedOut records a confirmed sign-out and remains visible through pending or
failed session refreshes. A remembered identity selects local data;
it grants no authority. The cache stores one public snapshot, never credentials or
the Atom registry. Your application owns IndexedDB and other business data.
Compose auth.verifiedSession(expectedSubjectId) into an Effect workflow before
sending that account’s queued work. It uses the shared live session and
rejects a different or signed-out account; the server must still authorize each
request. Check auth.session for network errors. A failed verification preserves
the remembered account and its local work; confirmation of the same subject keeps
that work, while a different subject or confirmed sign-out retires it.
Browser focus and reconnect refresh the session when caching is enabled. See the cache reference for storage requirements and the consumer example.
Server rendering and hydration
Section titled “Server rendering and hydration”Default atoms render Initial on the server without fetching. For session-aware
rendering, use request-local atoms and registries; serialize only public session
data. Follow the hydration reference and
SSR example.
Use your Effect HttpClient
Section titled “Use your Effect HttpClient”Replace the default AuthAtom.make call with explicit Layer composition:
import { Layer } from "effect";
import { ApplicationHttpClient } from "./http-client";
export const ClientLive = AppClient.layer.pipe(Layer.provide(ApplicationHttpClient));export const auth = AuthAtom.make(AppClient, { layer: ClientLive });Your transport must send browser credentials, reject redirects, and disable retries and status filtering. Auth decodes expected failures from response bodies. A timeout may hide a committed mutation; follow the operation’s recovery flow rather than retrying it. See transport options for Fetch defaults, deadlines, and native clients.
Call the client directly
Section titled “Call the client directly”Provide layerFetch to a standalone Effect program:
import { Effect } from "effect";
import { AppClient } from "./auth-client";
export const session = Effect.gen(function* () { const client = yield* AppClient; return yield* client.auth.getSession();}).pipe(Effect.provide(AppClient.layerFetch));Use ClientLive instead for your own transport. To share the Atom client and its
account lifetime, compose through auth.runtime rather than acquiring another Layer.
Compose a passkey workflow
Section titled “Compose a passkey workflow”Use the contract and server setup from the passkey guide. The atom owns begin → browser prompt → complete, including cancellation:
import { Effect, Redacted } from "effect";import { Atom as AuthAtom, Client } from "@yielded/auth";import * as PasskeyBrowser from "@yielded/auth-simplewebauthn/Browser";
import { PasskeyApi } from "@app/domain/passkey-contract";
export const PasskeyClient = Client.make(PasskeyApi, { baseUrl: "https://app.example.com" });export const passkeys = AuthAtom.make(PasskeyClient);
export const signIn = passkeys.runtime.fn<{ flowId: string; commandId: string }>()( Effect.fn("app.passkeySignIn")(function* (input) { const client = yield* PasskeyClient; const browser = yield* PasskeyBrowser.make(); const started = yield* client.auth.signIn({ ...input, profileId: "default", }); const response = yield* browser.authenticate({ started, mediation: "required" });
return yield* client.auth.completeSignIn({ flowId: input.flowId, response: Redacted.value(response.response), }); }),);An account change retires this custom workflow, including when it completes sign-in. Render the updated session rather than chaining UI work after completion. Do not retry completion after an uncertain write; follow the server flow’s recovery policy.