Catalog My learning Blog
Micro-Frontends, BFF and tRPC: Full-Stack TypeScript Project · Phase 3 · Lesson 5 · 5 min read

Typed Micro-Frontends with tRPC and TanStack Query

On this page
  1. Each micro-frontend brings its own client
  2. The client setup
  3. Mounting with providers
  4. The screen
  5. What the types catch
  6. Check yourself

Each micro-frontend brings its own client

In a single app, there's one tRPC client and one TanStack Query QueryClient at the root. With micro-frontends, the question is whether the shell should create them and hand them down, or each micro-frontend should create its own.

TaskBoard gives each micro-frontend its own, created in mount and thrown away in unmount:

  • Each team picks its own tRPC and TanStack Query versions and upgrades on its own schedule.
  • Each micro-frontend has its own React root, so a provider from the shell wouldn't reach it anyway.
  • A cache that dies on unmount can't leak one area's data into another.

The cost is a duplicate client library per micro-frontend, about 27 KB gzipped each in this project, and no cache sharing between areas. For two to five micro-frontends that's a good trade. Day 9 discusses moving the libraries into the import map if it stops being one.

The client setup

Each micro-frontend has a small trpc.ts:

TypeScript
// packages/mfe-tasks/src/trpc.ts
import { createTRPCClient, httpBatchLink, httpSubscriptionLink, splitLink } from '@trpc/client';
import { createTRPCContext } from '@trpc/tanstack-react-query';
import superjson from 'superjson';
import type { AppRouter } from '@taskboard/bff/router';
import { CSRF_HEADER, sessionLink } from '@taskboard/contract';

export const { TRPCProvider, useTRPC } = createTRPCContext<AppRouter>();

export function makeClient() {
  return createTRPCClient<AppRouter>({
    links: [
      sessionLink<AppRouter>(),                                     // Day 6
      splitLink({
        condition: (op) => op.type === 'subscription',
        true: httpSubscriptionLink({ url: '/trpc', transformer: superjson }),
        false: httpBatchLink({ url: '/trpc', transformer: superjson, headers: () => CSRF_HEADER, maxItems: 10 }),
      }),
    ],
  });
}

Three details tie it to the BFF:

  • Relative URLs. /trpc on the same origin, so the browser sends the session cookie and no CORS is needed.
  • CSRF_HEADER from the contract package on every batch request. The subscription link can't send headers, which is why the BFF's CSRF rule has its narrow SSE exception (Day 3).
  • maxItems: 10 matches the BFF's maxBatchSize: 10, so a busy screen splits its calls instead of getting a 400.

Mounting with providers

mount creates the clients and wraps the screen in the providers:

Shell
// packages/mfe-tasks/src/index.tsx
export const mount: Mount = (el) => {
  const queryClient = new QueryClient();
  const trpcClient = makeClient();
  const root = createRoot(el);
  root.render(
    <QueryClientProvider client={queryClient}>
      <TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
        <Tasks />
      </TRPCProvider>
    </QueryClientProvider>,
  );
  return () => { root.unmount(); queryClient.clear(); };
};

queryClient.clear() on unmount drops the cached tasks, which also stops any background refetching for a screen nobody is looking at.

The screen

Inside, it's the TanStack Query integration from the tRPC course, now checked against the BFF's real router:

TypeScript
function Tasks() {
  const trpc = useTRPC();
  const queryClient = useQueryClient();
  const [title, setTitle] = useState('');

  const tasks = useQuery(trpc.tasks.list.queryOptions());
  const create = useMutation(trpc.tasks.create.mutationOptions({
    onSuccess: () => {
      setTitle('');
      return queryClient.invalidateQueries({ queryKey: trpc.tasks.list.queryKey() });
    },
  }));

  if (tasks.isPending) return <p>Loading tasks…</p>;
  if (tasks.isError) return <p role="alert">{tasks.error.message}</p>;

  return (
    <section data-mfe="tasks">
      <h2>Your tasks</h2>
      <form onSubmit={(e) => { e.preventDefault(); create.mutate({ title }); }}>
        <input aria-label="New task" value={title} onChange={(e) => setTitle(e.target.value)} />
        <button disabled={create.isPending}>Add</button>
      </form>
      {create.error?.data?.fieldErrors?.title && <p role="alert">{create.error.data.fieldErrors.title[0]}</p>}
      <ul>{tasks.data.map((t) => <li key={t.id}>{t.done ? '[x]' : '[ ]'} {t.title}</li>)}</ul>
    </section>
  );
}

In the end-to-end run, adding "Wire up tRPC" listed it immediately, and submitting three spaces showed "Title is required", the message defined in the tasks team's Zod schema in the BFF and delivered through the error formatter's fieldErrors.

What the types catch

Because AppRouter comes from the BFF package, the root type check (Day 2) catches cross-package mistakes before they ship:

  • The tasks team renames done to completed in tasks.list. The tasks micro-frontend's t.done fails to compile in the same pull request.
  • The account team adds a required input to account.rename. Every caller that doesn't pass it fails to compile.
  • Anyone types trpc.task.list instead of trpc.tasks.list. It fails to compile.

The types do *not* protect a micro-frontend that's already deployed against a BFF that changes after it. That's deploy skew, and Day 9 covers it.

TipKeep each micro-frontend's trpc.ts identical except for which router parts it uses. When the platform team improves the link setup, the change is a copy, or better, a shared makeClient exported from the contract package.

Check yourself

Each has its own React root and team-owned library versions, and a per-area cache can't leak data between areas. The cost is a duplicated library and no shared cache.

To match the BFF's maxBatchSize: 10. When a busy screen makes more than ten calls at once, the client splits them into several requests instead of sending one batch the BFF would reject with 400 Batch call exceeds maximum size. Keeping both numbers in one shared constant prevents drift.

At compile time, in the same pull request. The tasks micro-frontend imports the BFF's AppRouter type, so the root tsc -p . check flags every place that still reads the old field. What types can't catch is an already-deployed micro-frontend meeting the new BFF, which is why Day 9 adds expand and contract.

It drops the micro-frontend's cached data and stops any background refetching for a screen nobody is looking at. It also guarantees that data from one visit can't leak into the next mount or into memory longer than needed.

When the duplication starts to matter, for example with many micro-frontends on one page or strict mobile performance budgets. Sharing them means one version for everyone and coordinated upgrades, like React, so make that trade only when the size cost is real.