How to Build a Node.js Proxy Server ?
Last Updated : 01 Aug, 2024
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.
Similar Reads
How to create proxy server on Heroku in Node.js ?
The following approach covers how to create a proxy server on Heroku using NodeJS. Heroku is a cloud application platform that is used as PaaS (Platform as a service) to build, operate and run applications on their cloud. Prerequisites: To create a proxy server, you will need the following to be ins
2 min read
How to Build a Simple Web Server with Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 min read
How to Run Node Server?
A Node server runs JavaScript outside the browser to handle web requests. It listens for incoming requests, processes them, and sends responses. Unlike traditional servers, it handles multiple requests at once without waiting for each to finish. Some of the key features of the Node Server are: Non-B
3 min read
How to build Node.js Blog API ?
In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters. Functionalities: Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we
5 min read
Build a Node.js-powered Chatroom Web App
In this article, we are going to create a chatroom web app using Node.js. A Chatroom Web App is basically used to create a chatroom that is similar to a group chat, where users can come and join the group/ chatroom, send messages to the chatroom, and see other users' messages. We are going to set up
5 min read
How to Create HTTPS Server with Node.js ?
Creating an HTTPS server in Node.js ensures secure communication between your server and clients. HTTPS encrypts data sent over the network, providing a layer of security essential for handling sensitive information. This guide will walk you through the process of setting up an HTTPS server in Node.
4 min read
How Proxy Backend Server using React.js ?
When building a web application with React.js, you may need to request a backend server. However, if the backend server does not allow Cross-Origin Resource Sharing (CORS), you may encounter an error when requesting from the frontend application. In this case, you can use the proxy server to forward
3 min read
How to Install Node.js on a Webserver ?
Node.js is a powerful, lightweight, and efficient runtime for executing JavaScript code on the server side. It is particularly well-suited for building scalable network applications. Installing Node.js on a web server enables developers to run server-side JavaScript, host web applications, and serve
2 min read
How to Separate Routers and Controllers in Node.js ?
In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the appli
4 min read
How to build a simple Discord bot using Node.js ?
Discord is an instant messaging application mostly used by developers and gamer communities. Many discord servers use bots to automate the task. Bots are programs that allow us to automate some tasks like messaging, maintaining our server, etc. Discord provides us with many built-in bots. Discord al
3 min read