@dolfinai/react
v0.4.0
Published
React SDK for Dolfin: DolfinProvider, headless hooks for accounts payable, accounts receivable and expenses, and server helpers for token and proxy auth.
Maintainers
Readme
@dolfinai/react
The hook and provider package of the Dolfin SDK: DolfinProvider, core hooks, and
module hooks for accounts payable, accounts receivable and expenses. The SDK also
includes connected components, distributed as editable shadcn registry source.
Standalone registry ui-* components are the presentation layer. They require no
SDK/provider and receive explicit props and callbacks. Connected registry entries
compose that UI with this package's finance logic; npm component imports have not
been introduced.
- Docs and component explorer: https://dolfin-sdk-explorer.vercel.app
- Go live in a day (token route, provider, first pages, with a prompt for your coding agent): https://dolfin-sdk-explorer.vercel.app/start
- Ready-made screens: the
@dolfinshadcn registry,https://registry.dolfinai.co/r/{name}.json(connected items depend on this package; pureui-*items do not)
Install
npm install @dolfinai/react
# or: pnpm add @dolfinai/react / bun add @dolfinai/reactIt brings @dolfinai/sdk-core and @dolfinai/api-schema with it; you never install them yourself. Peer dependencies: react and react-dom 19. ESM only; server code needs Node 20.9 or later.
| Import | Where |
| --- | --- |
| @dolfinai/react | Client code: the provider, core hooks and the framework-agnostic helpers. Marked "use client". |
| @dolfinai/react/ap, /ar, /expenses | Client code: the module hooks. Marked "use client". |
| @dolfinai/react/server | Server code only (route handlers, server components, jobs): it holds your API key. No React. |
API environment and existing organisations
Omitting both baseUrl and environment defaults to the production API, https://api.dolfinai.co. baseUrl takes precedence. environment: "sandbox" uses the same hostname: isolation comes from the Dolfin client/organisation type, not another API host. It does not select staging. Use an explicitly supplied staging URL with matching credentials when applicable. Set the API URL explicitly and confirm the client is Sandbox before test writes.
Server/authentication guide and existing-organisation examples. Existing mapped members can use issueToken; the restricted proxy supports an existing organisation without creating users. createDolfinTokenRoute intentionally resolves/provisions organisations and users through connect.
Quick start
import { DolfinProvider } from "@dolfinai/react";
<DolfinProvider auth={{ mode: "token", fetchToken, userId }} organisationId={orgId} baseUrl={apiUrl}>
<App />
</DolfinProvider>;The provider owns its own TanStack Query client. It never mounts QueryClientProvider, so host components inside it keep using the host's client and cache.
Authentication
Two modes:
- Token (
{ mode: "token", fetchToken, userId, cache? }): the browser sends a Dolfin bearer token.fetchToken({ userId })calls your backend, which mints a code with its API key (/v1/auth/codes), exchanges it (/v1/auth/exchange) and returns theAuthResponse. The SDK renews the token 60s before it expires, retries a request once after a 401, and drops the token synchronously whenuserIdchanges or becomes undefined (sign out). - Proxy (
{ mode: "proxy", identity? }): your backend forwards requests to Dolfin and addsx-dolfin-api-key. The SDK sends no credentials.
Your server: @dolfinai/react/server
The backend half of both modes, with no React and no framework (it takes a Request and returns a Response, so the route helpers mount as Next.js App Router handlers as they are). Server only: it holds your API key. It also re-exports the framework-independent helpers (toNumber, formatMoney, dolfinRoutePath, DolfinError, ...) under the same names as @dolfinai/react, so server components never import client code.
import { createDolfinServer, createDolfinTokenRoute } from "@dolfinai/react/server";
const apiKey = process.env.DOLFIN_API_KEY?.trim();
const baseUrl = process.env.DOLFIN_API_URL?.trim();
if (!apiKey || !baseUrl) throw new Error("Set DOLFIN_API_KEY and DOLFIN_API_URL explicitly");
const dolfin = createDolfinServer({ apiKey, baseUrl, roles: { "Finance manager": "Admin" } });
// app/api/dolfin/token/route.ts: your session decides who the user is; ids from the browser are ignored.
export const GET = createDolfinTokenRoute({ dolfin, getSession: async () => toDolfinSession(await getCurrentUser()) });| Export | What |
| --- | --- |
| createDolfinServer({ apiKey, baseUrl?, environment?, roles?, defaults?, store?, fetch? }) | connect(session) ensures the organisation (by your externalOrgId) and the member (by email, with the mapped role) and returns { organisationId, userId, role }; also ensureOrganisation, ensureUser, issueToken, setRole, removeUser. Ids and the last role are cached 10 minutes in memory, or kept in your store; a changed role is re-applied on the next connect. |
| dolfin.client({ organisationId, userId? }) | A typed client for server components and jobs: as the user (a token kept per process) with userId, as the API key without. Read on the server, pass the data to a block. |
| createDolfinTokenRoute({ dolfin, getSession }) | Token mode's route: 401 without a session, a fresh AuthResponse with one. getSession returns null when signed out; never a helper that redirects. Pair it with fetchTokenFrom(url) from @dolfinai/react. |
| createDolfinProxy({ dolfin, getSession, authorize, organisationId? }) | Proxy mode's route: signs the user in first, resolves the organisation on the server, checks authorize, drops inbound credentials, forwards /v1/... only (never /v1/auth/...). authorize is required. |
| allowRoles(roles?), readOnly(), classifyDolfinRequest(method, path), DOLFIN_PROXY_ROLES | Proxy policies. Each request is one of read, edit, approve, pay, invoice, manage; allowRoles() applies Dolfin's role rules to the mapped role (override per kind), readOnly() forwards reads only. |
| mapRole(hostRole, mapping?), DEFAULT_ROLE_MAPPING | Your roles to Member, Admin or Owner; anything unmatched is Member. |
| DEFAULT_INDUSTRY_ID | Dolfin's "Miscellaneous business services", used when a new organisation has no industry. |
Token caching: cache
Without a cache, every page load calls fetchToken before its first Dolfin request. With cache, the latest AuthResponse is kept between page loads, so the first request goes out at once with the cached token when it is still more than 60s from expiry.
<DolfinProvider auth={{ mode: "token", fetchToken, userId, cache: "session" }}>"session":sessionStorage(this tab, until it closes)."local":localStorage(every tab, until it expires or the user signs out).- A custom store:
{ get(key): string | null; set(key, value): void; remove(key): void }.
Entries are keyed by backend URL and userId, so one user never gets another's token. An entry is removed when userId changes or is cleared, when a refresh fails, and when the backend answers 401 to it. Unmounting the provider keeps the entry, so on sign out set userId to undefined before you unmount it. Storage is only touched in the browser, when a token is first needed, so server rendering and hydration are unaffected. Blocked or full storage falls back to no cache.
Security: the cache is off by default. A token in Web Storage can be read by any script running on your origin, so an XSS bug would expose it for the token's lifetime. Turn it on only if you accept that, and prefer "session" over "local".
Writing hooks: useDolfinQuery and useDolfinMutation
useDolfinQuery({
queryKey: (keys) => keys.ap.bills.list(filters),
queryFn: ({ client, scope, keys, queryKey, signal }) => unwrap(client.GET("/v1/bills", { signal })),
});
useDolfinMutation({
mutationFn: (billId: string, { client, scope, keys, signal }) =>
unwrap(client.POST("/v1/bills/{billId}/approve", { params: { path: { billId } } })),
invalidates: (keys) => [keys.ap.bills.all],
event: (_, billId) => ({ type: "bill.approved", payload: { billId } }),
});Every query key starts with the scope ["dolfin", envId, principalId, organisationId]. A scope is one backend, one user and one organisation. The fn's client is pinned to scope, which is the scope at dispatch:
- Every request it sends carries the captured organisation, even after the user switches organisation.
- A request is refused with
Dolfin.ScopeChangedand never sent if the provider no longer shows that scope. That covers a different organisation, user or backend. The check runs when the request is dispatched, after it waits for a token, and before a 401 replay. - Refusals for a scope that is gone are silent: no
onError, no error state. A mutation whose scope came back gets a real error that says nothing was saved. - For a mutation,
signalaborts (reasonDolfin.ScopeChanged) when the provider moves to another scope. Pass it to polling and delays. If you pass it to a write, the client stops waiting for the answer, but the server may still apply the write.
Rule for module hooks
Module hooks MUST send requests through ctx.client. Inside a query or mutation fn, never use useDolfinClient() or useDolfinAuth().authFetch.
The provider's client always follows the current organisation. A fn that awaits something before its first request would send that request to whichever organisation is current at that moment. useDolfinClient() is only for work that is not a query or a mutation, such as an SSE stream that manages its own lifecycle.
The package tests enforce this rule with a source lint: a file that calls useDolfinQuery or useDolfinMutation may not also call useDolfinClient().
Changelog and licence
See CHANGELOG.md and LICENSE.
