HTTP Proxy/Load Balancer in Node.js

There are different existing mature reverse proxy servers and load balancers like NGINX or Traefik.

But imagine I have a situation where I need to redirect requests coming to my server to single or multiple (load balancing) locations and existing products do not suit my needs.

For example, because of one of the following:

  1. need for some custom pre- or post-processing to be applied in request or response
  2. need for some custom load-balancing logic (e.g. depending on readiness or state of balanced microservices etc.)
  3. need for custom authentication or request filtering solution
  4. need to intercept and log all the requests and responses between 3rd party components
  5. need to create some adapter between client and server, where client expects specific format of server API and server provides it in another format (so, you need to convert requests and responses on the fly)
  6. and more…

In this case, I would need to write the proxy/load balancer by myself – and it is interesting and not complicated task.

In the past I wrote proxy server using C# Reverse proxy with requests redirect in C# , this time I will use node.js which is ideal for this task.

So, here we are. The code is pretty short, simple and self-explanatory:

Continue reading