| | |

Vue Router 02 🧭 History Modes & Server Fallbacks — createWebHistory, createWebHashHistory, and Memory Mode

⏱️ Estimated read: 12 min | |

Choosing the right history mode is one of the most critical architectural decisions when setting up Vue Router. The history mode determines how the URL is represented in the browser’s address bar and how the application interacts with the browser’s navigation history stack. While Vue Router handles the internal logic of switching components, the history mode dictates whether those changes are visible to the server or remain entirely internal to the client.

In Vue Router 4, there are three primary modes: HTML5 History, Hash, and Memory. Each mode has distinct advantages, trade-offs, and server-side requirements. Most modern web applications aim for the HTML5 History mode because it provides “clean” URLs (e.g., /user/profile instead of /#/user/profile), which are better for SEO and professional aesthetics. However, this mode introduces a significant challenge: since the URLs are virtual and handled by JavaScript, a hard refresh or a direct link entry will cause the browser to request a non-existent file from the server, resulting in a 404 error.

This chapter explores the mechanics of each history mode, the scenarios where one is preferred over the others, and the essential server-side configurations required to make Single Page Applications (SPAs) work correctly in production. We will cover configuration for popular web servers like Nginx and Apache, as well as modern hosting platforms like Vercel and Netlify.

Key point: createWebHistory is the modern standard for production apps but requires a server “fallback” configuration to redirect all traffic to index.html, whereas createWebHashHistory works out-of-the-box on any server but uses a # symbol in the URL.


Why exists

The Server-Side 404 problem.
Browsers are designed to request specific files from a server. In an SPA, the file /about doesn’t actually exist on the server; it’s a virtual route handled by Vue. Without a fallback configuration, the server sees a request for a missing file and returns a 404. History modes and fallbacks exist to bridge this gap between client-side routing and server-side file serving.

The URL Aesthetic problem.
Early SPAs relied on the “hash” (#) to manage state because changes to the hash don’t trigger a page reload. However, hashes are often seen as “ugly” or “hacky” in modern web design. The HTML5 History API exists to allow developers to use standard URL structures without the full-page refresh, making SPAs indistinguishable from traditional multi-page sites.

The SEO and Analytics problem.
Search engine crawlers and analytics tools sometimes struggle with hash-based URLs. While Google’s crawler has improved significantly, standard paths are still considered the gold standard for indexability and precise tracking. History modes provide the flexibility to choose the path structure that best suits a project’s marketing and discovery needs.

The Environment Isolation problem.
Not all environments have a browser URL bar. For example, when running tests in a Node.js environment or performing Server-Side Rendering (SSR), there is no window.location. Memory history exists to provide a routing mechanism that lives entirely in-memory, allowing the same routing logic to work in non-browser environments.

The Legacy Hosting problem.
Some developers work in environments where they have no control over the server configuration (e.g., uploading files to a basic FTP server or a restricted CMS). In these cases, the developer cannot implement a fallback redirect. Hash mode exists as a “plug-and-play” solution that works regardless of the server’s capabilities.


a. HTML5 History Mode: createWebHistory

HTML5 History mode is the recommended mode for most web applications. It utilizes the history.pushState and history.replaceState APIs to change the URL without a page reload. This results in “clean” URLs that look like traditional websites. When a user clicks a RouterLink, Vue Router updates the address bar and swaps the component, but the browser does not send a new request to the server.

import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  // The 'base' argument is optional. Use it if your app 
  // is hosted in a subfolder like /my-app/
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', component: () => import('./views/Home.vue') },
    { path: '/dashboard', component: () => import('./views/Dash.vue') }
  ]
});

The import.meta.env.BASE_URL is a Vite-provided variable that ensures the router understands its root path, which is especially helpful when deploying to a sub-directory. While this mode is visually superior, it relies on the server being “SPA-aware.”

If a user is at myapp.com/dashboard and hits the refresh button, the browser sends a GET request to the server for /dashboard. Since that file doesn’t exist (only index.html exists), the server returns a 404. To fix this, you must configure your server to serve index.html for any request that doesn’t match a physical file (like an image or a CSS file).


b. Hash Mode: createWebHashHistory

Hash mode uses the URL hash character (#) to simulate a full URL. Because the portion of the URL after the # is never sent to the server, the server only ever sees a request for the root index.html file. This means no special server configuration is required. It is the safest choice for projects hosted on platforms that do not support URL rewriting.

import { createRouter, createWebHashHistory } from 'vue-router';

const router = createRouter({
  // URLs will look like: example.com/#/about
  history: createWebHashHistory(),
  routes: [
    { path: '/about', component: () => import('./views/About.vue') }
  ]
});

The primary drawback is the visual presence of the # and its potential impact on SEO. Additionally, some internal corporate tools or legacy security filters might strip or block hash fragments. However, for internal dashboards, prototypes, or sites hosted on GitHub Pages (without custom workarounds), Hash mode is an excellent, low-friction solution.

Internally, Vue Router listens for the hashchange event. When the hash changes, the router parses the string after the # and matches it against the defined routes. This is a very robust mechanism that works even in older browsers.


c. Memory Mode and Server Fallbacks

createMemoryHistory does not interact with the browser’s address bar at all. It maintains the routing state in an internal variable. This is primarily used for Server-Side Rendering (SSR) where the server needs to “render” a specific route to a string to send to the client, or in unit testing where you want to simulate navigation without a browser environment.

import { createRouter, createMemoryHistory } from 'vue-router';

const router = createRouter({
  // No URL change will be visible in the browser
  history: createMemoryHistory(),
  routes: [ /* ... */ ]
});

Server Fallback Configurations

When using createWebHistory, the server must be configured to handle the fallback. The logic is always: “If the requested resource is not a file and not a directory, serve index.html.”

Nginx Configuration:
The try_files directive is the key here. It attempts to serve the URI as a file, then as a directory, and finally falls back to /index.html.

location / {
  try_files $uri $uri/ /index.html;
}

Apache (.htaccess) Configuration:
Apache uses mod_rewrite. This script checks if the request is not for an actual file or directory before rewriting the request to index.html.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

Express.js (Node) Configuration:
In a Node environment, you can use the connect-history-api-fallback middleware to handle this automatically.

const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();

app.use(history()); // Must be used before static files
app.use(express.static('./dist'));

Complete Example Session

// ============================================
// PART 1: CHOOSE HISTORY MODE (router/index.ts)
// ============================================
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';

// Toggle this based on environment or deployment needs
const useHistoryMode = true;

const router = createRouter({
  history: useHistoryMode 
    ? createWebHistory() 
    : createWebHashHistory(),
  routes: [
    { path: '/', component: () => import('../views/Home.vue') },
    { path: '/login', component: () => import('../views/Login.vue') }
  ]
});

// ============================================
// PART 2: SERVER CONFIG - NGINX (nginx.conf)
// ============================================
/*
server {
    listen 80;
    server_name example.com;
    root /var/www/dist;
    index index.html;

    location / {
        # This line is critical for HTML5 History Mode
        try_files $uri $uri/ /index.html;
    }
}
*/

// ============================================
// PART 3: SERVER CONFIG - VERCEL (vercel.json)
// ============================================
/*
{
  "rewrites": [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}
*/

// ============================================
// PART 4: SERVER CONFIG - NETLIFY (_redirects)
// ============================================
/*
# Simply redirect everything to index.html with a 200 status
/*   /index.html   200
*/

// ============================================
// PART 5: HANDLING SUBDIRECTORIES
// ============================================
// If hosted at example.com/admin/
const subDirRouter = createRouter({
  history: createWebHistory('/admin/'),
  routes: []
});

// ============================================
// PART 6: MEMORY HISTORY FOR TESTING
// ============================================
// vitest.setup.ts
const testRouter = createRouter({
  history: createMemoryHistory(),
  routes: []
});

// ============================================
// PART 7: CHECKING CURRENT MODE
// ============================================
console.log(router.options.history); // Inspects history implementation

// ============================================
// PART 8: DYNAMIC BASE URL
// ============================================
// Uses Vite's base config (from vite.config.ts)
const base = import.meta.env.BASE_URL;

// ============================================
// PART 9: EXPRESS FALLBACK MIDDLEWARE
// ============================================
/*
const history = require('connect-history-api-fallback');
app.use(history({
  verbose: true, // Log rewrites for debugging
  index: '/index.html'
}));
*/

// ============================================
// PART 10: SUMMARY OF STEPS
// ============================================
// 1. Choose createWebHistory.
// 2. Build for production (npm run build).
// 3. Upload 'dist' folder to server.
// 4. Configure server to redirect 404s to index.html.

The parts above outline the decision-making process for history modes and provide the specific configuration syntax for various production server environments to prevent 404 errors.


Quick Reference

History Mode Comparison

ModeFunctionURL ExampleServer Config
HTML5createWebHistory/aboutRequired (Rewrite)
HashcreateWebHashHistory/#/aboutNone
MemorycreateMemoryHistory(None)N/A (Internal)

Common Server Fallback Logic

PlatformConfiguration FileKey Syntax
Nginxnginx.conftry_files $uri $uri/ /index.html;
Apache.htaccessRewriteRule . /index.html [L]
Netlify_redirects/* /index.html 200
Vercelvercel.json"source": "/(.*)", "destination": "/index.html"

Vite Configuration (Base Path)

Scenariovite.config.tscreateWebHistory
Root Domainbase: '/'createWebHistory('/')
Subfolderbase: '/my-app/'createWebHistory('/my-app/')

Best Practices

✅ Do This:

// Use HTML5 History mode for production websites
const history = createWebHistory();                            // ✅

// Always provide a fallback to index.html on the server
// (Prevents 404 on refresh)                                  // ✅

// Use import.meta.env.BASE_URL to handle flexible deployments
const historySub = createWebHistory(import.meta.env.BASE_URL); // ✅

// Use Memory history for unit tests to avoid side effects
const testHist = createMemoryHistory();                        // ✅

❌ Don’t Do This:

// Don't use Hash mode for public-facing, SEO-sensitive sites
// (Worse search engine visibility)                           // ❌

// Don't forget the server fallback when using WebHistory
// (Users will see 404 on direct navigation)                  // ❌

// Don't hardcode the base path in createWebHistory
// (Makes it harder to move the app to a different folder)    // ❌

// Don't use WebHistory in Node-based testing environments
// (It will crash because 'window' is undefined)             // ❌

Common Pitfalls

PitfallWhy It HappensFix
404 on RefreshUsing WebHistory without server rewriteAdd Nginx/Apache fallback rules
Assets not loadingIncorrect base path in build configSet base: '/subfolder/' in vite.config.ts
Link sharing failsShared link leads to 404 on the serverImplement server-side redirect to index.html
Analytics mismatchHash change not tracked as page viewUse a plugin or switch to WebHistory
SSR hydration errorMemory history used incorrectly on clientEnsure mode matches environment (Node vs Browser)
Blank PageBASE_URL is undefined or incorrectCheck Vite environment variables

Real-World Examples

1. Nginx SPA Config

try_files $uri $uri/ /index.html;

2. Apache SPA Config

RewriteRule . /index.html [L]

3. Netlify Redirect File

/* /index.html 200

4. Memory History for SSR

const history = createMemoryHistory(); // For Node.js server

5. Vite Base Path Setting

export default defineConfig({ base: '/portfolio/' });

6. Dynamic Mode Selection

const h = isDev ? createWebHashHistory() : createWebHistory();

7. Vercel Rewrite Logic

"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]

8. Firebase Hosting Config

"hosting": { "rewrites": [{ "source": "**", "destination": "/index.html" }] }

9. Sub-directory Router Instance

const router = createRouter({ history: createWebHistory('/app/') });

10. Express History Middleware

app.use(require('connect-history-api-fallback')());

Visual

Routing Resolution: Client vs. Server

┌──────────────────────────────────────────────────────────┐
│  USER TYPES: example.com/profile                         │
└──────────────────────────┬───────────────────────────────┘
                           │
             ┌─────────────▼──────────────┐
             │       WEB SERVER           │
             └─────────────┬──────────────┘
                           │
             ┌─────────────┴──────────────┐
             │   DOES /profile EXIST?     │
             └──────┬──────────────┬──────┘
                    │              │
             NO (SPA Route)      YES (Image/CSS)
                    │              │
     ┌──────────────▼──────┐   ┌───▼──────────────────┐
     │  REWRITE TO:        │   │  SERVE ACTUAL FILE   │
     │  index.html         │   │                      │
     └──────────────┬──────┘   └──────────────────────┘
                    │
     ┌──────────────▼──────┐
     │  VUE ROUTER (Client)│
     │  Reads URL path     │
     │  Renders Profile.vue│
     └─────────────────────┘

Hash Mode vs. History Mode URLs

┌──────────────────────────────────────────────────────────┐
│  URL STRUCTURE COMPARISON                                │
│                                                          │
│  HISTORY MODE:                                           │
│  https://myapp.com/products/123                          │
│  └───────┬───────┘└─────┬─────┘                          │
│      Domain         Clean Path (Sent to Server)          │
│                                                          │
│  HASH MODE:                                              │
│  https://myapp.com/#/products/123                        │
│  └───────┬───────┘ └──────┬──────┘                       │
│      Domain        Fragment (NOT sent to Server)         │
│                                                          │
└──────────────────────────────────────────────────────────┘

Memory History Flow (Testing/SSR)

┌──────────────────────────────────────────────────────────┐
│  MEMORY HISTORY (No Browser)                             │
│                                                          │
│  [ Router State ] ◄───► [ Internal Array of Paths ]      │
│          │                                               │
│          ▼                                               │
│  [ Current Component: Home ]                             │
│          │                                               │
│  (Navigation Triggered Programmatically)                  │
│          │                                               │
│          ▼                                               │
│  [ Current Component: Settings ]                         │
│                                                          │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Cleanest URLcreateWebHistory
Easiest DeploymentcreateWebHashHistory
Server TaskRewrite non-files to index.html
Environmentimport.meta.env.BASE_URL
API dependencyhistory.pushState (HTML5)
SSR compatiblecreateMemoryHistory
Fallback Status200 (Success, not 404)
Nginx Keytry_files

Key takeaways:

  • HTML5 History mode is standard. It provides the most professional URLs and is better for SEO, but it requires the server to be configured to handle route fallbacks .
  • Server configuration is mandatory for WebHistory. Without a rewrite rule that points missing paths to index.html, users will experience 404 errors when refreshing the page or using direct links .
  • Hash mode is a reliable fallback. It works on any server without configuration because the hash fragment is ignored by the server, making it ideal for restricted hosting environments .
  • Memory history is for non-browser contexts. It allows Vue Router to function in Node.js for tasks like unit testing or generating static/server-rendered content .
  • Base paths matter. If your application is not at the root of your domain, you must specify the base path in both your build configuration and your router instance .
  • Redirects should return a 200 status. When the server falls back to index.html, it should serve the file with a success status so the client-side router can take over smoothly .

Remember: The history mode you choose dictates the relationship between your application and the world outside the browser. While createWebHistory offers the best user experience, it requires a partnership with your web server. If you cannot configure your server, createWebHashHistory is your safety net. Always test your production build with a hard refresh to ensure your fallbacks are working correctly.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!