dolfindevelopers
SDK AUTHENTICATION

Connect to Dolfin

Connected components and hooks use DolfinProvider. Choose user-token authentication or a server proxy. Standalone UI needs neither.

Before you begin, install @dolfinai/react with bun add @dolfinai/react (or npm install @dolfinai/react / pnpm add @dolfinai/react). The route examples below use Next.js App Router; adapt the server handlers and provider placement to your framework.

Choose the API environment explicitly

The SDK defaults to production: omitting both baseUrl and environment sends requests to https://api.dolfinai.co. An explicit baseUrl takes precedence. The examples below refuse to start without DOLFIN_API_URL.

environment: "sandbox" uses the same API hostname as production. Sandbox isolation comes from the Dolfin client and organisation type, not the URL. Confirm your credentials and organisation are Sandbox before testing writes. The separately supplied staging API is selected only with its explicit baseUrl and matching credentials; "sandbox" does not select staging. "local" resolves to http://localhost:5000.

.env.local
# Set the API URL and matching credentials supplied by Dolfin.
# This hostname serves both Live and Sandbox clients.
DOLFIN_API_URL=https://api.dolfinai.co
DOLFIN_API_KEY=your_server_only_api_key

Keep this file uncommitted. Pass the non-secret API URL to the client provider; never expose the API key with a NEXT_PUBLIC_ prefix.

Map your authenticated host session

Your existing authentication supplies getHostSession(request) from lib/auth.ts. Validate the session and current workspace membership on the server; return null when signed out, rather than redirecting. Export this type alongside your implementation:

lib/auth.ts — session contract
export type HostSession = {
  user: { id: string; email: string; name: string; role?: string; dolfinId?: string };
  organisation: { id: string; name: string; dolfinId?: string };
};

The id fields are your application's identities. The optional dolfinId fields are actual Dolfin IDs from your trusted server-side mapping. Do not derive that mapping from browser headers, URL parameters or form fields. Send only the authenticated session's public IDs to the provider.

01Configure the server SDK

lib/dolfin-server.ts
import "server-only";
import { createDolfinServer, type DolfinSession } from "@dolfinai/react/server";
import type { HostSession } from "@/lib/auth";

const apiKey = process.env.DOLFIN_API_KEY?.trim();
export const apiUrl = process.env.DOLFIN_API_URL?.trim();
if (!apiKey || !apiUrl) throw new Error("Set DOLFIN_API_KEY and DOLFIN_API_URL explicitly");
export const dolfin = createDolfinServer({
  apiKey, baseUrl: apiUrl,
  roles: role => role === "finance-admin" ? "Admin" : "Member",
});
export const toDolfinSession = (session: HostSession): DolfinSession => ({
  externalOrgId: session.organisation.id,
  orgName: session.organisation.name,
  email: session.user.email,
  name: session.user.name,
  role: session.user.role,
});

The role mapping applies only to roles from your authenticated host session. Unmapped roles resolve to Member. API configuration is explicit, shared by server and browser, and fails closed when missing.

Use an existing Dolfin organisation and member

When the organisation and user already exist in Dolfin, store their IDs on your host workspace and user membership records. Use this route at app/api/dolfin/token/[user]/[organisation]/route.ts. It uses the supported issueToken API and checks the returned membership; it does not call connect, create an organisation, add a user or change a role.

app/api/dolfin/token/[user]/[organisation]/route.ts — existing IDs
import "server-only";
import { getHostSession } from "@/lib/auth";
import { dolfin } from "@/lib/dolfin-server";

export const dynamic = "force-dynamic";
const answer = (status: number, title: string) =>
  Response.json({ title }, { status, headers: { "Cache-Control": "no-store" } });
export async function GET(request: Request) {
  if (request.headers.get("sec-fetch-site") === "cross-site") return answer(403, "Cross-site request refused");
  const session = await getHostSession(request);
  if (!session) return answer(401, "Sign in first");
  const path = "/api/dolfin/token/" + encodeURIComponent(session.user.id) +
    "/" + encodeURIComponent(session.organisation.id);
  if (new URL(request.url).pathname !== path) return answer(409, "Session changed");
  const userId = session.user.dolfinId;
  const organisationId = session.organisation.dolfinId;
  if (!userId || !organisationId) return answer(409, "Link this host user and organisation to Dolfin first");
  try {
    const auth = await dolfin.issueToken({ userId });
    if (auth.userId !== userId || !auth.organisations.some(org => org.organisationId === organisationId))
      return answer(403, "The user is not a member of this Dolfin organisation");
    return Response.json(auth, { headers: { "Cache-Control": "no-store" } });
  } catch {
    return answer(502, "Dolfin could not issue a token");
  }
}

If only the organisation exists, provision the user deliberately during onboarding with dolfin.ensureUser({ organisationId, email, name, role }), using your server-owned mapping and authorised role, then persist the returned user ID. This can create a membership or synchronise its role; keep it separate from token renewal. Alternatively use the existing-organisation proxy below, which needs no per-user Dolfin token.

Let Dolfin resolve or provision organisations and users

Choose this alternative only when you want SDK-managed onboarding. createDolfinTokenRoute calls connect: it resolves or creates the organisation by your host external reference, ensures the member and synchronises the mapped role. A host workspace ID is not an existing Dolfin organisation ID. Use the existing-ID route above when you must avoid provisioning.

app/api/dolfin/token/[user]/[organisation]/route.ts — managed alternative
import "server-only";
import { createDolfinTokenRoute } from "@dolfinai/react/server";
import { getHostSession } from "@/lib/auth";
import { dolfin, toDolfinSession } from "@/lib/dolfin-server";

export const dynamic = "force-dynamic";
export async function GET(request: Request) {
  if (request.headers.get("sec-fetch-site") === "cross-site")
    return Response.json({ title: "Cross-site request refused" }, { status: 403 });
  const session = await getHostSession(request);
  if (!session) return Response.json({ title: "Sign in first" }, { status: 401 });
  const path = "/api/dolfin/token/" + encodeURIComponent(session.user.id) +
    "/" + encodeURIComponent(session.organisation.id);
  if (new URL(request.url).pathname !== path)
    return Response.json({ title: "Session changed" }, { status: 409 });
  return createDolfinTokenRoute({
    dolfin,
    getSession: () => toDolfinSession(session),
  })(request);
}

During your authenticated onboarding, call await dolfin.connect(toDolfinSession(session)) and persist its organisationId and userId in your server mapping before rendering finance pages. This operation can create records. The SDK's default ID cache is process-local; a durable DolfinIdStore can store these mappings across server instances. Do not select an arbitrary first organisation from a user's memberships.

02Wrap your authenticated finance page

components/finance-token-provider.tsx
"use client";
import { DolfinProvider, fetchTokenFrom } from "@dolfinai/react";
import type { ReactNode } from "react";

export function FinanceTokenProvider({ hostUserId, hostOrganisationId, dolfinOrganisationId, apiUrl, children }: {
  hostUserId: string;
  hostOrganisationId: string;
  dolfinOrganisationId: string;
  apiUrl: string;
  children: ReactNode;
}) {
  const tokenUrl = "/api/dolfin/token/" + encodeURIComponent(hostUserId) + "/" + encodeURIComponent(hostOrganisationId);
  return (
    <DolfinProvider
      key={apiUrl + ":" + hostUserId + ":" + hostOrganisationId + ":" + dolfinOrganisationId}
      baseUrl={apiUrl}
      organisationId={dolfinOrganisationId}
      auth={{ mode: "token", userId: hostUserId, fetchToken: fetchTokenFrom(tokenUrl) }}
      onError={error => { if (error.status === 401 || error.status === 409) window.location.reload(); }}
    >{children}</DolfinProvider>
  );
}
app/finance/page.tsx
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { getHostSession } from "@/lib/auth";
import { apiUrl } from "@/lib/dolfin-server";
import { FinanceTokenProvider } from "@/components/finance-token-provider";
import { ApBillsTable } from "@/components/dolfin/ap/bills-table";

export default async function FinancePage() {
  const session = await getHostSession(new Request("https://host.invalid", { headers: await headers() }));
  if (!session) redirect("/login");
  if (!session.user.dolfinId || !session.organisation.dolfinId)
    return <p>Link this user and organisation to Dolfin before continuing.</p>;
  return (
    <FinanceTokenProvider hostUserId={session.user.id} hostOrganisationId={session.organisation.id}
      dolfinOrganisationId={session.organisation.dolfinId} apiUrl={apiUrl!}>
      <ApBillsTable />
    </FinanceTokenProvider>
  );
}

Install @dolfin/ap-bills-table using the component quickstart first. Your app owns /login and the authenticated session. The token URL pins the expected host user and workspace; a stale tab gets 409 before issuing a token. Refreshing the host session remounts the provider with the current IDs. Add navigation and notification adapters as your application grows.

03Check it works

connection-check.tsx
import { useBills } from "@dolfinai/react/ap";

export function ConnectionCheck() {
  const { bills, isLoading, error } = useBills({ pageSize: 1 });
  if (isLoading) return <p>Connecting…</p>;
  if (error) return <p>Not connected: {error.message}</p>;
  return <p>Connected. {bills?.length ?? 0} bill(s) on the first page.</p>;
}

If bills appear, you are connected. From here, go to install a connected component or use a hook.

Read-only proxy for an existing organisation

Use this Next.js App Router example to read an existing Dolfin organisation through your authenticated application. Your API key stays on the server. The explicit organisation mapping avoids creating organisations or users during setup.

Your application provides getHostSession(request) in lib/auth.ts. It must validate the signed-in session and organisation membership, return null when signed out, and resolve this server-owned shape for an already linked organisation:

host-session.ts
type HostSession = {
  user: { id: string; email: string; name: string };
  organisation: { id: string; name: string; dolfinId: string };
};

The host organisation ID identifies your workspace. dolfinId is its existing Dolfin organisation ID, loaded from your server-side mapping. Never accept that mapping or permissions from browser input.

Use the explicit server API configuration above. The proxy snippet also refuses missing credentials or API URL.

app/api/dolfin/[...path]/route.ts
import "server-only";
import { createDolfinProxy, createDolfinServer, readOnly } from "@dolfinai/react/server";
import { getHostSession } from "@/lib/auth";

export const dynamic = "force-dynamic";
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 on the server");
const dolfin = createDolfinServer({ apiKey, baseUrl });
const deny = (status: number, title: string) =>
  Response.json({ title }, { status, headers: { "Cache-Control": "no-store" } });

async function handle(request: Request) {
  const session = await getHostSession(request);
  if (!session) return deny(401, "Sign in first");
  const dolfinOrganisationId = session.organisation.dolfinId;
  if (!dolfinOrganisationId) return deny(409, "Link this organisation to Dolfin first");
  const prefix = "/api/dolfin/scope/" + encodeURIComponent(session.user.id) +
    "/" + encodeURIComponent(session.organisation.id) + "/v1/";
  if (!new URL(request.url).pathname.startsWith(prefix))
    return deny(409, "Session changed; refresh your host session");

  const proxy = createDolfinProxy({
    dolfin,
    getSession: () => ({
      externalOrgId: session.organisation.id,
      orgName: session.organisation.name,
      email: session.user.email,
      name: session.user.name,
      role: "Member",
    }),
    // Resolve this mapping on your server after checking membership.
    organisationId: () => dolfinOrganisationId,
    authorize: async request => (await readOnly()(request)) === true &&
      /^\/v1\/(bills|suppliers|invoices|customers|expenses)(?:\/|$)/.test(request.path),
  });
  const response = await proxy(request);
  response.headers.set("Cache-Control", "no-store");
  return response;
}

export { handle as GET, handle as HEAD, handle as POST,
  handle as PUT, handle as PATCH, handle as DELETE };

Mount the provider below your authenticated host session. Pass its user ID, host organisation ID and server-resolved Dolfin organisation ID as separate values. Implement refreshSession to clear the old session view, reload the authenticated session and unmount this provider when signed out. A stale tab receives 409 before any upstream request.

finance-provider.tsx
"use client";
import { DolfinProvider } from "@dolfinai/react";
import type { ReactNode } from "react";

export function FinanceProvider({ userId, hostOrganisationId, dolfinOrganisationId, refreshSession, children }: {
  userId: string;
  hostOrganisationId: string;
  dolfinOrganisationId: string;
  refreshSession: () => void;
  children: ReactNode;
}) {
  return (
    <DolfinProvider
      key={userId + ":" + hostOrganisationId + ":" + dolfinOrganisationId}
      baseUrl={"/api/dolfin/scope/" + encodeURIComponent(userId) + "/" + encodeURIComponent(hostOrganisationId)}
      organisationId={dolfinOrganisationId}
      auth={{ mode: "proxy", identity: { userId, role: "Member", modules: ["ap", "ar", "expenses"] } }}
      onError={error => { if (error.status === 401 || error.status === 409) refreshSession(); }}
    >
      {children}
    </DolfinProvider>
  );
}

Render ApBillsTable or the connection check above inside FinanceProvider. The starter proxy permits reads only for bills, suppliers, invoices, customers and expenses; other paths and mutation actions receive 403. Keep organisation-directory, identity and client-administration routes closed. Expand this allowlist only for the resources your application needs; organisation IDs in any newly permitted URL paths must match the authenticated server mapping. Client roles describe presentation, while the server policy enforces access. For writes, define a server authorisation policy for your product or use user-token mode, where Dolfin enforces the user's permissions.

Try it in the browser first