Skip to content

Architecture

tRPC: a typed passthrough, not a second backend

Section titled “tRPC: a typed passthrough, not a second backend”

The frontend’s most important architectural fact: tRPC procedures are defined in this app, not in the Go API, and they contain no business logic. The tRPC layer (src/trpc/) is a thin, type-safe passthrough over the generated @huddlesurety/api SDK.

Each procedure declares its input as the SDK’s generated type and its handler just calls the matching SDK method:

export const bondRequestRouter = createTRPCRouter({
get: proc
.input(z.custom<GetBondRequestRequest>()) // type = SDK operation type
.query(({ input }) => api.bond.getBondRequest(input)),
create: proc
.input(z.custom<BondCreateRequestBody>())
.mutation(({ input }) => api.bond.createBondRequest(input)),
});

(This example used to call bondGetRequest / bondCreateRequest, names the SDK never had.) List procedures (*.list, auth.listInvite, organization.listChildren) are the one wrinkle: the SDK’s eight paged list methods return Speakeasy page iterators, so the handler returns the first page’s serializable result — { items, nextCursor } — and callers read .items. A request without limit gets every row (#208; see API › Paging and sorting).

Two procedures in bondRequest now do slightly more than one SDK call, and that is as far as it goes. If you read “no business logic” above as “exactly one SDK call per handler”, that was true until this week:

  • updateField saves the field, then lists and deletes the field’s bond_request_field_evidence rows (#229). Evidence became a resource of its own, and a manual edit makes the generated evidence stale. Only manual edits call this procedure.
  • findSpec returns null instead of throwing on a 404, so the spec editor can offer “create from the base spec” for an agency with no spec yet (#225).

The spec procedures (getSpec, findSpec, getBaseSpec, createSpec, #224) also declare a hand-written { orgID, bondType } input instead of the SDK operation type. Anything beyond this belongs in the API.

z.custom<T>() is a type-only assertion (no runtime schema) — the SDK types are the contract. Typesafety flows end to end:

graph LR
    A[Go handlers<br/>+ swag annotations] --> B[OpenAPI spec]
    B --> C["@huddlesurety/api<br/>generated types"]
    C --> D["z.custom&lt;SDKType&gt;()<br/>procedure input"]
    D --> E[AppRouter type]
    E --> F[createTRPCReact<br/>client hooks]

So tRPC here is a transport bridge, not a schema owner. Why have it at all? It gives the client React Query hooks, a single place to inject cookies and tracing, consistent error mapping, and SSE subscriptions — over an OpenAPI backend that otherwise wouldn’t offer them.

The SDK is configured with a custom fetcher (src/trpc/api.ts) that runs on the server and acts as a cookie + trace bridge:

  • Copies the incoming browser jwt cookie onto the outbound request to the Go API (API_URL).
  • Injects the W3C traceparent header (propagation.inject) so the app → api → rag trace stays connected, and tags the active span with the requester’s org.
  • Flushes any Set-Cookie the API returns (login/refresh JWT) back to the browser — in Route Handler / Server Action contexts; during SSR render, where cookies are read-only, it’s caught and ignored.

Two middlewares wrap every procedure (src/trpc/init.ts). errorMappingMiddleware catches an SDK HuddleAPIError and maps its HTTP statusCode to the equivalent TRPCError code (401→UNAUTHORIZED, 404→NOT_FOUND, …), taking the message from the message member of the API’s JSON error body rather than the SDK’s status-plus-raw-body string. On the client, isNotFoundError(err) checks error.data?.code === "NOT_FOUND". A separate isPrerenderAbort walks the error’s .cause chain for the Cache Components prerender-abort signal so those aren’t logged as real errors.

API messages in error toasts (#177). The tRPC errorFormatter adds data.apiMessage to the error shape, but only for 4xx HuddleAPIErrors: the API writes its 4xx messages for end users, while 5xx messages stay generic and never reach the client. Mutation hooks pass toastError(title) (src/lib/utils.ts) as the toast.promise error handler. It keeps the hook’s fixed title and shows apiMessage (read with apiErrorMessage in src/trpc/utils.ts) as the toast description when the error has one.

The client (src/components/providers.tsx) routes each operation over a splitLink: subscriptions use httpSubscriptionLink (SSE); everything else uses httpBatchLink with methodOverride: "POST" (paired with allowMethodOverride: true on the route handler). Batched query inputs are otherwise encoded into the GET URL, which on a multi-query refocus refetch can blow past Node’s 16 KB header limit and return HTTP 431 — so ordinary queries are sent as POST bodies. File uploads never cross tRPC: the tRPC layer creates the record and returns a presigned storage URL via a presign* query (upload: true); the browser PUTs the file straight to storage with uploadFile() (src/lib/utils.ts). Documents then send a JSON update that stamps uploadedAt. (This replaced the old non-JSON httpLink branch, #156.)

The transport URL is origin-relative, decoupled from any configured host: in the browser it’s "/api/trpc" (same-origin, so it works under any serving host), and during SSR it self-calls http://localhost:${PORT ?? 3000}/api/trpc. It no longer reads NEXT_PUBLIC_URL (which now only builds invite links).

The component library is Base UI (@base-ui/react). The design-system primitives live in src/components/ui/ and are composed with Tailwind v4 (via the PostCSS plugin — no tailwind.config), cva for variants, and cn() (twMerge + clsx).

The look is flat/sharp with a surface-elevation depth model: sharp or minimally-rounded borders, bg-popover/bg-primary/bg-secondary surface variables, and OKLCH color-mix for hover elevation. The primary color is injected per-organization in AppFrame via a --primary CSS variable.

Forms use TanStack Form, not react-hook-form (which isn’t a dependency). The pattern is centralized in src/components/ui/form.tsx, which wires the design-system fields to a useAppForm hook:

export const { useAppForm, withForm } = createFormHook({
fieldContext, formContext,
fieldComponents: { TextField, TextareaField, SwitchField },
formComponents: { SubmitButton },
});

Consumers call useAppForm(...) and render form.TextField, form.SwitchField, form.SubmitButton (which auto-disables until the form is dirty and valid, and shows a spinner while submitting). Passing an explicit disabled replaces that policy — e.g. disabled={!canSubmit} for a dialog whose seeded defaults are already a valid submission (complete-request-dialog.tsx). Field validity is read reactively via useSelector(field.store, …).

Server state is TanStack Query, accessed through the tRPC React hooks — suspense-first: data-owning components use useSuspenseQuery and self-wrap in Suspense with a co-located skeleton (see Style Guide › Data fetching). The main exception is client-only panels that never prerender — e.g. the bond editor tools — which use plain useQuery.

The agent bonds route is now live (its bid/final tables previously rendered a placeholder): each parallel @table slot calls useBondLog(bondType) (src/components/bond-log/filter.tsx), which runs bond.list.useSuspenseInfiniteQuery with limit: 50 and renders a BidBondTable / FinalBondTable with infiniteScroll (#210). It maps the URL to server filters: ?q= (written by a SearchInput) → the scalar search filter, ?contractor= → orgIDIn, each date param → a createdFrom/To, filedFrom/To or endFrom/To range, and ?sort= / ?order= → sort / order (see API › QUERY-method list endpoints). This paragraph used to point at useBondSearch as a client-side fallback for matching org names; both tables now pass ?q= to bond.list’s server-side search filter, and the unused hook was deleted in #181.

The @summary slot renders BondLogCharts (src/components/bond-log/charts.tsx), which replaced a placeholder chart. It landed in #204 as BondLogDashboard and was renamed in #205. Every figure is computed client-side from bond.list, organization.listChildren, and rate classes, and figures that depend on the clock wait for useMounted.

The bond log’s filters and sort live only in the URL (filter.tsx, #218/#220): ?contractor=, plus one param per date named after its BondSort key — ?createdAt= (“Date processed”), ?filedAt= (bid date, or contract start date on the final log), and ?endAt= (contract end date, final log only) — each holding a year, month or day such as 2026-03; sort is ?sort= / ?order=. Defaults (createdAt desc) and empty filters stay out of the URL. BondLogToolbar (a Filter popover and a Sort by menu) writes them with router.replace. The @table lists send them to the server as above; the charts still fetch the whole log with no limit and scope it client-side with filterBonds, and sort affects only the tables. This used to describe a ?contractor= / ?year= filter applied client-side to both the charts and the tables. Chart pieces that aren’t specific to the bond log (ChartCard, Legend, BarList, BoxPlot, MonthBars) live in src/components/chart/; put new reusable chart pieces there rather than in a feature folder.

Long, cursor-paged lists send limit: 50 and use useSuspenseInfiniteQuery (plain useInfiniteQuery only where the fetch waits on an interaction, like the audit-log drawer) with getNextPageParam: ({ nextCursor }) => nextCursor, and flatten the pages with flattenPages (src/lib/pagination.ts). Tables pass the query result to DataTable’s infiniteScroll prop; other lists (inbox, contractor requests, library grids) render <LoadMore {...query} /> (src/components/ui/load-more.tsx) after their items. Either way a sentinel loads the next page as it scrolls into view, so there are no page buttons. Pass getRowId so that row state such as an expanded renderExpanded row stays with its record as pages are appended. This used to name the agency audit log as the only user; since #208–#212 it also covers the inbox, contractor requests, bond log, contractors, members, invites, and library attachments and seals.

Ordering is the server’s job. Never toSorted an infinite list — that only reorders the pages loaded so far. Sortable tables pass DataTable a controlled sorting={{ value, onChange }} (which turns on single-column manualSorting); column ids are the API sort keys, and toSortParams(sorting, fallback) turns the state into { sort, order }. Seed it with the API default, and wrap onChange in startTransition so the old rows stay up while the new order loads. A new search or sort is new query input, so the list restarts at page 1. Layout prefetches use prefetchInfinite with the same input as the client query. Callers that need every row (charts, pickers, comboboxes) keep plain queries with no limit.

Mutations live in src/hooks/use-*-mutation.ts (one per domain), wrap trpc.*.useMutation(), usually surface a toast.promise(...) with a toastError(title) error handler, and invalidate related queries in onSuccess. Local UI state uses useState/context; cross-cutting UI state (breadcrumbs) uses a TanStack Store, read through useCrumbStore — its empty server snapshot keeps late-hydrating Suspense boundaries consistent with the SSR HTML, since crumbs are only set by client effects.

The bond form editor (src/components/bond-form/editor/) keeps its fields in a per-editor TanStack Store (store.ts). Edits apply locally right away, and each field syncs to the API after a 1 s debounce; new fields use a temp: id until the create returns. Since #174 a bond form can carry attachments: library PDFs (power of attorney, certificate of authority, notary form, other), stored as the form’s ordered attachments id array. The viewer shows the form followed by its attachments as one continuous document: mergePdfsFromUrls (src/lib/pdf.ts) concatenates the presigned PDFs and returns each source’s page count. Those counts become Segments (attachmentID?, offset, length). A field stores its page relative to its segment plus the attachmentID it sits on (none for the form’s own pages). toPageIndex / fromPageIndex convert between that anchor and the viewer’s absolute page index, so attaching, detaching, or reordering never renumbers existing fields. Since #232 the viewer is EmbedPDF 3 (@embedpdf/react), and one shared pdfEngine (localEngine(), PDFium in a Web Worker) handles page counts, merging and thumbnails. EmbedPDF 2 drew /Rotated pages sideways. The tools panel lists the org’s attachments per AttachmentType and toggles them onto the form. The attachment tRPC router replaced powerOfAttorney, and the library’s single /library/poa tab is now one tab per type.

Since #231, creating a bond form or replacing its PDF (useBondFormMutation().create / uploadDocument) also starts the fill workflow (bondForm.fill), fire-and-forget, wherever the upload happens (the initial request, the inbox, or the editor). A metadata-only update doesn’t. The chaining lives in the client hook, so tRPC is still a passthrough here. The editor’s button now reads “Re-run autofill”.

Bond request form: drawn from the agency’s spec

Section titled “Bond request form: drawn from the agency’s spec”

Since #224 the bond request form is no longer two hard-coded layouts (render/layouts/{bid,final}-bond-request.tsx are deleted). BondRequestLayout (src/components/bond-request/render/layout.tsx) draws the form from the agency’s bond request spec (one per agency and bond type; see API), and the same component renders the in-app form, the PDF and the editor preview. The contractor select and the bond forms table appear wherever the spec places a contractor_account or bond_forms section (#226).

Root-org users edit specs at /agencies/[agencyID]/spec/[bondType] (src/components/bond-request-spec/: draft, editor, inspector, outline; helpers in src/lib/bond-request-spec.ts). The editor auto-saves 800 ms after the last edit (SAVE_DELAY_MS, #227), one save at a time, and shows its status inline. That is why useBondRequestSpecMutation().update is a deliberate exception to the toast-on-mutation convention above.

Cache Components (CC) is enabled (cacheComponents: true). CC forbids unstable values (like Date.now()) during prerender, so the app has a few deliberate, documented workarounds:

  • tRPC hydration — a custom HydrateClient (src/trpc/server.tsx) hydrates via a childless sibling <Hydrate/> behind Suspense + connection(), so dehydrate()’s internal Date.now() is deferred to request time and children still prerender statically.
  • Relative timestamps — <TimeAgo> uses the shared useMounted hook (useSyncExternalStore with a false server snapshot) to render nothing on the server and only compute the relative time after mount; the absolute ISO date stays in the prerendered HTML.
  • Route params in layouts — useParams() is runtime data. A crumb or other client component mounted from a layout.tsx must read it behind <Suspense>, or prerendering every nested route fails. agencies/layout.tsx broke the staging build this way until #225 wrapped its <Crumb />, matching the inbox, projects and requests crumbs.
  • Tables — the live DataTable uses useReactTable, but DataTableSkeleton (rendered in loading.tsx) derives columns directly to avoid useReactTable’s internal Date.now() during prerender.
  • Persisted layout state (#170) — the app sidebar’s open state (the sidebar_state cookie) and the inbox list/detail split (localStorage) are only readable on the client, so the prerendered shell always renders the defaults. To avoid a snap after hydration, each emits a tiny inline script (via dangerouslySetInnerHTML on a hidden wrapper) that runs during HTML parsing. The sidebar’s script stamps the collapsed data-state onto the sidebar element. The inbox layout’s script injects a temporary flex override that is removed once the panel group reports data-layout-ready. AppFrame also writes the role-derived sidebar default to the cookie on first visit, so the next hard load already matches.

Prefetch/hydration model:

  • getQueryClient() returns one client per request on the server (so RSC prefetch matches what client components read) and a singleton on the client.
  • Layouts prefetch shared queries fire-and-forget and never throw on auth — trpc.auth.session().catch(() => null) — so an unauthenticated shell still renders.
  • Pages read their data with useSuspenseQuery and suspend into their own loading.tsx. Parallel routes (@slot folders) each own their fetch and boundary.
  • ReactQueryStreamedHydration (in providers.tsx) streams queries resolved during the SSR pass into the client cache, using the query client’s superjson dehydrate/hydrate options. This covers the gap HydrateClient can’t: HydrateClient transfers RSC-layer prefetches, while client components’ useSuspenseQuery fetches happen in the separate SSR pass — the two module graphs don’t share a query client. Without the streamed transfer those fetches were discarded (double fetch on the client) and data seeded by a sibling route could render into SSR HTML the client cache didn’t have — a hydration mismatch.

Long-running backend workflows (parse document, generate field, fill form, find bond, process request) report progress to the UI via tRPC subscriptions over SSE. The app no longer polls the Go API once per second; instead it consumes the API’s …/watch SSE routes, which push a bare WorkflowStatus string whenever it changes.

That consumption is server-only. src/trpc/watch.ts (marked import "server-only") holds the generators — split out of src/trpc/utils.ts so client bundles never pull them in:

  • parseSSE(body) — parses the SSE byte stream, yielding data: payloads and skipping heartbeat/comment lines.
  • watchStatus(path, signal) — consumes one watch route. It requests accept: text/event-stream, surfaces a failed connect (401/403), reconnects after 1s if the stream drops, and dedups identical consecutive statuses.
  • watchStatusMap(pathFor, ids, signal) — opens one watchStatus connection per id, merges them into a Record<id, WorkflowStatus>, and emits the full map once every id has reported and again on any change.

The watch route paths are the single place they’re spelled — typed helpers at the bottom of watch.ts (watchParseStatuses, watchGenerateFieldStatuses, watchFillFormStatuses / watchFillFormStatus, watchFindBondStatus, watchProcessRequestStatus) — because Speakeasy gates SSE (serverEvents) generation behind its business tier, so the SDK ships no client for these routes (the API side also marks them x-speakeasy-ignore).

  • JWT cookie (jwt), verified locally with jose (HS256, JWT_SECRET) in src/lib/session.ts. verifySession returns SessionClaims (userID, orgID, orgType) or undefined — it no longer inspects the JWT purpose claim (the API now enforces purpose at the signature layer via per-purpose signing keys, so a session cookie simply verifies against the raw secret). This is treated as identity hints for UX only — the Go API is the security boundary.
  • Role gating lives in the Next middleware (src/proxy.ts), driven by the nav map in src/pages.ts. It reads orgType from the JWT, redirects / to the role’s home, and rewrites wrong-role paths to a 404 (preserving the URL). A path listed under multiple roles (e.g. /requests/new) admits all of them.