http-proxy-middleware

21 August, 2020
Back

http-proxy-middleware is a package to create a quick proxy server.

This demo will setup a proxy to get data from a free Coin Gecko API before passing it on to the frontend.

The flow looks like this:

Coin Gecko API --> proxy server (port 3001) --> React.js (port 3000)

Link to tutorial.

The Steps

  1. Run npx create-react-app react-proxy
  2. Run npm i express http-proxy-middleware
  3. Create a server.js file in the root folder. Copy this code into the server.js file.
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
app.use('/coins/markets', createProxyMiddleware({
    target: 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=USD&order=market_cap_desc&per_page=100&page=1&sparkline=false',
    headers: {
        accept: "application/json",
        method: "GET",
    },
    changeOrigin: true
}));
app.listen(3001);
  1. Create a fetch-proxy.js file in the src folder. Copy this code into the fetch-proxy.js file.
import React, { useState, useEffect } from "react";

const FetchProxy = () => {
  const [data, setData] = useState([]);

  const coins = "http://localhost:3001/coins/markets";

  useEffect(() => {
    fetch(coins)
      .then((response) => response.json())
      .then((info) => setData(info));
  }, []);

  console.log(data);

  return (
    <div>
      {data.map((x) => (
        <div>
          <p>
            {x.name}: <span className="price">{x.current_price}</span>
          </p>
        </div>
      ))}
    </div>
  );
};

export default FetchProxy;
  1. Import the FetchProxy component into App.js.
import FetchProxy from "./fetch-proxy";

<FetchProxy/>
  1. Open two command prompts and run these two commands concurrently.
npm start

node server.js
  1. Open these two links in the browser.

localhost:3000 localhost:3001/coins/markets

Done

That's it! React.js should be displaying the list of cryptocurrency prices.

The data is fetched from the proxy server (on port 3001).

In turn, React is fetching the data from the proxy server.

Proxy servers are used for a number of reasons like to hide the source IP, filter requests, and prevent attacks.

This demo isn't that sophisticated to do those things, but it demonstrates how to set up a simple one.


Back