Proxy Requests for Local and Remote Service Parity

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

High availability apps require that no distinction be made between local and remote services. Attached resources should be accessed by environment variables, and in doing so allow you to swap out one attached resource for another.

In this lesson we will setup a reverse proxy that directs image path requests and routes them through a defined server URL. By doing so, we decouple server requests for images which allows for easy switching from locally-served image assets to a CDN by simply updating an environment variable.

[00:00] We have an Express app that serves up a simple request of an image of our cat friend, Herman. Let's set up a proxy for our /images path. Route requests through a content delivery network dependent on a specified URL.

[00:14] Our first step is to require the Express HTTP proxy module, which is Express middleware to simply proxy requests. Then we will set up our base image URL variable to an environment variable with the same name.

[00:31] Let's create a new proxy base image URL variable. We want to check if the base image URL environment variable exists, and trigger which middleware to use based on that condition.

[00:44] Let's move up our Express static middleware to be used as the fallback in the event our environment variable is not defined. We'll also now update our middleware to use the value returned on the proxy base image URL variable.

[00:58] Let's build our proxy condition. The first parameter the proxy middleware accepts is the URL of where we want to proxy request, in this case, the value of our base image URL environment variable. The second parameter is an options object.

[01:12] Within this option, let's define a proxy request path resolver. This is a function where we can define a custom path for our image request. It expects to return a simple string or a promise. The function contains the request object as its first parameter.

[01:29] Let's set the new path variable to equal the base image URL concatenated with the requested path. We'll also log this path to the console, so we know when request are being proxied, and where they are being proxied to. Finally, we will return this new path.

[01:45] Let's save this file, as it's now ready to proxy requests. Before starting our web server, make sure to install the Express HTTP proxy module. Let's start our Node.js script, but first prepend the URL of the CDN to the new environment variable named baseImageURL.

[02:07] In this case, I am storing Herman within the Google Cloud storage bucket. Now, when we start our app, we can see from the console.log output that requests are being properly proxied through to our CDN.