createWebHistory() | Vue Router
createWebHistory() creates a HTML5 history mode implementation for Vue Router, which uses the browser's native history.pushState API for clean URLs without hash fragments. 🌐
📋 Function Signature
typescript
function createWebHistory(base?: string): RouterHistory🎯 Purpose and Use Cases
The createWebHistory() function is designed for modern web applications that want clean, SEO-friendly URLs without the # hash fragment. It's the recommended choice for most production applications.
Key Characteristics:
- ✅ Clean URLs - No
#in URLs, better for SEO and user experience - ✅ Browser History Integration - Leverages native browser history API
- ✅ Server Configuration Required - Needs proper server setup for SPA routing
- ❌ Not for Static Hosting - Requires server-side configuration
⚙️ Parameters
base - Base Path (Optional)
| Type | Default | Description |
|---|---|---|
string | '' | The base URL for the application. All routes will be relative to this path. |
📤 Return Value
Returns a RouterHistory instance configured for HTML5 history mode.
💡 Practical Examples
Basic Usage
javascript
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(), // HTML5 history mode
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})With Base Path
javascript
// When deploying to a subdirectory like https://example.com/my-app/
const router = createRouter({
history: createWebHistory('/my-app/'), // Base path
routes: [
{ path: '/', component: Home }, // Serves from /my-app/
{ path: '/about', component: About } // Serves from /my-app/about
]
})Production Configuration
javascript
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'home',
component: () => import('./views/Home.vue')
},
{
path: '/products/:id',
name: 'product',
component: () => import('./views/Product.vue'),
props: true
}
]
})🔄 Comparison with Other History Modes
| Mode | URL Format | Server Requirements | SEO Friendly |
|---|---|---|---|
createWebHistory | example.com/about | ✅ Required | ✅ Yes |
createWebHashHistory | example.com/#/about | ❌ None | ❌ No |
createMemoryHistory | No URL change | ❌ None | ❌ No |
🚨 Server Configuration Requirements
Apache (.htaccess)
apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>Nginx
nginx
location / {
try_files $uri $uri/ /index.html;
}Express.js
javascript
const express = require('express')
const path = require('path')
const app = express()
// Serve static files
app.use(express.static(path.join(__dirname, 'dist')))
// Handle SPA routing
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'))
})🔧 Advanced Usage
Dynamic Base Path
javascript
// Determine base path dynamically
function getBasePath() {
if (window.location.hostname === 'localhost') {
return '/'
} else if (window.location.pathname.startsWith('/staging')) {
return '/staging'
} else {
return '/production'
}
}
const router = createRouter({
history: createWebHistory(getBasePath()),
routes: [...]
})Error Handling
javascript
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
// Handle navigation errors
router.onError((error) => {
if (error.message.includes('Failed to fetch')) {
// Handle network errors
showOfflineMessage()
}
})🔗 Related APIs
createWebHashHistory()- Hash-based history alternativecreateMemoryHistory()- Memory history for SSRRouterHistory- History manager interface
📚 Best Practices
1. Proper Server Configuration
javascript
// Always configure your server to handle SPA routing
// This ensures direct URL access works correctly
const router = createRouter({
history: createWebHistory(), // Requires server configuration
routes: [
{ path: '/', component: Home },
{ path: '/:pathMatch(.*)*', component: NotFound } // Catch-all route
]
})2. Base Path Considerations
javascript
// When deploying to subdirectories
const base = process.env.NODE_ENV === 'production'
? '/my-app/'
: '/'
const router = createRouter({
history: createWebHistory(base),
routes: [...]
})3. Development vs Production
javascript
// Use hash history in development for easier setup
// Switch to web history in production for better URLs
const history = process.env.NODE_ENV === 'production'
? createWebHistory()
: createWebHashHistory()
const router = createRouter({
history,
routes: [...]
})💡 Pro Tip: For the best user experience, always set up proper server configuration when using
createWebHistory(). This ensures that users can bookmark pages and use the browser's back/forward buttons correctly.