Our great sponsors
-
SurveyJS
Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.
-
example-nodejs-api-proxy-server
Example Node.js API proxy server built with @fastify/fastify-http-proxy
In these cases you might want to consider creating your own API endpoints which then make requests to an upstream API. The node-fetch library is a popular choice for making requests from Node.js. However, if you are interested in the features offered by undici, I recommend keeping an eye on the undici-fetch library. It is being developed as a WHATWG Fetch implementation based on undici.
As we don't want our client side JavaScript to contain the API key for security reasons, we're going to create a proxy server in Node.js which can receive a request from the client side JavaScript (made with fetch, or a request library like Axios). This proxy server will add the required API key to the request and forward it on to the API server.
fastify-http-proxy accepts a replyOptions object which it passes through to fastify-reply-from. These options give us full control to modify requests and responses as they pass through our proxy server.
In order to add an API key to the HTTP request headers, we're going to set a replyOptions.rewriteRequestHeaders function. We will access our API key from an environment variable and set it as the value of an X-Api-Key request header. This code builds on our initial configuration for the fastify-http-proxy plugin:
Our proxy server will use the HTTP client library undici to make requests to the upstream server. The undici library is a dependency of fastify-reply-from, which fastify-http-proxy is using under the hood. undici is much faster than the native HTTP client provided by Node.js.
The full code for this article is on GitHub.