appflare-client
Use the Appflare generated client in frontends, including creating new Appflare() with endpoint, wsEndpoint and bearer-token storage, calling appflare.queries/appflare.mutations with .run() and { data
SKILL.mdskills/appflare-client/SKILL.md
GitHubAppflare client
Workflow
- Find the generated client:
<backend package>/_generated/client, ordist/_generated/clientwhen the backend builds withtsc - Create one shared client module (e.g.
lib/appflare.ts) - Wrap the React tree in
AppflareQueryProvider(or TanStack'sQueryClientProvider) - Call routes through
appflare.queries.*andappflare.mutations.*. Names mirror handler file paths - After backend changes, run
bun appflare devin the backend so the client types update
Shared client
// lib/appflare.ts
import { Appflare } from "my-backend/_generated/client";
export const appflare = new Appflare({
endpoint: import.meta.env.VITE_API_URL, // e.g. http://localhost:8787
wsEndpoint: import.meta.env.VITE_API_WS_URL, // e.g. ws://localhost:8787 (needed for realtime)
onGetAuthToken: () => localStorage.getItem("appflare-token") ?? "",
onSetAuthToken: (token) => localStorage.setItem("appflare-token", token),
});
For React Native, store the token with AsyncStorage or SecureStore. On the Android emulator, use http://10.0.2.2:8787 instead of localhost.
Plain calls
const { data, error } = await appflare.queries.tasks.listTasks.run({ projectId, limit: 20 });
if (error) throw new Error(`${error.status} ${error.message}`);
await appflare.mutations.tasks.completeTask.run({ id: 42 });
React
// App root: cache persisted across reloads, shown before the network answers
import { AppflareQueryProvider, createAppflareQueryClient } from "appflare/react";
const queryClient = createAppflareQueryClient();
<AppflareQueryProvider client={queryClient} persist={{ storage: localStorage }}>
<App />
</AppflareQueryProvider>;
import { useMutation, useQuery } from "appflare/react";
import { appflare } from "../lib/appflare";
const listTasks = appflare.queries.tasks.listTasks;
export function Tasks({ projectId }: { projectId: string }) {
const tasks = useQuery(listTasks, { projectId }, {
realtime: { enabled: true },
});
const complete = useMutation(appflare.mutations.tasks.completeTask, {
// Typed from the routes; rolled back automatically if the mutation fails.
optimistic: ({ id }, cache) =>
cache.update(listTasks, (list) =>
list.map((t) => (t.id === id ? { ...t, done: true } : t)),
),
});
if (tasks.isLoading) return <p>Loading…</p>;
if (tasks.error) return <p>{tasks.error.message}</p>;
return tasks.data?.map((t) => (
<button key={t.id} onClick={() => complete.mutate({ id: t.id })}>{t.title}</button>
));
}
Optimistic and cache rules:
optimistic(args, cache)runs before the request. Its writes survive refetches and realtime pushes while pending, roll back on error, and the touched queries refetch once it settles (reconcile: falseto skip).updateCache(result, args, cache)writes the server response;invalidates: [route]refetches routes after success.useAppflareCache()gives the same typedcacheanywhere:get,set,update,getInfinite,updateInfinite,updatePages,invalidate,optimistic.cache.update(route, updater)changes every cached args variant;cache.update(route, args, updater)only one. UseupdatePages/updateInfiniteforuseInfiniteQuerydata.- Persistence saves server data only, never pending optimistic writes. Bump
persist.busterwhen cached data shapes change.
Auth
await appflare.auth.signUp.email({ email, password, name });
await appflare.auth.signIn.email({ email, password }); // token stored via onSetAuthToken
await appflare.auth.signOut(); // then clear your stored token
The server needs Better Auth's bearer() plugin so responses include set-auth-token.
Gotchas
run()returns{ data, error }for HTTP failures and doesn't throw. It does throw aZodErrorif the args fail the route schema on the client.- Hooks throw
Errorobjects that carry astatusproperty, so use TanStack'serrorstate. - A
Datereturned by a handler arrives as an ISO string, even though the type saysDate. - Query args go in the URL, and the server converts them to the handler's arg types, so numbers, booleans, arrays and objects work without client-side tricks.
- A route whose handler takes no args (
args: {}) is callable with no arguments:route.run()anduseQuery(route). - Unhandled server errors return
{ message: "Internal error", requestId }. Showerror.messagefor expected failures (ctx.error) and log therequestIdotherwise. Constraint failures carry acodesuch asunique_violationinerror.body. - Realtime needs
wsEndpoint.subscribe()only pushes changes; hooks load initial data for you. useInfiniteQueryrealtime pushes replace only the first page.route.queryKey()with no args matches all cached variants, which makes it a good key for invalidation.clientOptionsinappflare.config.tsonly typesappflare.auth. Pass runtime Better Auth client plugins throughnew Appflare({ authOptions: { plugins: [...] } }).appflare.storage.download()expects JSON but the route streams bytes. Usestorage.preview({ path })as a URL instead.
References
- Read references/react-hooks.md when you need hook options (queryOptions, requestOptions, realtime callbacks), infinite pagination, the full optimistic/cache API, persistence options (AsyncStorage,
maxAge,buster,shouldPersist), or client types such asInferRouteInput,InferRouteOutputandInferQueryData. - Read references/auth.md when implementing sign-in or sign-up, OTP or admin client plugins, token storage, role-aware UI, or storage uploads from the client.