We have all heard the term “proxy”. It might sound like it’s some kind of portal to a new dimension from the Matrix movies, but it turns out it’s very real...and very useful!
In a nutshell, a proxy is an intermediary application which sits between two (or more) services and processes/modifies the requests and responses in both directions. This sounds complicated, I know, but let’s try with a simpler analogy:
Imagine you meet someone from Spain, but you don’t speak Spanish. What do you do? Well, you remember that your friend Santiago knows both Spanish and English and can translate for you.
The process goes like this:
- You tell something to Santiago in English
- Santiago translates it to Spanish in his head and says it in Spanish to your new friend
- Your new friend replies back to Santiago in Spanish
- Santiago then translates it in his head and tells you the response in English
Santiago in this case serves as a proxy between you and your new friend. You can’t speak directly to each other but thanks to the translator you can relay messages (i.e. requests and responses) and have a conversation!
Okay, now that we know what a proxy is, what are the use cases for it? Well, here are a few that we, at Twilio, find really useful:
- Authorization - Forward only requests that are authorized to access a service
- Load balancing - Distribute the requests equally among many instances
- Logging - Log every requests going to a Back End API service
- And many more…
Now that you know what a proxy is and why it is useful, let’s build a simple one using Node.js!
Prerequisites
To follow along, you need Node.js and Yarn installed, which are available on Mac, Windows and Linux distributions.
Build the simple Node.js proxy
In a few easy steps we are going to create a simple proxy in Node.js which can forward requests to multiple different servers/endpoints!
The full code which will be implemented step-by-step is available on GitHub here.
Initialize the project
Let’s start by initiating a new node project: