Skip to content

Multi-Sidebar Configuration for VitePress

For larger documentation sites, a single sidebar can quickly become cluttered. VitePress allows you to define multiple sidebars that automatically change based on the user's current URL path. This ensures that readers only see links relevant to the section they are currently exploring.

Defining Sidebar Types

Using a recursive interface makes your sidebar configuration flexible and easy to maintain. By defining a single SidebarItem, you can represent a simple link, a heading with nested items, or a combination of both. Create a file named sidebarTypes.ts to house this structure.

typescript
// sidebarTypes.ts

export interface SidebarItem {
  text: string
  link?: string
  items?: SidebarItem[]
}

export type Sidebar = SidebarItem[]

The text property is the display label, the link is the destination path, and the items array allows you to nest further SidebarItem objects to create groups.

Creating Category Sidebars

To keep your project organized, create dedicated files for each main section of your site in a folder like .vitepress/sidebars/. This separation makes it easier to update individual sections without affecting the entire site.

Example: sidebars/guides.ts

typescript
import { Sidebar } from '../sidebarTypes'

export const guidesSidebar: Sidebar = [
  {
    text: 'Getting Started',
    items: [
      { text: 'Introduction', link: '/guides/introduction' },
      { text: 'Quick Start', link: '/guides/quick-start' }
    ]
  },
  {
    text: 'Advanced Features',
    items: [
      { text: 'Configuration', link: '/guides/config' },
      { text: 'Deployment', link: '/guides/deploy' }
    ]
  }
]

Mapping Sidebars to Paths

Once your category sidebars are created, you need to map them to specific URL prefixes. Create a central sidebar.ts file in your .vitepress folder to act as the main entry point for your configuration.

typescript
import { Sidebar } from './sidebarTypes'
import { guidesSidebar } from "./sidebars/guides"
import { apiSidebar } from "./sidebars/api"

export type SidebarConfig = Record<string, Sidebar>

export const sidebarConfig: SidebarConfig = {
  '/guides/': guidesSidebar,
  '/api/': apiSidebar
}

TIP

Always ensure your path keys end with a trailing slash. If you use /guides without the final slash, VitePress might fail to match sub-pages correctly within that directory.

In this setup, when a user navigates to any URL starting with /guides/, VitePress will automatically load the guidesSidebar.

Integration

Finally, ensure your central sidebarConfig is imported and assigned to the themeConfig section of your main VitePress configuration file.

typescript
// .vitepress/config.ts
import { defineConfig } from 'vitepress'
import { sidebarConfig } from './sidebar'

export default defineConfig({
  themeConfig: {
    sidebar: sidebarConfig
  }
})