Build Your First BFF with Fastify and Node
On this page
The setup
TaskBoard's web BFF will run on Node 22 with Fastify 5. Fastify is fast, has first-class TypeScript types and a good plugin set for proxying, cookies and static files.
npm init -y
npm i fastify @fastify/http-proxy @fastify/static
npm i -D typescript tsx @types/nodeBehind the BFF there's a tasks API at http://localhost:4810 and a recommendations service at http://localhost:4811. In a real system they would be services owned by other teams.
Serve the frontend from the BFF
The simplest and most secure deployment puts the web app and its BFF on one origin, for example https://app.taskboard.dev. The browser loads the app and calls /api/... on the same host. No CORS, and as you'll see on Day 4, cookies stay simple.
// src/server.ts
import Fastify from 'fastify';
import fastifyStatic from '@fastify/static';
import path from 'node:path';
const app = Fastify({ logger: true });
await app.register(fastifyStatic, {
root: path.resolve('web/dist'), // the built React app
wildcard: false,
});
// single-page app: unknown paths get index.html so client-side routing works
app.setNotFoundHandler((req, reply) => {
if (req.method === 'GET' && !req.url.startsWith('/api') && !req.url.startsWith('/bff')) {
return reply.sendFile('index.html');
}
reply.code(404).send({ error: 'not found' });
});
await app.listen({ port: 4900 });During development you'll usually run Vite's dev server for the React app and set its server.proxy option to forward /api, /bff and /auth to the BFF, so the browser still sees one origin.
Proxy API calls
Many calls from the browser don't need any shaping. Forward them to the service as they are with @fastify/http-proxy:
import httpProxy from '@fastify/http-proxy';
await app.register(httpProxy, {
upstream: 'http://localhost:4810',
prefix: '/api', // /api/tasks -> http://localhost:4810/tasks
});The prefix is stripped, so the browser's /api/tasks becomes /tasks on the tasks API. On Day 7 you'll add a preHandler to this proxy that checks the session and attaches the user's access token.
Add an endpoint shaped for one screen
The dashboard shows the user's tasks and a few suggestions. Without a BFF the browser makes two calls and receives everything both services return. With a BFF it makes one:
app.get('/bff/dashboard', async (_req, reply) => {
const [tasks, recs] = await Promise.all([
fetch('http://localhost:4810/tasks').then((r) => r.json()),
fetch('http://localhost:4811/recs').then((r) => r.json()),
]);
return {
tasks: tasks.items.map((t: any) => ({ id: t.id, title: t.title, done: t.done })),
recommendations: recs.items,
};
});Notice the shaping: the tasks API also returns an owner field and other internals, and the dashboard doesn't need them, so they never reach the browser.
The two downstream calls run in parallel with Promise.all, so the total time is roughly the slower of the two, not their sum. Inside a data center each call takes a few milliseconds. From a phone on a mobile network each round trip could take 100 ms or more, so moving fan-out to the server is a real win.
This first version has a serious weakness: if the recommendations service is slow or down, the whole dashboard fails with it. You'll fix that properly on Day 9.
Name your routes by purpose
Keep three clear groups of routes, and you'll thank yourself later:
/auth/* login, callback and logout (Day 5)
/bff/* endpoints the BFF builds itself (shaped for screens)
/api/* pass-through proxy to services (unchanged)When someone reads a request log, the prefix tells them whether the BFF composed the response or just forwarded it.
What the browser sees
From the browser's point of view there's now one backend:
GET / -> index.html (React app)
GET /tasks/42 -> index.html (client-side route)
GET /api/tasks -> proxied to the tasks API
GET /bff/dashboard -> composed by the BFFThe React app never learns the internal service addresses. You can split, merge or move services later without shipping a new frontend, as long as the BFF keeps its own routes stable.
TASKS_API_URL, never in code. The same BFF build then runs against local, staging and production services.Check yourself
The browser calls the BFF on its own origin, so no CORS configuration is needed and no preflight requests slow things down. The session cookie can be a strict first-party __Host-Http- cookie, and the CSRF defense on Day 8 stays a simple header check. It's both the simplest and the most secure layout.
/api/* routes are forwarded to a downstream service unchanged, apart from swapping the cookie for a token later. /bff/* routes are built by the BFF itself, usually by combining and shaping data for one screen. The prefix tells anyone reading a log whether the BFF composed the response or just passed it through.
Both downstream calls start at the same moment, so the response waits only for the slower one instead of the sum of both. Inside a data center each call takes a few milliseconds, while from a phone each browser round trip may take 100 ms or more, so moving the fan-out to the server saves real time.
A fallback for client-side routes. The browser asks the server for /tasks/42, which isn't a file, so the BFF must answer unknown GET paths outside /api, /bff and /auth with index.html and let the React router take over. The lesson's setNotFoundHandler does exactly that.
The same BFF build then runs unchanged against local, staging and production services. Hard-coded URLs force a rebuild per environment and make it easy to point a staging BFF at production data by accident.