Reputation: 69
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
Upvotes: 0
Views: 1965
Reputation: 1
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);
}
Upvotes: 0
Reputation: 69
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.
Upvotes: 3