Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Run Node Server?
Next article icon

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: 

https://media.geeksforgeeks.org/wp-content/uploads/20240727234816/1FullHD1080p.mp4

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:

https://media.geeksforgeeks.org/wp-content/uploads/20240727235053/2FullHD1080p.mp4

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
How to Run Node Server?

R

riyaa7vermaa
Improve
Article Tags :
  • Geeks Premier League
  • Node.js
  • Web Technologies
  • Geeks-Premier-League-2022
  • NodeJS-Questions

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences