fastify/fastify-http-proxy

Bug in rewrite prefix when having query params and url params in the URL

noa-frontegg opened this issue · 3 comments

Prerequisites

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

Fastify version

4.0.0-rc.2

Plugin version

9.2.0

Node.js version

18

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13.4.1

Description

When registering routes that includes path parameter in the route, and configuring rewrite prefix, when sending the request with query parameters, there is a bug and the rewrite Prefix is not working.
For example:
registering path: /pref/types/:type/example
with rewritePrefix of: /types/:type/example
The server sends the request with the /pref prefix that should have been removed, when calling this URL with qs, for example:
when calling with: http://localhost:8080/pref/types/sometype/example?data=123
The server proxy the request to the target server with the full URL, instead of sending it without the prefix.
After debugging, the bug is in the line: (index.js line 330)
dest = dest.replace(prefixPathWithVariables, rewritePrefixWithVariables)
When the value of "prefixPathWithVariables" includes the querystring, but it should not include it (the replace doesn't work)

Steps to Reproduce

register route with path parameter (taken from the example):

// /rest-api/123/endpoint will be proxied to http://my-rest-api.example.com/123/endpoint
server.register(proxy, {
  upstream: 'http://my-rest-api.example.com',
  prefix: '/rest-api/:id/endpoint', // optional
  rewritePrefix: '/:id/endpoint', // optional
  http2: false, // optional
});

Call the API with qs:
http://localhost:9090/rest-api/123/endpoint?data=1234

Expected Behavior

The proxy should call: http://my-rest-api.example.com/123/endpoint?data=1234
But it calls: http://my-rest-api.example.com/rest-api/123/endpoint?data=1234

Thanks for reporting!

Can you provide steps to reproduce? We often need a reproducible example, e.g. some code that allows someone else to recreate your problem by just copying and pasting it. If it involves more than a couple of different file, create a new repository on GitHub and add a link to that.

Hello,
It's as simple as using the example given in the readme:

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

server.register(proxy, {
upstream: 'http://my-rest-api.example.com',
prefix: '/rest-api/:id/endpoint',
rewritePrefix: '/:id/endpoint',
http2: false,
});

server.listen({ port: 3000 });

And call the server with query parameter like this:
http://localhost:3000/rest-api/1234/endpoint?data=12345

Thanks for reporting! Would you like to send a Pull Request to address this issue? Remember to add unit tests.