Published: September 18 2021

Node.js - Simple Proxy to Pass Through HTTP Requests to an External URL

This is a quick example of how to proxy an HTTP request through a Node.js server to an external URL and return the response.

The below example is a super simple HTTP server that returns a random image that's been proxied from the Lorem Picsum sample image website (https://picsum.photos/). The server is built with the Node.js http library, and uses the request library from npm to send the external HTTP request that is proxied.

Node.js code to proxy a request

Before jumping into the example, this is the line of code to proxy a request in Node.js:

req.pipe(request('[URL_TO_PROXY]')).pipe(res);


Node.js HTTP Proxy Server Demo

An random image proxied from Lorem Picsum through Node.js.

(See on CodeSandbox at https://codesandbox.io/s/node-js-simple-http-proxy-server-example-bzye2)


Node Proxy Server Code

As you can see there's not much to the example Node.js server code, it contains the minimal required to demonstrate rendering a proxied image in the browser.

The default route (e.g. for the root / path) returns an <img /> with the source attribute pointing to the relative /random-image/${Math.random()} URL, the random number is to ensure a new image is displayed on each page refresh.

The /random-image/* route is where the proxying happens, the HTTP request received by the Node.js server (req) is piped into a new request to the picsum image URL (https://picsum.photos/300) sent with the request library, which is then piped back into the original Node.js response (res).

const http = require('http');
const request = require('request');

http.createServer(function (req, res) {
    if (req.url.startsWith('/random-image')) {
        // proxy random image from picsum website
        const imageUrl = 'https://picsum.photos/300';
        req.pipe(request(imageUrl)).pipe(res);
    } else {
        // default page with image tag that renders random image
        res.setHeader('Content-type', 'text/html');
        res.write(`<img src="/random-image/${Math.random()}" />`);
        res.end();
    }
}).listen(8080);

 


Need Some NodeJS Help?

Search fiverr for freelance NodeJS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by