Lorenzo
Lorenzo

Reputation: 288

How to intercept response with fastify-http-proxy

I'm trying to leverage fastify and fastify-http-proxy to proxy a legacy web server for some requests.

Example code from the fastify-http-proxy repo:

const Fastify = require('fastify')
const server = Fastify()

server.register(require('fastify-http-proxy'), {
  upstream: 'http://my-legacy-webserver.com',
  prefix: '/legacy'
})

server.listen(3000)

It works as expected but some proxied request can return a 404, with the legacy webserver rendering its custom 404 page that is proxied to the client. I would like to intercept 404 (maybe every 40x and also 50x) responses and handle them in my fastify server. It it possible? How can i achieve that?

Upvotes: 1

Views: 2080

Answers (1)

eol
eol

Reputation: 24565

I think this can be done with the onResponse handler in the replyOptions:

server.register(require('fastify-http-proxy'), {
  upstream: 'http://my-legacy-webserver.com',
  prefix: '/legacy',
  replyOptions: {
        onResponse (reply) {
             // you have access to the response here, e.g. check for errors and handle them
             reply.send("your modified response");
          }
      }
})

Upvotes: 2

Related Questions