Vite Plugin History API Fallback

raw JSON →
0.0.1 verified Mon Apr 27 auth: no javascript

A Vite plugin that serves as middleware for handling fallback to an index page when using HTML5 History API for multiple single-page applications. Version 0.0.1, early release with basic functionality. Differentiates from history-api-fallback by targeting Vite's dev server and supporting multiple SPA entries. Requires peer dependency vite ^2.6.4. Documentation is minimal; usage patterns may change in future versions.

error Cannot find module 'vite-plugin-history-api-fallback'
cause Package not installed or ESM require error
fix
Run npm install vite-plugin-history-api-fallback and use import instead of require.
error TypeError: historyApiFallback is not a function
cause Wrong import style; package exports a function but used incorrect import
fix
Use import historyApiFallback from 'vite-plugin-history-api-fallback' or import { historyApiFallback } from 'vite-plugin-history-api-fallback'.
error Error: The service should serve the fallback page, but the path /some/route is not found.
cause Rewrite pattern not matching or missing rewrites configuration
fix
Add a rewrite entry for the route, e.g., { from: /^\/some/, to: '/index.html' }.
gotcha Plugin only works in Vite's dev server, not during build. For production, you must configure a separate server (e.g., Express) with history-api-fallback middleware.
fix Use a production-grade fallback middleware like connect-history-api-fallback for built output.
breaking Named export 'historyApiFallback' may be the default export in future versions. Documentation shows default import but named is also supported.
fix Use import historyApiFallback from 'vite-plugin-history-api-fallback' to be safe across versions.
gotcha Plugin options 'rewrites' patterns are tested against the request URL, not the full path. Ensure patterns start with ^ to avoid unexpected matches.
fix Use regex patterns anchored at start, e.g., /^\/app1/.
deprecated The 'index' option defaults to '/index.html'. If you set it, ensure the path exists relative to the Vite root.
fix Set 'index' to your actual fallback file, e.g., '/app/index.html'.
npm install vite-plugin-history-api-fallback
yarn add vite-plugin-history-api-fallback
pnpm add vite-plugin-history-api-fallback

Configures the plugin to rewrite requests for /app1 and /app2 to their respective index files, with a global fallback to /index.html.

import { defineConfig } from 'vite';
import { historyApiFallback } from 'vite-plugin-history-api-fallback';

export default defineConfig({
  plugins: [
    historyApiFallback({
      rewrites: [
        { from: /^\/app1/, to: '/app1/index.html' },
        { from: /^\/app2/, to: '/app2/index.html' },
      ],
      index: '/index.html',
    }),
  ],
});