DEV Community

Cover image for Build a Node.js API Proxy to supercharge your backend
Saurabh Dashora
Saurabh Dashora

Posted on • Originally published at progressivecoder.com

Build a Node.js API Proxy to supercharge your backend

Have you ever wondered who's the middleman between you and that fancy API you're using?

Meet the API proxy. The undercover agent of the tech landscape!

Just like how your best friend proxied your attendance call during that boring college lecture, an API proxy acts on behalf of something else in the digital realm.

And it's not just for the FBI. Even API developers use it to sneakily redirect incoming requests to the real server.

api-proxy-concept

Want to learn how to build a Node.js API Proxy on your own? Keep reading!

The Need for an API Proxy

Several reasons justify the use of an API proxy:

  • Maybe the real API server is unpredictable. A proxy can act as a trusty stable hand and provide a more stable interface for your clients.
  • Probably the current API server is like a temporary rental car. You have plans for upgrading in the future, but you want to shield the API clients from future changes. You can use an API proxy to make the transition smoother.
  • Or maybe, the response from the API server is like a bad translation. A proxy can act as a translator and convert the API response to something that the clients can understand or consume.

All in all, an API Proxy makes your actual backend API more scalable in the long run.

Bottom line, an API Proxy is like a swiss-army knife. You never know when you might need one. But when you do, you would be happy to have it.

The Project Setup

First, you need to initialize the project by executing the below command in a project directory:

$ npm init -y
Enter fullscreen mode Exit fullscreen mode

This will generate a basic package.json file with meta-data information about the project such as name, version, author and scripts.

Next, install a couple of packages for developing the Node.js API proxy.

$ npm install --save express http-proxy-middleware
Enter fullscreen mode Exit fullscreen mode
  • express is a minimalistic web framework you can use to build API endpoints.
  • http-proxy-middleware is a third-party Node.js package that has all the tools to create an API proxy

After the package installation, define a start command for the project within the package.json file. You can use this command to start the application.

Your project’s package.json should look similar to the below example.

{
  "name": "express-proxy-demo",
  "version": "1.0.0",
  "description": "Demo Application for Proxy Implementation in Node.js",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "Saurabh Dashora",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "http-proxy-middleware": "^2.0.6"
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating the API Proxy using Node.js

The project setup is done. Now, it’s time to build the API Proxy.

You are going to create an application that acts like a proxy and redirects incoming requests to an API that’s hosted somewhere else. Think of it like a game of telephone but with requests.

For the sake of this tutorial, I’m going to use some fake APIs hosted at the wonderful website JSONPlaceholder.

Check out the below illustration for a visual perspective.

nodejs-api-proxy

Here’s the index.js file where all the magic happens.

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

const PORT = 3000;
const HOST = "localhost";

const API_URL = "https://jsonplaceholder.typicode.com";

app.get("/status", (req, res, next) => {
    res.send('This is a proxy service');
});

const proxyOptions = {
    target: API_URL,
    changeOrigin: true,
    pathRewrite: {
        [`^/api/posts`]: '/posts',
    },
}

const proxy = createProxyMiddleware(proxyOptions);

app.use('/api/posts', proxy)

app.listen(PORT, HOST, () => {
    console.log(`Proxy Started at ${HOST}:${PORT}`)
});
Enter fullscreen mode Exit fullscreen mode

Let’s understand each step in the above program:

Step 1: The first segment of the code contains the import statements for express and http-proxy-middleware.

Step 2: The next statement creates an application instance using the call to express() function. This is followed by declaring a few important constants such as PORT, HOST and API_URL.

Step 3: Implement an endpoint /status to describe the role of the application. This endpoint has nothing to do with proxying requests. It simply provides a way to test our application.

Step 4: Next, we declare an object proxyOptions. This is a configuration object for our API proxy. It contains a few important properties

  • target - It defines the target host where you want to proxy requests. In our case, this is the https://jsonplaceholder.typicode.com
  • changeOrigin - This is set to true since we are proxying to a different origin.
  • pathRewrite - This is a very important property where you define the rules for rewriting the path. For example, the expression [^/api/posts]: '/posts' routes all incoming requests directed at URL /api/posts to just /posts. In other words, this will remove the /api prefix from the path.

Step 5: After declaring the configuration object, create the proxy object by calling createProxyMiddleware() function with the proxyOptions object as input.

Step 6: Next, create a request handler for the path /api/posts and pass the proxy object as handler for the incoming request.

Step 7: At the very end, start the Node.js API Proxy server to listen on the port and host that were already declared earlier.

You can start the application using the command npm run start.

> express-proxy-demo@1.0.0 start
> node index.js

[HPM] Proxy created: /  -> <https://jsonplaceholder.typicode.com>
[HPM] Proxy rewrite rule created: "^/api/posts" ~> "/posts"
Proxy Started at localhost:3000
Messages about the proxy setup indicate that the proxy is configured properly.
Enter fullscreen mode Exit fullscreen mode

If you visit the URL http://localhost:3000/api/posts/1 in the browser, you will get the response from the JSONPlaceholder APIs as below:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto"
}
Enter fullscreen mode Exit fullscreen mode

Basically, the Node.js API Proxy is doing its job by proxying requests to the mock APIs hosted by JSONPlaceholder.

That’s it

Congratulations! You've just built a basic version of a Node.js API proxy.

But don't stop there. Just like a birdhouse, you can always make it bigger and better based on specific requirements.

The http-proxy-middleware is like the toolbox for building a Node.js API proxy server and you can extend it in many ways using path matching and so on.

The code for this demo is available on GitHub.

If you found the post useful, consider sharing it with friends and colleagues. And if you have any questions, feel free to ask in the comments section below.

In case you want to know more about proxies, you can also head over to this tutorial on building a Node.js forward proxy.

You can also connect with me on other platforms:

My Regular Newsletter

Twitter

LinkedIn

Youtube

Top comments (0)