Created
November 24, 2018 19:08
-
-
Save jeremyben/de83a1011867483562c345abc2b57fb9 to your computer and use it in GitHub Desktop.
Express Proxy Requests for Local and Remote Service Parity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
// Let's 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. | |
import * as express from 'express' | |
import * as proxy from 'express-http-proxy' | |
import { join } from 'path' | |
let proxyBaseImageUrl | |
if (process.env.BASE_IMAGE_URL) { | |
proxyBaseImageUrl = proxy(process.env.BASE_IMAGE_URL, { | |
proxyReqPathResolver(req) { | |
return process.env.BASE_IMAGE_URL + req.path | |
}, | |
}) | |
} else { | |
proxyBaseImageUrl = express.static(join(__dirname, 'public/images')) | |
} | |
const app = express() | |
app.use('/images', proxyBaseImageUrl) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment