Open In App

How to Build a Node.js Proxy Server ?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A proxy server acts as an intermediary between a client and other servers. It can be used for various purposes, including load balancing, security, and caching. In the context of web development, a proxy server forwards requests from clients to other servers, fetches responses, and sends them back to the clients. In this article, we will create a Node.js proxy that forwards requests to different servers or endpoints. 

Why Proxy Server? 

In the standard method, the client sends a request directly to the API endpoint to fetch the desired data. In this case, the node.js proxy will act as an intermediary between the user and the API. Thus, the user makes a request to the proxy, which is then forwarded to the API endpoint. The user requests to the proxy endpoint.

The benefits of using a proxy are to:

  • Allow and restrict certain resources of the API.
  • Improves the network performance.
  • Load Balancing.

Steps to Implement Proxy Servers in Node

We will be building a node.js proxy for sending requests to a weather API - Open weather Map using http-proxy-middleware framework. 

Step 1: Initialize npm 

Make a new project directory and head over to the terminal. Write the following command to initialize npm.

npm init -y
Initializing npm 

Step 2: Install the required dependencies

We need a few packages in our project listed below:

  • express: It is a node.js framework.
  • http-proxy-middleware: It is a proxy framework.
  • dotenv: Loads environment variables.
  • morgan: Logs the requests.

Install the above packages by running the following command: 

npm i express http-proxy-middleware dotenv morgan
Installing packages 

Step 3: Creating proxy server 

Create an app.js file and write the code for the proxy server. First, we will import the installed packages into our project and create an express server.

const express = require('express');
const morgan = require("morgan");
const { createProxyMiddleware } = require('http-proxy-middleware');
require('dotenv').config()

// Creating express server
const app = express();

To use the open weather map api, you need an API key. Go to https://openweathermap.org/api  sign in or create a new account. Click on API keys and copy the key.

We will create a .env file to store this API key and its URL. Add the following code in the .env file

API_BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
API_KEY_VALUE = "<Enter your API key>"

Then, we will mention our port, host, and API URL.

const PORT = 3000;
const HOST = "localhost";
const API_BASE_URL = process.env.API_BASE_URL;
const API_KEY_VALUE = process.env.API_KEY_VALUE;

const API_SERVICE_URL = `${API_BASE_URL}?q=London&appid=${API_KEY_VALUE}`;

The proxy Logic: We will create a proxy middleware and specify the API endpoint and the new path that the user will use to fetch data. By default, we will retrieve the weather of London. 

app.use('/weather', createProxyMiddleware({
target: API_SERVICE_URL,
changeOrigin: true,
pathRewrite: {
[`^/weather`]: '',
},
}));

API_SERVICE_URL will be hidden from the user, and they will only be able to request weather from localhost:3000/weather. Behind the scenes, the path will be rewritten to localhost:3000/<API_SERVICE_URL>. 

Configure the server 

// Start Proxy
app.listen(PORT, HOST, () => {
console.log(`Starting Proxy at ${HOST}:${PORT}`);
});

Example: Implementation to build a node.js proxy server.

Node
// app.js

const express = require("express");
const morgan = require("morgan");
const { createProxyMiddleware } = 
    require("http-proxy-middleware");
require("dotenv").config();

// Create Express Server
const app = express();

// Configuration
const PORT = 3000;
const HOST = "localhost";
const { API_BASE_URL } = process.env;
const { API_KEY_VALUE } = process.env;
const API_SERVICE_URL = 
    `${API_BASE_URL}?q=London&appid=${API_KEY_VALUE}`;

// Logging the requests
app.use(morgan("dev"));

// Proxy Logic :  Proxy endpoints
app.use(
    "/weather",
    createProxyMiddleware({
        target: API_SERVICE_URL,
        changeOrigin: true,
        pathRewrite: {
            "^/weather": "",
        },
    })
);

// Starting our Proxy server
app.listen(PORT, HOST, () => {
    console.log(`Starting Proxy at ${HOST}:${PORT}`);
});

Step to Start Application: Run the application using the following command:

node app.js 

Output: 

You are now ready to use your proxy server. 

Step 4: Go to Postman to send requests.

We will send a request to localhost:3000/weather and get weather data for London, as specified in the URL query. The user doesn't even know the exact API endpoint. The user sends a request to the proxy server, and the proxy server forwards it to the API endpoint. 

Output:

Conclusion

Building a Node.js proxy server is a straightforward yet powerful way to manage requests and forward them to other servers. By leveraging the http-proxy library, you can create a robust proxy server capable of handling HTTP and HTTPS requests, customizing error handling, logging, and even rewriting request paths.


Next Article

Similar Reads