Open In App

How to build a node.js proxy server ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create a Node.js proxy that forwards requests to different servers or endpoints. 

Proxy server: Proxy servers act as intermediaries between the end-user and the website or API they wish to access.

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 is to:

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

Example: Let’s build a node.js proxy server.

Prerequisites: Make sure you have the following applications on your device.

  • Node.js (install).
  • Visual studio code or any other code editor.
  • Postman to test API requests.

Approach: 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.

Getting an API key at Open Weather Map API 

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}`);
});

Add the following code to the app.js file.

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: 

Creating the proxy server

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:

Sending request to fetch weather data 



Last Updated : 10 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads