Reverse-Proxy Routes to Another Backend
@fastify/http-proxy
Forward incoming requests to an upstream service — handy for backend-for-frontend patterns, API gateways, and gradual service migrations.
What you'll learn
- Install @fastify/http-proxy
- Register with an upstream URL and prefix
- Rewrite requests and responses with hooks
Sometimes you need Fastify to forward requests rather than handle them. @fastify/http-proxy is a thin reverse proxy built on undici — fast, streaming, and easy to customise.
Install & Register
npm install @fastify/http-proxy import proxy from '@fastify/http-proxy'
await app.register(proxy, {
upstream: 'http://internal-api:5000',
prefix: '/api',
http2: false,
}) Every request hitting /api/* is forwarded to the upstream, preserving method, headers, query, and body as a stream.
Inject Headers
Use preHandler to mutate the request before it goes upstream — for example, injecting a service token or stripping cookies.
await app.register(proxy, {
upstream: 'http://internal-api:5000',
prefix: '/api',
preHandler: async (req) => {
req.headers['x-service-token'] = app.config.SERVICE_TOKEN
},
}) Transform the Response
replyOptions.rewriteHeaders and onResponse let you customise what flows back to the client.
await app.register(proxy, {
upstream: 'http://internal-api:5000',
prefix: '/api',
replyOptions: {
rewriteHeaders: (headers) => ({
...headers,
'x-served-by': 'gateway',
}),
},
}) Pair this plugin with @fastify/rate-limit and @fastify/helmet to build a small but effective API gateway in front of your services.