Skip to content

Conventional Routing

Rspress uses a file-system based routing mechanism, where your directory structure directly maps to URL routes. This "convention over configuration" approach eliminates the need for manual route configuration, making project structure intuitive and maintainable.

Basic Routing Principles

File to Route Mapping

The routing system is straightforward - every .md or .mdx file in your docs directory automatically becomes a route:

docs/
├── index.md                    -> /
├── getting-started.md          -> /getting-started
├── guide/
│   ├── index.md               -> /guide
│   ├── installation.md        -> /guide/installation
│   └── configuration.md       -> /guide/configuration
└── api/
    ├── index.md               -> /api
    ├── cli.md                 -> /api/cli
    └── config-options.md      -> /api/config-options

Index Files

Files named index.md serve as directory index pages, similar to index.html in web servers:

docs/
└── products/
    ├── index.md               -> /products (landing page)
    ├── laptop.md              -> /products/laptop
    └── phone.md               -> /products/phone

When users visit /products, they'll see the content from products/index.md.

Nested Routes

Creating Deep Hierarchies

You can create arbitrarily nested route structures by organizing files in subdirectories:

docs/
└── documentation/
    ├── index.md               -> /documentation
    ├── basic/
    │   ├── index.md          -> /documentation/basic
    │   ├── syntax.md         -> /documentation/basic/syntax
    │   └── features.md       -> /documentation/basic/features
    └── advanced/
        ├── index.md          -> /documentation/advanced
        ├── customization.md  -> /documentation/advanced/customization
        └── plugins.md        -> /documentation/advanced/plugins

Best Practices for Nesting

  1. Keep it Shallow: Limit nesting to 3-4 levels for better user experience
  2. Logical Grouping: Group related content together
  3. Consistent Naming: Use clear, descriptive folder and file names
✅ Good:
docs/
└── guides/
    ├── getting-started.md
    ├── configuration.md
    └── deployment.md

❌ Too Deep:
docs/
└── guides/
    └── web/
        └── frontend/
            └── react/
                └── hooks/
                    └── use-effect.md

Dynamic Routes

Parameter-based Routes

While Rspress primarily focuses on static documentation, you can handle dynamic-like routes using query parameters and hash fragments:

markdown
<!-- docs/user.md -->
# User Profile

Access user profiles via: `/user?id=123`
Or use hash routing: `/user#john-doe`

Custom Route Handlers

For more complex routing needs, you can use React components with route parameters:

typescript
// rspress.config.ts
export default defineConfig({
  route: {
    // Custom route configuration
    exclude: ['**/fragments/**', '**/_components/**'],
  },
});

Route Configuration

Excluding Files from Routes

Sometimes you want files in your docs directory that shouldn't become routes:

typescript
// rspress.config.ts
import { defineConfig } from 'rspress/config';

export default defineConfig({
  root: 'docs',
  route: {
    // Exclude specific patterns from routing
    exclude: [
      '**/fragments/**',      // Exclude fragments directory
      '**/_*.md',             // Exclude files starting with _
      '**/README.md',         // Exclude README files
      '**/.temp/**',          // Exclude temporary files
    ],
  },
});

Including Specific Extensions

By default, Rspress processes .md and .mdx files. You can customize this:

typescript
// rspress.config.ts
export default defineConfig({
  route: {
    extensions: ['.md', '.mdx', '.jsx', '.tsx'],
  },
});

URL Slugification

Automatic Slug Generation

Rspress automatically converts file names to URL-friendly slugs:

File Name                      → URL Path
getting-started.md            → /getting-started
API Reference.md              → /api-reference
User Guide (2024).md          → /user-guide-2024
配置指南.md                    → /pei-zhi-zhi-nan

Custom Slugs via Frontmatter

Override automatic slug generation using frontmatter:

markdown
---
slug: /custom-url-path
---

# Page Title

This page will be accessible at `/custom-url-path` instead of the default.

Slash-based Routing

Create custom route hierarchies regardless of file location:

markdown
---
slug: /api/v2/authentication
---

# Authentication Guide

File location: `docs/auth-guide.md`
Accessible at: `/api/v2/authentication`

Use relative or absolute paths for internal navigation:

markdown
<!-- Relative links -->
[Configuration Guide](./configuration.md)
[Go to parent](../index.md)

<!-- Absolute links -->
[Home](/)
[API Reference](/api)
[Getting Started](/guide/getting-started)

<!-- With hash anchors -->
[Jump to Installation](/guide/getting-started#installation)

Rspress validates internal links during build:

bash
# Build will warn about broken links
npm run build

 Warning: Broken link detected
  From: /guide/getting-started.md
  To:   /guide/nonexistent-page.md

Special Route Behaviors

404 Page

Create a custom 404 page by adding a 404.md file:

markdown
<!-- docs/404.md -->
---
title: Page Not Found
---

# 404 - Page Not Found

The page you're looking for doesn't exist.

[Return to Home](/)

Redirect Handling

Configure redirects in your config file:

typescript
// rspress.config.ts
export default defineConfig({
  builderConfig: {
    html: {
      meta: {
        'http-equiv': 'refresh',
        content: '0; url=/new-location',
      },
    },
  },
});

Or use a dedicated plugin:

typescript
// rspress.config.ts
import { defineConfig } from 'rspress/config';

export default defineConfig({
  plugins: [
    // Custom redirect plugin
    {
      name: 'redirect-plugin',
      async routeGenerated(routes) {
        // Add redirect logic
        routes.push({
          path: '/old-path',
          redirect: '/new-path',
        });
      },
    },
  ],
});

Route Metadata

Frontmatter Configuration

Control route behavior with frontmatter:

markdown
---
title: Custom Page Title
description: SEO-friendly description
keywords: [rspress, routing, documentation]
slug: /custom-path
sidebar_position: 2
sidebar_label: Short Label
---

# Page Content

Access Route Information

Use route data in your MDX components:

mdx
import { usePageData } from 'rspress/runtime';

export function RouteInfo() {
  const { page } = usePageData();

  return (
    <div>
      <p>Current Path: {page.routePath}</p>
      <p>Page Title: {page.title}</p>
    </div>
  );
}

<RouteInfo />

Practical Examples

Example 1: Documentation Site Structure

docs/
├── index.md                           # Homepage: /
├── introduction.md                    # /introduction
├── quick-start.md                     # /quick-start
├── guides/
│   ├── index.md                      # /guides
│   ├── installation.md               # /guides/installation
│   ├── basic-usage.md                # /guides/basic-usage
│   └── advanced-features.md          # /guides/advanced-features
├── api-reference/
│   ├── index.md                      # /api-reference
│   ├── cli.md                        # /api-reference/cli
│   └── configuration.md              # /api-reference/configuration
└── examples/
    ├── index.md                      # /examples
    ├── basic-example.md              # /examples/basic-example
    └── advanced-example.md           # /examples/advanced-example

Example 2: Multi-version Documentation

docs/
├── index.md                           # Latest version homepage
├── v1/
│   ├── index.md                      # /v1
│   ├── guide.md                      # /v1/guide
│   └── api.md                        # /v1/api
├── v2/
│   ├── index.md                      # /v2
│   ├── guide.md                      # /v2/guide
│   └── api.md                        # /v2/api
└── latest/                           # Symlink or copy of current version
    ├── index.md                      # /latest
    ├── guide.md                      # /latest/guide
    └── api.md                        # /latest/api

Example 3: Blog-style Structure

docs/
├── index.md                           # Blog homepage
├── posts/
│   ├── 2024-01-15-first-post.md     # /posts/2024-01-15-first-post
│   ├── 2024-02-20-second-post.md    # /posts/2024-02-20-second-post
│   └── 2024-03-10-third-post.md     # /posts/2024-03-10-third-post
└── categories/
    ├── tutorials/
    │   └── index.md                  # /categories/tutorials
    └── updates/
        └── index.md                  # /categories/updates

Troubleshooting

Common Issues

  1. Route Not Found

    • Check file extension (.md or .mdx)
    • Verify file is not excluded in config
    • Ensure file is within the root directory
  2. Conflicting Routes

    • Avoid files with same name at same level
    • Check for duplicate custom slugs in frontmatter
  3. Links Not Working

    • Use consistent path format (with or without trailing slashes)
    • Prefer absolute paths for clarity
    • Include file extensions in relative links

Debugging Tips

bash
# Enable verbose logging
npm run dev -- --debug

# Check generated routes
# Routes are logged during build
npm run build

# Verify route structure
tree docs/ -I 'node_modules|doc_build'

Performance Considerations

Route Loading Strategy

Rspress uses code splitting to load routes efficiently:

typescript
// Routes are automatically split
// Each page loads only what it needs
- Homepage: ~50KB
- Guide pages: ~30KB each
- Total bundle split across routes

Optimize Large Route Trees

For sites with many routes (100+):

  1. Use exclude patterns to reduce route generation time
  2. Leverage lazy loading for heavy components
  3. Consider pagination for large lists
typescript
// rspress.config.ts
export default defineConfig({
  route: {
    exclude: ['**/old-versions/**', '**/deprecated/**'],
  },
});

Next Steps

Now that you understand Rspress's routing system, you can:

  1. Learn about Navigation & Sidebar configuration
  2. Explore Automatic Navigation Generation
  3. Discover MDX & React Components for dynamic content

Best Practices

  • Keep URLs short and descriptive
  • Use kebab-case for file names
  • Maintain consistent directory structure
  • Test all internal links before deployment

Content is for learning and research only.