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.
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.
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.
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.
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.
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.
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.
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.
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.