Skip to content

createMemoryHistory() | Vue Router

createMemoryHistory() creates an in-memory based history manager, which is one of Vue Router's three history modes. This mode is specifically designed for Server-Side Rendering (SSR) and testing environments. 🧠

📋 Function Signature

typescript
function createMemoryHistory(base?: string): RouterHistory

🎯 Purpose and Use Cases

The primary purpose of createMemoryHistory() is to handle SSR scenarios where there's no actual browser environment. It creates a history manager that operates entirely in memory, without interacting with the browser's URL bar or history stack.

Key Characteristics:

  • Browser-independent - No actual browser URL manipulation
  • SSR-optimized - Perfect for server-side rendering
  • Testing-friendly - Ideal for unit and integration tests
  • No URL synchronization - Users don't see URL changes

⚙️ Parameters

base - Base Path (Optional)

TypeDefaultDescription
string''The base path for the application. All routes will be relative to this path.

📤 Return Value

Returns a RouterHistory instance containing all the methods for managing the in-memory history stack.

💡 Practical Examples

Server-Side Rendering (SSR)

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

// Create router instance for SSR
const router = createRouter({
  history: createMemoryHistory(), // Use memory history for SSR
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

// Use in server-side rendering context
app.use(router)

Testing Environment

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

describe('Router Navigation', () => {
  it('should navigate correctly', async () => {
    const router = createRouter({
      history: createMemoryHistory(), // Memory history for tests
      routes: [{ path: '/test', component: TestComponent }]
    })
    
    await router.push('/test')
    expect(router.currentRoute.value.path).toBe('/test')
  })
})

With Base Path Configuration

javascript
const router = createRouter({
  history: createMemoryHistory('/app'), // Base path set to /app
  routes: [
    { path: '/', component: Home },     // Actual path: /app/
    { path: '/user', component: User }  // Actual path: /app/user
  ]
})

🔄 Comparison with Other History Modes

ModeUse CaseURL VisibilityServer Requirements
createMemoryHistorySSR, Testing❌ Not visibleNo special requirements
createWebHistoryProduction SPA✅ VisibleRequires server configuration
createWebHashHistoryStatic deployment✅ Visible (with #)No special requirements

🚨 Important Considerations

Client-Side Limitations

javascript
// Not recommended for client-side usage
const router = createRouter({
  history: createMemoryHistory(), // ❌ Avoid in client-side apps
  routes: [...]
})

// Users won't be able to use browser back/forward buttons
// No URL sharing capability
// No SEO benefits

Path Resolution Differences

javascript
const history = createMemoryHistory()
history.push('/page?query=value') 
// Query parameters are handled in memory only
// No actual browser URL changes occur

🔧 Advanced Usage Patterns

Environment-Specific History Selection

javascript
// Choose history mode based on environment
const history = typeof window === 'undefined' 
  ? createMemoryHistory()  // Server environment
  : createWebHistory()     // Client environment

const router = createRouter({
  history,
  routes: [...]
})

Testing Complex Navigation Flows

javascript
describe('Complex Navigation', () => {
  it('should handle multiple navigation steps', async () => {
    const router = createRouter({
      history: createMemoryHistory(),
      routes: [
        { path: '/', component: Home },
        { path: '/login', component: Login },
        { path: '/dashboard', component: Dashboard }
      ]
    })
    
    // Simulate user navigation flow
    await router.push('/login')
    expect(router.currentRoute.value.path).toBe('/login')
    
    await router.push('/dashboard')
    expect(router.currentRoute.value.path).toBe('/dashboard')
    
    // Test going back in memory history
    router.back()
    expect(router.currentRoute.value.path).toBe('/login')
  })
})

📚 Best Practices

1. Use for Intended Purposes Only

javascript
// ✅ Correct usage - SSR and testing
const ssrRouter = createRouter({
  history: createMemoryHistory(),
  routes: [...]
})

// ❌ Avoid in client-side applications
const clientRouter = createRouter({
  history: createMemoryHistory(), // Wrong choice for client apps
  routes: [...]
})

2. Handle Base Path Correctly

javascript
// When deploying to subdirectory
const router = createRouter({
  history: createMemoryHistory('/my-app'), // Correct base path
  routes: [
    { path: '/', component: Home }, // Serves from /my-app/
    { path: '/about', component: About } // Serves from /my-app/about
  ]
})

3. Testing Strategy

javascript
// Isolate router instances for different tests
function createTestRouter() {
  return createRouter({
    history: createMemoryHistory(),
    routes: testRoutes
  })
}

// Each test gets a fresh router instance
describe('Feature Tests', () => {
  it('test 1', async () => {
    const router = createTestRouter()
    // Test implementation
  })
  
  it('test 2', async () => {
    const router = createTestRouter() // Fresh instance
    // Test implementation
  })
})

💡 Pro Tip: When building universal applications (SSR + SPA), use environment detection to automatically choose the appropriate history mode. This ensures optimal behavior in both server and client environments.

🚀 Vue Router - 让前端路由变得简单而强大 | 构建现代化单页应用的最佳选择