Proxyfiying in Node.js

54 days ago, 0 views.

For historical reasons there are a lot of NPM modules for doing this, but nowadays, it’s easier than ever just using native APIs:

const createProxyServer = () => {
  const resources = []

  const proxyServer = http.createServer((req, res) => {
    resources.push([req.url, res])

    const proxyRequest = http.request(
      req.url,
      {
        method: req.method,
        headers: req.headers
      },
      proxyResponse => {
        res.writeHead(proxyResponse.statusCode, proxyResponse.headers)
        proxyResponse.pipe(res, { end: true })
      }
    )

    req.pipe(proxyRequest, { end: true })
  })
  
  proxyServer.url = `http://[::]:${proxyServer.address().port}`
  proxyServer.history = proxiedRequestUrls

  return proxyServer
}

Easy peasy!

Kiko Beats

Kiko Beats