tRPC Inside a BFF: Context, Routers and Tokens
On this page
Context from the session
On Day 3 the tRPC plugin was given a createContext function. It's where the BFF's two worlds meet: the browser's cookie on one side, the user's tokens on the other.
// packages/bff/src/trpc/init.ts
export type Context = {
session: Session | null;
getAccessToken: () => Promise<string>;
requestId: string;
};// packages/bff/src/server.ts
createContext: async ({ req }): Promise<Context> => {
const session = await sessions.get(req.cookies['__Host-Http-sid']);
return {
session,
requestId: req.id,
getAccessToken: () => {
if (!session) throw new Error('no session');
return accessTokenFor(config, sessions, session); // refreshes once if near expiry
},
};
},Two design choices matter here:
- The token is fetched lazily.
getAccessTokenis a function, not a value. Procedures that don't call a downstream service never trigger a token refresh. - The token never enters the procedure's output. It goes from the session to the
Authorizationheader of a server-to-server call, and nowhere else.
accessTokenFor is the single-flight refresh from the BFF course: if several procedures in one batch find the token about to expire, they all wait for one refresh, which matters when the identity provider rotates refresh tokens.
The protected procedure
The base procedures live in the platform team's init.ts:
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.session) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Sign in first' });
return next({ ctx: { session: ctx.session, user: ctx.session.data.user } });
});After this middleware, every procedure sees a non-null ctx.user, typed, with no ! needed. UNAUTHORIZED also has a special job on the client: Day 6 turns it into one "your session ended" flow for the whole app.
The same init.ts holds the error formatter from the tRPC course: it masks INTERNAL_SERVER_ERROR messages in production and adds fieldErrors for Zod failures.
One sub-router per team
The root router is tiny and mostly a map of ownership:
// packages/bff/src/trpc/router.ts
export const appRouter = router({
tasks: tasksRouter, // tasks team
account: accountRouter, // account team
});
export type AppRouter = typeof appRouter;Each team writes its sub-router in its own file, with its own tests. A CODEOWNERS rule makes the tasks team review routers/tasks.ts and the platform team review init.ts and router.ts.
Calling downstream services
The tasks team's procedures don't own the data. The tasks API does. A small helper makes every downstream call the same way: with the user's token, the request id, a timeout, and errors translated into tRPC codes:
// packages/bff/src/trpc/downstream.ts
export async function callApi<T>(ctx: { getAccessToken: () => Promise<string>; requestId: string },
url: string, init: RequestInit = {}, timeoutMs = 1500): Promise<T> {
const token = await ctx.getAccessToken();
let res: Response;
try {
res = await fetch(url, {
...init,
headers: { ...init.headers, authorization: `Bearer ${token}`, 'x-request-id': ctx.requestId,
...(init.body ? { 'content-type': 'application/json' } : {}) },
signal: AbortSignal.timeout(timeoutMs),
});
} catch (err) {
throw new TRPCError({ code: 'GATEWAY_TIMEOUT', message: 'The tasks service did not answer in time', cause: err });
}
if (res.status === 404) throw new TRPCError({ code: 'NOT_FOUND' });
if (res.status === 401) throw new TRPCError({ code: 'UNAUTHORIZED' });
if (res.status === 403) throw new TRPCError({ code: 'FORBIDDEN' });
if (!res.ok) throw new TRPCError({ code: 'BAD_GATEWAY', message: `Downstream returned ${res.status}` });
return res.json() as Promise<T>;
}The mapping is the important part. Without it, a downstream 503 would surface as a generic INTERNAL_SERVER_ERROR, and with the production formatter, as "Something went wrong". With it, the client gets a meaningful code (BAD_GATEWAY, GATEWAY_TIMEOUT), the right HTTP status (502, 504), and can decide whether to retry.
The tasks router
With the helper, procedures stay short and focused on shaping:
// packages/bff/src/trpc/routers/tasks.ts (owned by the tasks team)
const TASKS_API = process.env.TASKS_API_URL ?? 'http://localhost:4810';
export const tasksRouter = router({
list: protectedProcedure.query(async ({ ctx }) => {
const data = await callApi<{ items: (Task & { owner: string })[] }>(ctx, `${TASKS_API}/tasks`);
return data.items.map(({ id, title, done }) => ({ id, title, done })); // shaped for the screen
}),
create: protectedProcedure
.input(z.object({ title: z.string().trim().min(1, 'Title is required').max(100) }))
.mutation(async ({ ctx, input }) => {
const task = await callApi<Task>(ctx, `${TASKS_API}/tasks`, { method: 'POST', body: JSON.stringify(input) });
await taskEvents.publish(ctx.user.sub, { type: 'created', task }); // Day 7
return { id: task.id, title: task.title, done: task.done };
}),
});list drops the downstream owner field before it reaches the browser. create validates and trims the title in the BFF, so an empty title never costs a call to the tasks API.
Note what the BFF doesn't do: it doesn't check that Ada owns the tasks. The tasks API filters by the token's subject, because it owns the data and the rules. The BFF composes; the service decides.
A second team, a different source
The account team's router reads and writes a display name in Redis instead of calling a service. Nothing in the shape of the API reveals that difference to the browser, which is part of the point:
export const accountRouter = router({
me: protectedProcedure.query(async ({ ctx }) => {
const displayName = await redis.get(`profile:${ctx.user.sub}:name`);
return { sub: ctx.user.sub, email: ctx.user.email, name: displayName ?? ctx.user.name ?? ctx.user.sub };
}),
rename: protectedProcedure
.input(z.object({ name: z.string().trim().min(1).max(60) }))
.mutation(async ({ ctx, input }) => {
await redis.set(`profile:${ctx.user.sub}:name`, input.name);
return { name: input.name };
}),
});callApi a per-service timeout and name, and log the name with each failure. "tasks-api timed out" is a far better alert than "fetch failed".Check yourself
So the access token is only loaded, and refreshed if it's about to expire, when a procedure actually calls a downstream service. Procedures that read Redis or return session data never trigger a refresh. And because a batch shares one context, several procedures asking at once share one single-flight refresh.
A meaningful error code and a 502 status instead of a masked generic error, so the client can show the right message and decide whether to retry.
No. The tasks API owns the data and filters by the token's subject. The BFF passes the user's token and shapes the response.
callApi aborts the call after its timeout, 1.5 seconds by default, and throws GATEWAY_TIMEOUT, which becomes HTTP 504. The code tells the client the failure was in a dependency behind the BFF, so it can show "try again shortly" instead of a generic error.
The tasks API returns extra fields, such as owner, that the screen doesn't need. Shaping the response in the BFF keeps payloads small and stops internal fields reaching the browser, and the shaped type is what the micro-frontend sees through tRPC.