Registry / web-framework / express-history-api-fallback

express-history-api-fallback

JSON →
library2.2.1jsnpmunverified

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-fallback
INSTALL
IMPORT
SIG · EXPRESS-HISTORY-AP
E
express-history-api-fallback
web-frameworkjavascriptv2.2.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

fallback
import fallback from 'express-history-api-fallback'
import { fallback } from 'express-history-api-fallback'
The package exports a default function. Attempting a named import will result in an error.
fallback (CommonJS)
const fallback = require('express-history-api-fallback')
Standard CommonJS import pattern. No named exports are available for require().
Middleware Function
app.use(fallback('index.html', { root }))
The imported 'fallback' symbol is directly the middleware function. It expects the path and an optional options object as arguments.

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.

import fallback from 'express-history-api-fallback' import express from 'express' import path from 'path' const app = express() const publicPath = path.join(__dirname, 'public') // Assuming 'public' folder for static assets const indexHtmlPath = path.join(publicPath, 'index.html') // Serve static files first app.use(express.static(publicPath)) // Use the history API fallback for all non-static GET/HEAD requests // This should come AFTER static file serving and API routes. app.use(fallback('index.html', { root: publicPath })) // Example API route (should be placed before fallback if you want it to be matched) app.get('/api/data', (req, res) => { res.json({ message: 'Hello from API!' }) }) const PORT = process.env.PORT || 3000 app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`) console.log(`Serving static files from ${publicPath}`) })
Debug
Known issues
breakingOlder versions of Express (prior to v4.8.0) used `res.sendfile()` instead of `res.sendFile()`. While `express-history-api-fallback` attempts to handle this internally, using a very old Express version might lead to unexpected behavior or limited options. The package specifically notes that only `maxAge` and `root` options are supported with `express@<4.8`.
fix
Upgrade to Express v4.8.0 or newer to ensure full compatibility and access to all `res.sendFile()` options.
affects: <4.8.0
gotchaThe `fallback` middleware must be placed AFTER any `express.static` middleware or API routes that should be handled directly by the server. If placed before, it can intercept static file requests or API calls, serving `index.html` instead.
fix
Ensure your middleware chain has `app.use(express.static('public'))` (or similar static file server) before `app.use(fallback('index.html', { root }))`.
affects: >=2.0.0
gotchaWhen providing a relative `path` argument to `fallback()`, the `root` option must be specified. If `root` is omitted, the `path` must be an absolute path to the `index.html` file.
fix
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' }))`.
affects: >=2.0.0
gotcha`express-history-api-fallback` is specifically designed to handle only `GET` and `HEAD` HTTP requests that accept `text/html`. It will not intercept `POST`, `PUT`, `DELETE`, or other non-HTML requests. If your API routes are also returning `index.html` for these methods, another middleware or misconfiguration is likely at fault.
fix
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.
affects: >=2.0.0
Errors
Common errors & fixes
TypeError: path must be absolute or specify root to res.sendFile
The `path` argument provided to the `fallback` middleware was relative, but the `root` option was not specified in the options object.
fix
Ensure the `path` argument is an absolute file path, or provide the `root` option: `app.use(fallback('index.html', { root: __dirname + '/public' }))`.
My static assets (JS, CSS, images) are not loading, or index.html is served instead of them.
The `express-history-api-fallback` middleware is placed earlier in the Express middleware chain than the static file serving middleware (e.g., `express.static`). It intercepts requests for static files before they can be served.
fix
Reorder your middleware: `app.use(express.static('public'))` should always come before `app.use(fallback('index.html', { root }))`.
TypeScript error: Argument of type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' is not assignable to parameter of type 'PathParams'.
This specific error often arises when using `@types/express` versions that are incompatible with `@types/connect-history-api-fallback` (a similar but distinct library, though the `express-history-api-fallback` typings might follow a similar pattern). It indicates a mismatch in expected middleware types.
fix
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.
Upgrade
Version history
2.2.1latest on npm
Audit
Dependencies
expressrequiredThis package is an Express middleware and relies on Express's request/response objects and `res.sendFile()` method.
Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources
express-history-api-fallback — npm install express-history-api-fallback · libregistry