ZetCode

JavaScript proxy

last modified June 19, 2022

In this tutorial, we show how to create and use a proxy in JavaScript.

A proxy server is a server application that acts as an intermediary between a client requesting a resource and the server providing that resource.

Proxies are used for various reasons, including authorization, anonymization, load balancing and logging.

JS proxy example

In our example, we use Express framework and http-proxy module. We are going to send a simple HTTP GET request to webcode.me website, which is going to be proxied over a local Express-based web application.

$ npm install express http-proxy

We install the two modules.

server.js
const express = require('express');
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer({});
const app = express();

app.get('*', (req, res) => {

    console.log('Request', req.method, req.url);
    proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
});

app.listen(3000, () => console.log('Application started on port 3000'));

This is a simple Express applications which logs the request and sends it to the final target.

app.get('*', (req, res) => {

    console.log('Request', req.method, req.url);
    proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
});

All requests are forwarded to the final destination. We log the request details to the console.

client.js
const axios = require('axios');

async function doGetRequest() {

    const res = await axios.get('http://webcode.me', {

        proxy: {
            host: 'localhost',
            port: 3000
        }
    });

    console.log(res.data);
}


doGetRequest();

With Axios, we create a GET request to the http://webcode.me webpage. It is sent via the proxy listening on localhost:3000.

$ node server.js 
Application started on port 3000

We start the server application.

$ node main.js 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="format.css">
    <title>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>
    
    <p>
         Hello there. How are you?
    </p>
    
</body>
</html>

We create a GET requst and receive a response. The server logs the Request GET http://webcode.me/ message to the console.

In this article, we have worked with a proxy in JavaScript.

List all JavaScript tutorials.