Table of Contents
Middleware to proxy requests through a specified index page, useful for Single Page Applications that utilise the HTML5 History API.
Table of Contents
Single Page Applications (SPA) typically only utilise one index file that is
accessible by web browsers: usually
index.html. Navigation in the application
HTML5 History API.
This results in issues when the user hits the refresh button or is directly
accessing a page other than the landing page, e.g.
as the web server bypasses the index file to locate the file at this location.
As your application is a SPA, the web server will fail trying to retrieve the file and return a 404 - Not Found
message to the user.
This tiny middleware addresses some of the issues. Specifically, it will change
the requested location to the index you specify (default being
whenever there is a request which fulfills the following criteria:
- The request is a GET request
- which accepts
- is not a direct file request, i.e. the requested path does not contain a
.(DOT) character and
- does not match a pattern provided in options.rewrites (see options below)
The middleware is available through NPM and can easily be added.
npm install --save connect-history-api-fallback
Import the library
var history = ;
Now you only need to add the middleware to your application like so
var connect = ;var app =;
Of course you can also use this piece of middleware with express:
var express = ;var app = ;app;
You can optionally pass options to the library when obtaining the middleware
var middleware = ;
Override the index (default
Override the index when the request url matches a regex pattern. You can either rewrite to a static string or use a function to transform the incoming request.
The following will rewrite a request that matches the
/\/soccer/ pattern to
Alternatively functions can be used to have more control over the rewrite process. For instance, the following listing shows how requests to
/libs/jquery/jquery.1.12.0.min.js and the like can be routed to
./bower_components/libs/jquery/jquery.1.12.0.min.js. You can also make use of this if you have an API version in the URL path.
The function will always be called with a context object that has the following properties:
- parsedUrl: Information about the URL as provided by the URL module's
- match: An Array of matched results as provided by
- request: The HTTP request object.
This middleware does not log any information by default. If you wish to activate logging, then you can do so via the
verbose option or by specifying a logger function.
Alternatively use your own logger
Override the default
Accepts: headers that are queried when matching HTML content requests (Default:
Disables the dot rule mentioned above:
[…] is not a direct file request, i.e. the requested path does not contain a
.(DOT) character […]