Skip to content

Instantly share code, notes, and snippets.

@lcherone
Last active December 13, 2022 17:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lcherone/5e2283e5659a2ebba1de09013ce223ba to your computer and use it in GitHub Desktop.
Save lcherone/5e2283e5659a2ebba1de09013ce223ba to your computer and use it in GitHub Desktop.
Express SPA history API express.static fallback

Mostly taken from: https://gitlab.com/sebdeckers/express-history-api-fallback, without all the repo/package fluff.

let staticPath = '/path/to/dist'

app.use(express.static(staticPath))

app.use('/', ((...args) => (req, res, next) => {
  if ((req.method === 'GET' || req.method === 'HEAD') && req.accepts('html')) {
    (res.sendFile || res.sendfile).call(res, ...args, err => err && next())
  } else next()
})('index.html', {
  root: staticPath
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment