Testing and Tracing a BFF with Fastify inject
On this page
Test without a network
A BFF route depends on services you don't want to run in unit tests. Two tools make that easy in Node:
app.inject(), built into Fastify, sends a fake HTTP request straight into your app without opening a port.- undici's
MockAgentinterceptsfetchcalls. Node's built-infetchis powered by undici, so installing a mock agent as the global dispatcher catches every downstream call.
// test/dashboard.test.ts
import test from 'node:test';
import assert from 'node:assert/strict';
import { MockAgent, setGlobalDispatcher, getGlobalDispatcher } from 'undici';
import { buildApp } from '../src/app';
const original = getGlobalDispatcher();
let agent: MockAgent;
test.beforeEach(() => {
agent = new MockAgent();
agent.disableNetConnect(); // any unmocked call fails the test
setGlobalDispatcher(agent);
});
test.afterEach(async () => {
await agent.close();
setGlobalDispatcher(original);
});
test('degrades when recommendations fail', async () => {
agent.get('http://tasks.internal').intercept({ path: '/tasks' }).reply(200, { items: [] });
agent.get('http://recs.internal').intercept({ path: '/recs' }).reply(503, {});
const res = await buildApp().inject({ method: 'GET', url: '/bff/dashboard' });
assert.equal(res.statusCode, 200);
assert.deepEqual(res.json().degraded, ['recommendations']);
});disableNetConnect() is worth having on every test. A forgotten mock then fails loudly instead of quietly calling a real service.
Test the failure cases
The happy path is the least interesting test. Write one test per decision from Day 9's table:
test('degrades when recommendations are slow', async () => {
agent.get('http://tasks.internal').intercept({ path: '/tasks' }).reply(200, { items: [] });
agent.get('http://recs.internal').intercept({ path: '/recs' }).reply(200, { items: ['late'] }).delay(1000);
const res = await buildApp().inject({ method: 'GET', url: '/bff/dashboard' });
assert.deepEqual(res.json().degraded, ['recommendations']);
});
test('fails with 502 when tasks are down', async () => {
agent.get('http://tasks.internal').intercept({ path: '/tasks' }).reply(500, {});
agent.get('http://recs.internal').intercept({ path: '/recs' }).reply(200, { items: [] });
const res = await buildApp().inject({ method: 'GET', url: '/bff/dashboard' });
assert.equal(res.statusCode, 502);
});ok 1 - combines both services
ok 2 - degrades when recommendations fail
ok 3 - degrades when recommendations are slow
ok 4 - fails with 502 when tasks are down
ok 5 - forwards request id and traceparent downstream
# pass 5The .delay(1000) test runs in about 300 ms, because the BFF's own timeout ends it. Add the CSRF tests from Day 8 to this suite as well.
Test the login flow end to end
Mocks can't prove that sign-in works with a real identity provider. Keep a small end-to-end suite that runs the BFF against a real OIDC provider in a container, such as Keycloak, or oidc-provider as this course's lab did, and drives a browser with Playwright through login, an API call, a token refresh and logout. It's slower, so run it in CI, not on every save.
Follow a request across services
When a user reports "the dashboard was slow at 10:42", you need to see what happened inside the BFF *and* in every service it called. Two headers make that possible.
x-request-id: a simple id for one request. Fastify can read it from the incoming request and generate one if it's missing.traceparent: the W3C Trace Context header. It carries a trace id shared by every service in the request, plus the id of the calling span. OpenTelemetry and most tracing tools understand it.
const app = Fastify({
logger: true,
genReqId: (req) => (req.headers['x-request-id'] as string) ?? randomUUID(),
});
function downstreamHeaders(req: FastifyRequest, token?: string) {
return {
'x-request-id': req.id,
...(req.headers.traceparent ? { traceparent: req.headers.traceparent } : {}),
...(token ? { authorization: `Bearer ${token}` } : {}),
};
}A test with MockAgent confirmed that both headers reached both downstream services unchanged. Fastify's logger includes reqId in every log line, so you can search all logs for one request.
Forwarding traceparent by hand keeps the trace id, but a proper trace also needs a new span for each hop. In production, use OpenTelemetry: the @opentelemetry/sdk-node package with the HTTP, undici and Fastify instrumentations creates spans automatically and propagates traceparent on every fetch, with no code in your routes.
What to measure
For each BFF route and each downstream dependency, track:
- request rate, error rate and latency percentiles (p50, p95, p99),
- timeouts, retries and circuit breaker state changes,
- degraded responses, by which part was missing,
- session events: sign-ins, refresh failures, logouts.
Alert on what users feel: dashboard p95 latency and error rate. Use dependency metrics to find the cause.
Never log secrets
A BFF handles cookies and tokens on every request, which makes its logs dangerous. Configure the logger to redact them:
const app = Fastify({
logger: {
redact: ['req.headers.authorization', 'req.headers.cookie', 'res.headers["set-cookie"]'],
},
});Fastify's default request serializer doesn't log headers at all. Redaction protects you on the day someone adds a header-logging serializer while debugging.
Check yourself
A forgotten mock. With network access disabled, any downstream call the test didn't intercept fails loudly. Without it, the test might silently call a real service, pass or fail depending on that service's state, and even change real data.
x-request-id is a simple correlation id. traceparent is the W3C Trace Context header, which carries a shared trace id and the parent span id that tracing tools use to build the full call tree.
Slow services are more common than dead ones, and they behave differently: nothing fails, the request just waits. The test proves the BFF's timeout ends the call and the page degrades instead of hanging. In the lab, a mocked 1-second delay finished in about 300 ms because the timeout fired.
If the BFF returns its request id in a response header and the error screen shows it, the ticket carries an id you can search for. The same id appears in every BFF log line for that request and in downstream services' logs, because the BFF forwards it as x-request-id.
Defaults change, and someone debugging will eventually add a serializer that logs headers. Redaction rules make sure tokens and session cookies never end up in log storage, where far more people can read them than can read production memory.