How to proxy HTTP request with NodeJS

For my data compression Chrome extension I needed a proxy server, which should download the original file, compress it and respond back to browser.
It was pretty straight forward to implement using NodeJS and Express.

To handle the whole process of conversion in memory without touching the file system, NodeJs Streams come in handy. I used request library to handle image download and sharp library to convert downloaded image. Both of them support stream interface and work together quite nicely:

const express = require('express')
const request = require('request')
const sharp = require('sharp')

const QUALITY = 40
const app = express()

app.get('/', (req, res) => {
  const imageUrl = req.query.url
  if (!imageUrl.match(/^https?:/i)) return res.status(400).end()

  const transformer = sharp()
    .grayscale()
    .toFormat('webp', { quality: QUALITY })

  request
    .get(imageUrl)     // download original image
    .pipe(transformer) // pass it to the transformer
    .pipe(res)         // pipe converted image to HTTP response
})

I used transform stream provided by sharp, but you can easily implement your own custom transformer to perform any kind of changes to the response from original server before returning it.

Here’s the full implementation of my compression proxy.

Written on June 1, 2017