fastify/fastify-http-proxy

how to dynamic rewrite or change proxy url, changeOrigin or other options

xygengcn opened this issue · 3 comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

import Fastify from 'fastify';
import proxy from '@fastify/http-proxy';

const server = Fastify({ logger: true });

// dynamic
const proxyMap = {
    '^/test': {
        target: 'http://localhost:3001',
        rewrite: '/newtest', // http://localhost:3000/test -> http://localhost:3001/newtest
        changeOrigin: true
    },
    '^/test2': {
        target: 'http://localhost:3002',
        rewrite: '', // http://localhost:3001/test2/get -> http://localhost:3002/get
        changeOrigin: true
    }
};

server.register(proxy, {
    upstream: '',
    http2: false, // optional
    preHandler(req, reply, done) {
        done();
    },
    // Feature
    router(req, reply) {
        const find = Object.keys(proxyMap).find((key) => new RegExp(key).test(req.url));
        if (find) {
            return proxyMap[find].target;
        }
        return find;
    },
    replyOptions: {
        getUpstream(req, base) {
            console.log(req.url, base);
            const find = Object.keys(proxyMap).find((key) => new RegExp(key).test(req.url));
            if (find) {
                return proxyMap[find].target;
            }
            return '';
        }
    }
});

server.listen({ port: 3000 });

Motivation

No response

Example

No response

Can you clarify the question? It seems your example implemented this already with our current options.

Can you clarify the question? It seems your example implemented this already with our current options.

I want to have a handler that can modify the target and rewrite at runtime, for example, when I first started http://localhost:3000/test -> http://localhost:3001/newtest ï¼›After a while, I want to make changes in runtime http://localhost:3000/test -> http://localhost:3002/newtest I don't need to restart the project. Similar to HTTP proxy middleware, there is a router function that can be implemented

You can always use https://www.npmjs.com/package/@fastify/reply-from to implement whatever routing logic you want to handle.

It's likely the easiest way for you to achieve that.