Skip to content

Instantly share code, notes, and snippets.

@jeremyben
Created November 24, 2018 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyben/de83a1011867483562c345abc2b57fb9 to your computer and use it in GitHub Desktop.
Save jeremyben/de83a1011867483562c345abc2b57fb9 to your computer and use it in GitHub Desktop.
Express Proxy Requests for Local and Remote Service Parity
// 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