• Stars
    star
    1,822
  • Rank 25,486 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Fallback to index.html for applications that are using the HTML 5 history API

connect-history-api-fallback

Middleware to proxy requests through a specified index page, useful for Single Page Applications that utilise the HTML5 History API.

Table of Contents

Introduction

Single Page Applications (SPA) typically only utilise one index file that is accessible by web browsers: usually index.html. Navigation in the application is then commonly handled using JavaScript with the help of the 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. /help or /help/online 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 /index.html) whenever there is a request which fulfills the following criteria:

  1. The request is a GET or HEAD request
  2. which accepts text/html,
  3. is not a direct file request, i.e. the requested path does not contain a . (DOT) character and
  4. does not match a pattern provided in options.rewrites (see options below)

Usage

The middleware is available through NPM and can easily be added.

npm install --save connect-history-api-fallback

Import the library

var history = require('connect-history-api-fallback');

Now you only need to add the middleware to your application like so

var connect = require('connect');

var app = connect()
  .use(history())
  .listen(3000);

Of course you can also use this piece of middleware with express:

var express = require('express');

var app = express();
app.use(history());

Options

You can optionally pass options to the library when obtaining the middleware

var middleware = history({});

index

Override the index (default /index.html). This is the request path that will be used when the middleware identifies that the request path needs to be rewritten.

This is not the path to a file on disk. Instead it is the HTTP request path. Downstream connect/express middleware is responsible to turn this rewritten HTTP request path into actual responses, e.g. by reading a file from disk.

history({
  index: '/default.html'
});

rewrites

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 /soccer.html.

history({
  rewrites: [
    { from: /\/soccer/, to: '/soccer.html'}
  ]
});

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.

history({
  rewrites: [
    {
      from: /^\/libs\/.*$/,
      to: function(context) {
        return '/bower_components' + context.parsedUrl.pathname;
      }
    }
  ]
});

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 url.parse.
  • match: An Array of matched results as provided by String.match(...).
  • request: The HTTP request object.

verbose

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.

history({
  verbose: true
});

Alternatively use your own logger

history({
  logger: console.log.bind(console)
});

htmlAcceptHeaders

Override the default Accepts: headers that are queried when matching HTML content requests (Default: ['text/html', '*/*']).

history({
  htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
})

disableDotRule

Disables the dot rule mentioned above:

[…] is not a direct file request, i.e. the requested path does not contain a . (DOT) character […]

history({
  disableDotRule: true
})

More Repositories

1

dock

Bootstrap databases, MOMs and other tools that you need for development purposes
Shell
219
star
2

lucene

Node.js lib to transform: lucene query β†’ syntax tree β†’ lucene query
JavaScript
72
star
3

fuzzy.js

approximate (fuzzy) string matching in JavaScript
JavaScript
57
star
4

proxrox

Proxy services, combine origins, use SSI and more during development
TypeScript
44
star
5

event-loop-stats

Exposes stats about the libuv default loop
C++
32
star
6

svg-export

Export SVG to JPEG, PNG, PDF and SVG
Java
28
star
7

formalistic

Model forms as an immutable data tree with validators and an explicit dirty/pristine state
JavaScript
18
star
8

admin

Drop-in Node.js admin endpoint to help you analyze production issues.
JavaScript
17
star
9

java-with-javascript

JavaScript
15
star
10

mix.js

Mixins with dependency resolution and private properties (without closures)
JavaScript
13
star
11

relato

Open Source Project Statistics
JavaScript
11
star
12

movie-database-spa

SPA example
JavaScript
7
star
13

Gravatar4Java

A small library for the generation of Gravatar URLs
Java
6
star
14

commonjs-karma-saucelabs-example

minimal working example of CommonJS modules that are tested on SauceLabs
JavaScript
6
star
15

project-sidebar

Atom editor sidebar plugin that can be used to open project directories
JavaScript
5
star
16

ec2c.js

Search and connect to EC2 instances via SSH - the easy way.
JavaScript
5
star
17

rxstore

RxJS based stores for highly reactive UIs
JavaScript
3
star
18

health-check-adapter

Connect health check endpoints to Slack
Scala
3
star
19

get-logger

Node.js logging facade to decouple frameworks, libraries and application code from specific logging implementations
JavaScript
3
star
20

json-schema-validation-example

Source code for a blog post about JSON Schema and validation
Clojure
3
star
21

json-template-generator

Use JSON schema to generate compliant input templates
JavaScript
2
star
22

web-based-elgato-control-panel

Web hosted control panel for the Elgato lighting products that does not rely on mDNS
HTML
2
star
23

homebrew-dock

Ruby
1
star
24

load-balancing-example

A load balancing example with Nginx, HAProxy and Node.js
Shell
1
star
25

janus

Groovy
1
star
26

static-i18n

Statically typed i18n support for Java
Java
1
star
27

Print-Google-Code-Wiki

This project facilitates printing of Google Code wiki pages
1
star
28

java-quickstart

Alternative to maven-archetype-quickstart
Java
1
star
29

prismatic-mobile

A very simple mobile (web app) version of Prismatic.
JavaScript
1
star
30

Example-ODR-web-service-client

Java
1
star
31

ionic-overview-slides

Slides for a presentation about the Ionic framework
JavaScript
1
star
32

janus-plugin

A Janus plugin for Jenkins
Java
1
star
33

pi-setup

Ansible based Raspberry PI setup
Shell
1
star
34

FND1-session2

Sources of the second algorithms and data structures session
Java
1
star
35

nashorn-pw-check-example

Example code for an upcoming blog post about Nashorn
Java
1
star
36

signal-forwarding

docker, zombie, exec, shell, signals
Shell
1
star
37

Open-Pattern-Repository

Open source pattern catalogue. Python / Django version of the Open Pattern Repository which is hosted on Google code.
JavaScript
1
star
38

aws-vault-prompt

A zsh prompt for 99designs/aws-vault to understand what the active AWS session is and when it expires
Go
1
star
39

dotfiles

Shell
1
star
40

spa-presentation

Sources for a presentation given at Fontys University of Applied Sciences Venlo
JavaScript
1
star