Patrick Hwang
Patrick Hwang

Reputation: 1

Fastify-http-proxy unable to get dynamic routes

I have a fastify server that's pointing to two "backend" fastify servers and I'd like to generate a random number that is then used to decide which backend to route to.

Currently it only works the first time, and I'm unable to override the upstream afterwards.

server.register(require('fastify-http-proxy'), {
  upstream: '',
  replyOptions: { 
    getUpstream: (originalReq, base) => {
      if (Math.random() < 0.5) {
        console.log(`setting base to backend1`)
        return `http://localhost:${backend1Port}`
      } else {
        console.log(`setting base to backend2`)
        return `http://localhost:${backend2Port}`
      }
    },
    disableCache: true,
    cacheURLs: 0,
  },
})

How can I make it so that upon refresh it might change where it routes to?

Upvotes: 0

Views: 598

Answers (1)

Patrick Hwang
Patrick Hwang

Reputation: 1

Figured it out. disableCache needed to be outside of replyOptions.

server.register(require('fastify-http-proxy'), {
  upstream: '',
  replyOptions: { 
    getUpstream: (originalReq, base) => {
      if (Math.random() < 0.5) {
        console.log(`setting base to backend1`)
        return `http://localhost:${backend1Port}`
      } else {
        console.log(`setting base to backend2`)
        return `http://localhost:${backend2Port}`
      }
    },
    disableCache: true,
    cacheURLs: 0,
  },
})

Upvotes: 0

Related Questions