express-history-api-fallback is an Express middleware designed to facilitate client-side routing for Single Page Applications (SPAs) that utilize the HTML5 History API. It addresses the common problem of 404 errors when a user directly navigates to a client-side route (e.g., `/app/dashboard`) that doesn't correspond to a static file on the server. The middleware ensures that the main `index.html` (or a specified entry point) is served instead. Currently stable at version 2.2.1, with its last known update around May 2017, the package maintains a highly focused approach. It explicitly serves the fallback only for GET/HEAD requests, for requests likely to be HTML, and only if no other static file or route matches. It leverages Express's `res.sendFile()` for efficient serving. While functional and widely used, its release cadence is dormant, indicating it's a mature, feature-complete library rather than one under active development.
npm install express-history-api-fallbackVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up `express-history-api-fallback` to serve a single-page application. It configures Express to serve static files from a 'public' directory and then applies the fallback middleware. The fallback ensures that any unhandled GET/HEAD requests (typically client-side routes) return 'index.html', enabling HTML5 History API routing. It also shows the importance of middleware order.
Upgrade to Express v4.8.0 or newer to ensure full compatibility and access to all `res.sendFile()` options.
Ensure your middleware chain has `app.use(express.static('public'))` (or similar static file server) before `app.use(fallback('index.html', { root }))`.Use either an absolute path directly: `app.use(fallback(__dirname + '/public/index.html'))` or provide the `root` option for relative paths: `app.use(fallback('index.html', { root: __dirname + '/public' }))`.Verify that `express-history-api-fallback` is the only fallback middleware in use. Ensure API routes for `POST`, `PUT`, `DELETE` are defined *before* this fallback middleware to guarantee they are handled correctly by your server-side logic.
Ensure the `path` argument is an absolute file path, or provide the `root` option: `app.use(fallback('index.html', { root: __dirname + '/public' }))`.Reorder your middleware: `app.use(express.static('public'))` should always come before `app.use(fallback('index.html', { root }))`.While `express-history-api-fallback` itself doesn't directly ship TypeScript types, if you are using `@types/express-history-api-fallback` (or similar community types), try adjusting the versions of `@types/express` or the history API fallback types to compatible versions. You might need to check the DefinitelyTyped repository for known compatibility issues or install `@ts-ignore` if a quick fix is needed and you're confident in the runtime behavior.