vue.jsexpress

404 error has been returned after "connect-history-api-fallback" middleware handed request


Need to provide the HTML5 mode for Vue frontend and Express backend.

Client:

import { createApp as createVueApplication } from "vue";
import {
  createRouter,
  createWebHistory,
  type RouteComponent,
  type Router
} from "vue-router";

const router: Router = createRouter ({
  history: createWebHistory(),
  routes: [

    {
      path: "/",
      component: TopPage
    },
    {
      path: "/users",
      component: UsersManagementPage
    }

  ]
});

createApp (RootComponent).
    use(clientRouter).
    mount("#APPLICATION");

Server:

import createExpressApplication, { type Express as ExpressApplication } from "express";
import NodeHTTPS from "https";
import morgan from "morgan";
import connectHistoryAPI_Fallback from "connect-history-api-fallback";


const expressApplication: ExpressApplication = createExpressApplication();

expressApplication.

    use(addSecurityResponseHTTP_Headers()).
    use(Express.static(/* ... */)).
    use(morgan("dev")).
    use(connectHistoryAPI_Fallback({ verbose: true }));

const HTTPS_Server: NodeHTTPS.Server = NodeHTTPS.createServer({
  /* ... */,
  expressApplication
);


HTTPS_Server.listen(
  port,
  (): void => {

    console.log("ok")

  }

);

Route / works fine, but https://localhost/users returns 404 error:

enter image description here

There "Rewriting GET /users to /index.html" log has been left by "connect-history-api-fallback", but then morgan left "GET /users 404 0.769 ms - 144" log:

enter image description here

Rewriting GET /users to /index.html
2025-07-20T23:14:54.744176357Z GET /users 404 0.769 ms - 144

According the example from official README of connect-history-api-fallback, nothing is missing:

const connect = require('connect');

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

Why "404 not found" has been returned?


Solution

  • You need to mount connect fallback middleware before mounting static files middleware, now the request is handled by static middleware first (which tries to serve users, which results with 404).

    Try this:

    // must come before static middleware
    use(connectHistoryAPI_Fallback({ verbose: true }));
    
    use(Express.static(/* ... */)).