Skip to content

Instantly share code, notes, and snippets.

@prodrammer
Last active January 8, 2020 01: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 prodrammer/3edab83929b2f46945c29f1145921821 to your computer and use it in GitHub Desktop.
Save prodrammer/3edab83929b2f46945c29f1145921821 to your computer and use it in GitHub Desktop.
Custom static file server + reverse proxy with clean HTML5 SPA routing support.
const fs = require('fs')
const url = require('url')
const path = require('path')
const http = require('http')
const static = require('node-static')
const httpProxy = require('http-proxy')
const file = new static.Server('./', { cache: 0 })
const proxy = httpProxy.createProxyServer({})
const server = http.createServer(function(req, res) {
// requests beginning with /api should be proxied
if (req.url.startsWith('/api')) {
proxy.web(req, res, { target: process.env.API_HOST })
return
}
const urlParts = url.parse(req.url)
const filePath = path.join(__dirname, urlParts.pathname)
fs.exists(filePath, exists => {
if (exists) {
file.serve(req, res)
return
}
file.serveFile('/index.html', 200, {}, req, res)
})
})
console.log(`hosting app at http://localhost:${process.env.PORT}`)
console.log(`proxying /api to ${process.env.API_HOST}`)
server.listen(process.env.PORT)
@prodrammer
Copy link
Author

npm i node-static http-proxy -D
Needs PORT (i.e. 8000) and API_HOST (i.e. http://my-api-server.com) environment variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment