The BFF as Host: Shell, Sign-In and tRPC
On this page
One server, four jobs
The BFF is the only server the browser talks to. It does four jobs, in this order of registration:
- A CSRF check on every API call.
- Sign-in routes:
/auth/login,/auth/callback,/auth/logoutand/bff/user. - The tRPC API at
/trpc. - Static files and the shell page, with the import map injected on every page load.
Sign-in is exactly the flow from the BFF course: authorization code with PKCE, state and nonce through openid-client, a fresh session in Redis, and a __Host-Http-sid cookie with HttpOnly, Secure and SameSite=Lax. This lesson focuses on how the pieces share one server.
The CSRF rule, including subscriptions
Every call to /trpc, /bff/* and logout must carry the x-csrf: 1 header. A cross-site page can't add that header without a CORS preflight, which the BFF never allows. One global hook enforces it:
app.addHook('onRequest', async (req, reply) => {
const guarded = req.url.startsWith('/trpc') || req.url.startsWith('/bff/') || req.url === '/auth/logout';
const isSse = req.method === 'GET' && String(req.headers.accept).includes('text/event-stream');
if (guarded && !isSse && req.headers['x-csrf'] !== '1') {
return reply.code(403).send({ error: 'csrf' });
}
});The isSse exception needs a careful reason, because RFC 10017 asks for the header on *every* request. tRPC subscriptions run over Server-Sent Events, and the browser's EventSource can't set custom headers. So the hook allows GET requests that ask for an event stream, and only those, on three conditions:
- Subscriptions are read-only. They must never change data when they start. Treat that as a hard rule in code review.
- A cross-site page can't read the stream. Reading a cross-origin response needs CORS permission, which the BFF never grants.
- The cookie is
SameSite=Lax, so cross-site subresource requests don't carry it anyway.
In the end-to-end test, the browser's requests looked exactly like this:
GET /trpc/tasks.list csrf=1
GET /trpc/tasks.onChanged csrf=- accept=text/event-stream
POST /trpc/tasks.create csrf=1
POST /trpc/account.rename csrf=1Mounting tRPC
The tRPC Fastify plugin goes at /trpc, with a batch limit and logging for failures:
await app.register(fastifyTRPCPlugin, {
prefix: '/trpc',
trpcOptions: {
router: appRouter,
maxBatchSize: 10,
createContext, // Day 4
onError({ path, error, req }) {
if (['INTERNAL_SERVER_ERROR', 'BAD_GATEWAY', 'GATEWAY_TIMEOUT'].includes(error.code)) {
app.log.error({ path, reqId: req.id, err: error.cause ?? error }, 'tRPC call failed');
}
},
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});Create the Fastify instance with routerOptions: { maxParamLength: 5000 }, because batched tRPC calls put several procedure names in one URL segment, and Fastify's default limit of 100 characters rejects long batches.
Also give every request an id, taken from the incoming x-request-id header or generated:
const app = Fastify({
genReqId: (req) => (req.headers['x-request-id'] as string) ?? randomUUID(),
routerOptions: { maxParamLength: 5000 },
});That id goes into the tRPC context and on to every downstream call (Day 4).
Serving the shell and the micro-frontends
Hashed micro-frontend files and versioned React files are cached for a year. Everything else is revalidated:
await app.register(fastifyStatic, {
root: distDir, wildcard: false, index: false,
setHeaders: (reply, file) => reply.header('cache-control',
/[.-][0-9A-Z]{8}\.js$|-\d+\.\d+\.\d+\.js$/.test(file) ? 'public, max-age=31536000, immutable' : 'no-cache'),
});In @fastify/static version 10, setHeaders receives Fastify's reply object, so you call reply.header(), not the Node response's setHeader.
Every other GET gets the shell page, with the current import map read fresh, so deep links like /account work and a deploy is a change to the map file:
app.setNotFoundHandler((req, reply) => {
if (req.method !== 'GET' || /^\/(trpc|bff|auth)/.test(req.url)) {
return reply.code(404).send({ error: 'not found' });
}
const map = fs.readFileSync(importMapFile, 'utf8');
return reply.header('cache-control', 'no-cache').type('text/html').send(`<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>TaskBoard</title>
<script type="importmap">${map}</script>
<script type="module" src="/shell.js"></script></head>
<body><div id="header"></div><main id="outlet"></main></body></html>`);
});The API prefixes are excluded, so a mistyped tRPC path returns a JSON 404 instead of an HTML page that would confuse the client.
Check yourself
tRPC subscriptions use Server-Sent Events, and the browser's EventSource API can't set custom headers at all. Requiring the header would block every subscription. So the BFF makes a narrow exception for GET requests that accept text/event-stream, backed by three conditions that keep it safe.
Subscriptions never change data, a cross-site page can't read the stream without CORS permission, and the SameSite=Lax cookie isn't sent on cross-site subresource requests.
So a wrong API path returns a JSON 404, not the shell's HTML page, which would make the client fail with a confusing parse error.
The CSRF exception for event-stream requests relies on subscriptions being read-only. A subscription that changes data when it starts could be triggered from another site without the custom header. Changes must go through mutations, which always require the header.
So one id follows a request everywhere: Fastify logs it, the tRPC context carries it, and callApi forwards it to downstream services. Reusing an incoming id keeps the chain intact when a proxy in front of the BFF already assigned one.