0

I have a small project with a node.js + fastify server, in which I want to proxy requests to an external API using fastify-http-proxy https://github.com/fastify/fastify-http-proxy (no existing tags here). This external API wants their api-key specified as a query param. I want to add this key to the proxied requests in my server, and not in our front-end. However I can't seem to get it to work with replyOptions.queryString, since it does not have direct access to request.query it overrides the original request queries, rendering the entire call useless:

    let originalRequestQueries = {};
    
    fastify.register(proxy, {
      upstream: CONFIG.externalApi,
      prefix: '/api/stocks',
      undici: true,
      replyOptions: {
        queryString: {
          ...originalRequestQueries,
          apikey: CONFIG.apiKey,
        },
      },
      preHandler: async (req, reply) => {
        try {
          await req.jwtVerify();
          originalRequestQueries = req.query;
          console.log(originalRequestQueries);
        } catch (err) {
          throw boom.boomify(err);
        }
      },
    });

Any tips on how to make this work? I can't seem to find information regarding this anywhere in fastify-http-proxy documentation nor fastify-reply-from which it was built on. The proxy works perfectly fine if I specify the apikey query param in the request coming in to the server. Kind regards, B

B.Dwyer
  • 69
  • 12

2 Answers2

3

I got it to work by adding

req.raw.url = `${req.raw.url}&apikey=${CONFIG.apiKey}`;

into the preHandler function. Strangely, this worked but not any alterations to req.query.

B.Dwyer
  • 69
  • 12
  • 1
    Glad you figured it out - but it's rather ugly. You might want to raise an issue on their github project ;) – eol May 13 '21 at 16:48
  • 2
    Haha it will do fine for our usecase, I'll check what I can do on the open source after I've finished this project :) I appreciate you taking a look at it mate. Cheers – B.Dwyer May 13 '21 at 16:50
  • typescript doesn't love this solution, saying 'Attempt to assign to const or readonly variable'... – grreeenn Nov 08 '22 at 15:31
0

You can try this if you want to handle it within the queryString replyOption:

queryString: (search, reqUrl) => {
  reqUrl = reqUrl.split("?").pop();
  var query = querystring.parse(reqUrl);
  query.apikey = CONFIG.apiKey;
  return querystring.stringify(query);
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31