# blade47/fumadocs Wiki
## Technical docs: Overview
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/overview
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json)
- [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json)
- [packages/api-docs/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json)
- [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts)
- [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json)
- [packages/basehub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json)
- [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json)
- [packages/local-md/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json)
- [packages/content/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json)
- [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/base-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json)
- [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts)
- [packages/epub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json)
- [packages/obsidian/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/package.json)
- [packages/radix-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json)
- [packages/cli/src/commands/shared.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts)
- [packages/typescript/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json)
- [packages/shared/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json)
- [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts)
- [packages/twoslash/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json)
- [packages/doc-gen/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/asyncapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json)
- [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json)
- [packages/sanity/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts)
- [packages/story/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json)
- [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json)
- [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml)
- [packages/preview/fumadocs.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/fumadocs.config.ts)
## Overview
Fumadocs is a modern, framework-agnostic documentation ecosystem designed for React applications, providing a modular architecture that separates core document processing, source loading, and layout presentation [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4). It addresses the complexity of building documentation sites by decoupling headless primitives and build-time content compilation from opinionated styling layers and frontend frameworks. The project is organized as a monorepo workspace containing runtime engines, bundler integration plugins, and user interface implementations [[packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4). Fumadocs integrates closely with tools like [BaseHub Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/basehub-integration) and [MDX Runtime Compilation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-runtime-compilation) to support flexible content workflows and dynamic rendering [[packages/basehub/package.json:4-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json#L4-L4), [packages/mdx/src/runtime/server.ts:1-2](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L1-L2).
## Architecture and Design Philosophy
Fumadocs is architected around a strict separation of concerns, decoupling framework-agnostic document processing, source loading, and state management from concrete UI implementations [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4). The core runtime library (`fumadocs-core`) delivers navigation tree generation, internationalization negotiation, [search server indexing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing), [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting), and remark/rehype markdown AST transformations without depending on a specific frontend framework or bundler [[packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/core/package.json:42-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L42-L87).
The ecosystem provides explicit [framework routing adapters](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/framework-routing-adapters) and runtime provider packages for Next.js, React Router, TanStack, Waku, and Vite [[packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33), [packages/radix-ui/package.json:104-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L104-L108). This modular layer separation allows documentation content models and source schemas to be compiled independently of presentation components, which are supplied separately through accessible UI packages like `fumadocs-ui` backed by [Radix UI primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives) [[packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4), [packages/radix-ui/package.json:134-143](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L134-L143).
| Layer Category | Primary Package | Export Modules & Target Responsibilities |
| :--- | :--- | :--- |
| Core Engine | `fumadocs-core` | `./source`, `./page-tree`, `./i18n`, `./search`, `./highlight`, `./mdx-plugins` |
| Content Compilation | `fumadocs-mdx` | `./node`, `./vite`, `./next`, `./rolldown`, `./webpack/mdx`, `./runtime/server` |
| UI & Layouts | `fumadocs-ui` | `./layouts/docs`, `./layouts/flux`, `./components/codeblock`, `./components/dialog/search` |
| Content Adapter | `@fumadocs/content` | `.` (index), `./runtime` for standard-schema type-safe document fetching |
| Shared Utilities | `shared` | Internal helper workspace for CLI tooling, translation specs, and glob file scanning |
Sources: [packages/core/package.json:20-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L20-L88), [packages/content/package.json:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L17-L21), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117), [packages/shared/package.json:4-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json#L4-L8), [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44)
> [!NOTE]
> The `@fumadocs/content` adapter depends on `@standard-schema/spec` and `fuma-content` to decouple validation schemas from specific file-system loaders [[packages/content/package.json:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L34), [packages/content/package.json:43-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L43-L46).
Sources: [packages/content/package.json:32-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L46)
> [!IMPORTANT]
> Framework integration is completely decoupled via dedicated export entry points in `fumadocs-core` (such as `./framework/next`, `./framework/react-router`, `./framework/tanstack`, and `./framework/waku`), preventing runtime coupling to Next.js [packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33).
Sources: [packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33)
## Monorepo Package Structure and Roles
### Core Runtime and Content Compilers
The Fumadocs workspace organizes its source code into specialized packages, separating the framework-agnostic runtime engine from build-time content compilation and UI layers. The core runtime package, `fumadocs-core`, provides foundational services including source file discovery, page tree calculations, internationalization negotiation, search server indexing, syntax highlighting, and unified remark/rehype markdown AST transformations [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/core/package.json:42-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L42-L87).
Build-time processing is handled by `fumadocs-mdx`, which exposes integration entry points for bundlers and runtime loaders, including Next.js, Vite, Webpack, Rolldown, and Bun [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44). Content validation and schema mapping across standard schemas are delegated to `@fumadocs/content`, which relies on `fuma-content` and `@standard-schema/spec` [packages/content/package.json:32-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L46).
Sources: [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/core/package.json:42-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L42-L87), [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44), [packages/content/package.json:32-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L46)
> [!IMPORTANT]
> The `fumadocs-mdx` package maintains separate sub-exports for static node compilation (`./node`, `./node/loader`) and client/server runtimes (`./runtime/server`, `./runtime/browser`, `./runtime/dynamic`), preventing server-only modules from leaking into browser bundles [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44).
Sources: [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44)
### UI Implementations and Layouts
Presentation components are factored into distinct UI packages that target specific primitive ecosystems. The two primary UI design implementations are `fumadocs-ui` (backed by Radix UI primitives) and `@fumadocs/base-ui` (built for Base UI) [packages/base-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4). Both packages provide identical export paths for documentation layouts, navigation slots, code blocks, search dialogs, and interactive UI widgets [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117).
| Package Name | Primary Dependency Stack | Target UI Library & Layout Exports |
| :--- | :--- | :--- |
| `fumadocs-ui` (`radix-ui`) | Radix Primitives (`@radix-ui/react-*`), `motion`, `next-themes` | `./layouts/docs`, `./layouts/flux`, `./layouts/notebook`, `./layouts/home` [packages/radix-ui/package.json:58-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L58-L90), [packages/radix-ui/package.json:134-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L134-L153) |
| `@fumadocs/base-ui` | Base UI primitives, `motion`, `next-themes` | `./layouts/docs`, `./layouts/flux`, `./layouts/notebook`, `./layouts/home` [packages/base-ui/package.json:58-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L58-L90) |
| `@fumadocs/api-docs` | Radix Accordion/Dialog/Select, `@fumari/stf` | `./schema`, `./codegen`, `./components/schema`, `./components/dialog` [packages/api-docs/package.json:18-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L18-L42), [packages/api-docs/package.json:56-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L56-L67) |
Sources: [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117), [packages/api-docs/package.json:18-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L18-L67), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4)]
> [!NOTE]
> The CLI utility references UI registries via the configuration mapping in `UIRegistries`, associating `'base-ui'` with `fumadocs/base-ui` and `'radix-ui'` with `fumadocs/radix-ui` [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4).
Sources: [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4)
### Tooling, Extensibility, and Preview Packages
Specialized plugins and developer tooling are isolated into independent workspace packages to keep runtime footprints minimal [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-L4), [packages/typescript/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L4), [packages/twoslash/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L4), [packages/doc-gen/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L4), [packages/create-app/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L4). These include `fumadocs-typescript` for type table extractions via `ts-morph` [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49), `fumadocs-twoslash` for Shiki-based compiler diagnostics [packages/twoslash/package.json:45-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L45-L53), `fumadocs-docgen` for remark utilities like `remark-ts2js` [packages/doc-gen/package.json:26-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L26-L30), [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50), `fumadocs-preview` for Waku-backed fast content previews with AI search features [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-L4), [packages/preview/package.json:35-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L35-L88), and `create-fumadocs-app` for project scaffolding [packages/create-app/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L4), [packages/create-app/package.json:43-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L43-L52).
Sources: [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-L4), [packages/preview/package.json:35-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L35-L88), [packages/typescript/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L4), [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49), [packages/twoslash/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L4), [packages/twoslash/package.json:45-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L45-L53), [packages/doc-gen/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L4), [packages/doc-gen/package.json:26-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L26-L30), [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50), [packages/create-app/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L4), [packages/create-app/package.json:43-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L43-L52)
## Content Compilation and Source Processing
### Document Schemas and Collection Configuration
Document parsing and type-safe frontmatter validation rely on `@standard-schema/spec` [[packages/content/package.json:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L34), [packages/mdx/package.json:56-58](https://github.com/blade47/fumadocs/package.json#L56-L58)]. The `@fumadocs/content` package provides helper utilities like `docsMdxCollection` and `docsCollection` to structure directories containing MDX documents and metadata files [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53). By default, `docsMdxCollection` integrates `mdxPreset` configurations with remark include plugins for content composition [packages/content/src/index.ts:24-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L24-L32).
Sources: [packages/content/package.json:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L34), [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53), [packages/mdx/package.json:56-58](https://github.com/blade47/fumadocs/package.json#L56-L58)]
> [!NOTE]
> The `docsMdxCollection` builder automatically falls back to `pageSchema` for frontmatter validation when a custom schema is omitted [packages/content/src/index.ts:16-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L19).
Sources: [packages/content/src/index.ts:16-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L19)]
### Runtime and Dynamic MDX Compilation
The `fumadocs-mdx` package supports runtime compilation and dynamic execution of MDX files through its runtime modules [[packages/mdx/package.json:37-40](https://github.com/blade47/fumadocs/package.json#L37-L40)]. The `dynamic` utility resolves collections and compiles raw content entries into hydrated properties [packages/mdx/src/runtime/dynamic.ts:47-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L95).
```typescript
async function executeMdx(compiled: string, options: ExecuteOptions = {}) {
const { opts: scopeOpts, ...scope } = options.scope ?? {};
const fullScope = {
opts: {
...(scopeOpts as object),
...(options.jsxRuntime ?? jsxRuntimeDefault),
baseUrl: options.baseUrl,
},
...scope,
};
const hydrateFn = new AsyncFunction(...Object.keys(fullScope), compiled);
return await hydrateFn.apply(hydrateFn, Object.values(fullScope));
}
```
Sources: [packages/mdx/src/runtime/dynamic.ts:32-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L32-L45)]
The `DocsCollection` class manages code generation by listening to emission hooks and constructing virtual code modules that link back to stores [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70). Concurrently, `toFumadocsSource` maps underlying file collection stores into structured static sources containing page and metadata entries [packages/content/src/runtime.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L42).
Sources: [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70), [packages/content/src/runtime.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L42)]
## Presentation Primitives and Layout Systems
### Headless UI Implementations and UI Registries
Fumadocs separates visual styling and component layout architectures into two alternative UI implementations: `@fumadocs/base-ui` and `fumadocs-ui` (backed by Radix UI primitives) [packages/base-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4). These UI variants share identical export paths for foundational primitives, layout slots, and navigation contexts while consuming distinct underlying primitives. The command line utility references these two packages under the identifiers `base-ui` and `radix-ui` [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4).
| UI Package | Package Name | Registry Key | Primary Dependencies |
| :--- | :--- | :--- | :--- |
| Base UI Version | `@fumadocs/base-ui` | `base-ui` | Tailored base primitives and CSS exports |
| Radix UI Version | `fumadocs-ui` | `radix-ui` | `@radix-ui/react-*`, `motion`, `next-themes` |
Sources: [packages/base-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4), [packages/radix-ui/package.json:131-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L131-L154)]
> [!IMPORTANT]
> Both UI packages expose identical module entry points for layouts (`./layouts/docs`, `./layouts/flux`, `./layouts/notebook`, `./layouts/home`), search dialogs, and component slots, enabling seamless switching between Radix and Base UI runtimes without altering layout consumption code [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117).
Sources: [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117)]
### Layout Presets and Markdown Compilation Pipeline
Layout presets determine how documentation pages and structural containers render[packages/preview/src/pages/[...slugs].tsx:80-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L80-L96). The [preview server](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/preview-server) configuration supports dynamic markdown rendering pipelines incorporating remark and rehype plugins for math, headings, GFM, code tabs, package manager persistence, and Mermaid diagrams[packages/preview/src/pages/[...slugs].tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46).
```tsx
const compiler = createMarkdownCompiler({
remarkPlugins: [
remarkGfm,
remarkMath,
remarkMdxMermaid,
plugin(remarkHeading, { generateToc: false }),
plugin(remarkNpm, { persist: { id: 'package-manager' } }),
remarkCodeTab,
],
remarkRehypeOptions: {
passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'],
},
rehypePlugins: [
rehypeKatex,
plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }),
plugin(rehypeToc, { exportToc: { as: 'data' } }),
],
});
```
Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46)]
The dynamic page renderer inspects the layout preset configuration (`docs` or `flux`) to load corresponding layout modules and page components dynamically[packages/preview/src/pages/[...slugs].tsx:80-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L80-L96). When rendering documentation containers, AI search widgets are conditionally injected alongside layout slots if AI support is enabled[packages/preview/src/pages/[...slugs].tsx:113-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L113-L138).
Sources: [packages/preview/src/pages/...slugs.tsx:80-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L80-L96), [packages/preview/src/pages/...slugs.tsx:113-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L113-L138)]
## Tooling and Extensibility Ecosystem
### Specification Generators and Language Integration Plugins
Fumadocs provides specialized packages that ingest specification files and foreign source code, transforming them into documentation structures. The `fumadocs-openapi` package parses OpenAPI v3 and Swagger definitions to generate MDX documentation pages, client request generators, and interactive UI components, with exports for C#, cURL, Go, Java, JavaScript, and Python request generators[packages/openapi/package.json:2-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L37). Similarly, `@fumadocs/asyncapi` processes AsyncAPI specifications to generate documentation for asynchronous message-driven architectures with dedicated server and internationalization entry points[packages/asyncapi/package.json:2-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L25). For Python codebases, `fumadocs-python` and the underlying `fumapy` module inspect source code and docstrings using Griffe and Griffe typing extensions to extract API documentation[packages/python/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L4), [packages/python/pyproject.toml:2-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L8).
| Tool / Plugin Package | Package Identifier | Primary Purpose | Key Export Endpoints |
| :--- | :--- | :--- | :--- |
| OpenAPI Generator | `fumadocs-openapi` | OpenAPI v3/Swagger MDX doc generation & request building | `.`, `./ui`, `./scalar`, `./requests/generators/*` |
| AsyncAPI Generator | `@fumadocs/asyncapi` | AsyncAPI event-driven messaging documentation | `.`, `./ui`, `./server`, `./i18n` |
| Python Docgen | `fumadocs-python` | Python docstring extraction and component presets | `.`, `./components`, `./preset.css` |
| Story Integration | `@fumadocs/story` | Component prop parsing and interactive playgrounds | `.`, `./next`, `./vite`, `./type-tree` |
Sources: [packages/python/package.json:2-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L32), [packages/openapi/package.json:2-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L37), [packages/asyncapi/package.json:2-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L25), [packages/python/pyproject.toml:2-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L8), [packages/story/package.json:2-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json#L2-L24)]
> [!NOTE]
> The `@fumadocs/story` package supports multiple build systems and frameworks, offering dedicated entry points for Next.js (`./next`, `./next/client`), Vite (`./vite`, `./vite/client`), and Webpack (`./webpack/story`) alongside type-tree extraction[packages/story/package.json:14-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json#L14-L24).
Sources: [packages/story/package.json:14-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json#L14-L24)]
### Standalone Content Sources and Export Utilities
Additional packages extend content ingestion and distribution capabilities beyond standard Markdown and MDX files. The `@fumadocs/local-md` package parses local Markdown files and executes embedded expressions in Node and browser runtimes, exposing execution targets such as `executor`, `executor-native`, and `executor-virtual`[packages/local-md/package.json:2-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json#L2-L30). For offline reading, `fumadocs-epub` bundles compiled documentation pages, assets, and tables of contents into EPUB ebooks[packages/epub/package.json:2-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json#L2-L26). Integration with headless CMS platforms is supported by registry modules like `fumadocs/sanity`, which provides installable component snippets for rendering portable text collections [packages/sanity/registry/index.ts:1-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts#L1-L100).
Sources: [packages/local-md/package.json:2-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json#L2-L30), [packages/epub/package.json:2-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json#L2-L26), [packages/sanity/registry/index.ts:1-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts#L1-L100)]
### Developer CLI Workflows
The [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli) (`@fumadocs/cli`) and site scaffolding tool (`create-fumadocs-app`) orchestrate project initialization, component management, and export actions[packages/cli/src/index.ts:1-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L1-L116), [packages/create-app/package.json:2-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L31). The CLI runner initializes configuration files, customizes UI layouts, downloads registry components via local or HTTP connectors, exports documentation to EPUB format, and converts file tree structures into JavaScript or MDX modules[packages/cli/src/index.ts:17-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L17-L114).
```typescript
program
.command('add')
.description('add a new component to your docs')
.argument('[components...]', 'components to download')
.option('--dir ', 'the root url or directory to resolve registry')
.action(async (input: string[], options: { config?: string; dir?: string }) => {
const config = await createOrLoadConfig(options.config);
const client = createClientFromDir(options.dir);
await add(input, client, config);
});
const exportCmd = program.command('export').description('export documentation to various formats');
exportCmd
.command('epub')
.description('export documentation to EPUB format (run after production build)')
.requiredOption('--framework ', 'React framework: next, tanstack-start, react-router, waku')
.option('--output ', 'output file path', 'docs.epub')
.option('--scaffold-only', 'only scaffold the EPUB route, do not copy')
.action(async (options: { output?: string; framework: string; scaffoldOnly?: boolean }) => {
await exportEpub({
output: options.output,
framework: options.framework,
scaffoldOnly: options.scaffoldOnly,
});
});
```
Sources: [packages/cli/src/index.ts:44-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L44-L69)]
> [!WARNING]
> The EPUB export command (`fumadocs export epub`) must be run after a successful production build, and requires specifying the target React framework via the required `--framework` option[packages/cli/src/index.ts:57-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L57-L69).
Sources: [packages/cli/src/index.ts:57-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L57-L69)]
## Where to go next
| I want to… | Read |
| --- | --- |
| How do you scaffold and run a minimal Fumadocs documentation site from scratch? | [Quick Start](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start) |
| What are the responsibilities and dependencies across the packages in the Fumadocs workspace? | [Project Structure](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure) |
| How does Fumadocs discover, parse, validate, and manage collections of documents and meta files into structured sources? | [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) |
| How are hierarchical navigation trees built, transformed, sorted, and decorated with status badges and icons? | [Page Tree Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation) |
| How are documents scanned, structured, and indexed on the server using Orama, Flexsearch, or Algolia engines? | [Search Server Indexing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing) |
| How do client dialogs query search backends including local endpoints, Orama Cloud, Algolia, and Mixedbread? | [Search Client Integrations](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-client-integrations) |
| How does Shiki integration format code blocks, manage themes, parse meta attributes, and handle transformer tokens? | [Syntax Highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) |
| What remark and rehype AST transformations occur for admonitions, headings, steps, LLM exports, and mermaid diagrams? | [Markdown AST Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/markdown-ast-plugins) |
| How are framework-agnostic navigation, dynamic links, and router abstractions provided for Next.js, Vite, React Router, and Waku? | [Framework Routing Adapters](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/framework-routing-adapters) |
| How does Fumadocs handle locale switching, fallback languages, language negotiation, and translated page trees? | [Internationalization Support](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/internationalization-support) |
| How does fumadocs-mdx compile MDX documents, track file metadata, and integrate with build tools via unified plugins? | [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) |
| How do the Webpack, Next.js, Vite, and Rolldown loader plugins intercept and transform documentation source files? | [Bundler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins) |
| How do plugins generate type-safe schema validation, last-modified git timestamps, and virtual index files for documentation? | [Content Compiler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins) |
| How are MDX strings compiled and evaluated dynamically on the server and in the browser for remote content? | [MDX Runtime Compilation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-runtime-compilation) |
| What foundational primitive components does fumadocs-ui/base-ui provide for dialogs, navigation, cards, and forms? | [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) |
| How does fumadocs-ui/radix-ui implement accessible primitives like popovers, collapsibles, scroll areas, and search dialogs? | [Radix UI Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives) |
| How do sidebar slots, headers, containers, footers, and page actions compose documentation layouts across frameworks? | [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) |
| How does the Flux layout arrange the modern dual-sidebar, responsive navbar, and article structure? | [Ui Layouts Layout](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/ui-layouts-layout) |
| How are table of contents trees extracted, highlighted dynamically on scroll, and displayed in sidebars or inline components? | [Table of Contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) |
| How do interactive client and server code blocks handle syntax styling, copy actions, dynamic tab groups, and file trees? | [Code Block Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/code-block-components) |
| How do CSS presets, Tailwind typography plugins, and theme variations (such as Catppuccin, Shadcn, and Vitepress) apply styling? | [Theme Styles and CSS](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/theme-styles-and-css) |
| How does the shared fumadocs-api-docs package handle schema dereferencing, mock sampling, and reusable UI widgets? | [API Docs Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/api-docs-primitives) |
| How are OpenAPI v3 and Swagger specifications parsed, validated, and converted into static MDX documentation pages? | [OpenAPI Document Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-document-generation) |
| How does the OpenAPI renderer render interactive API endpoint cards, request parameters, response schemas, and curl try-it-out widgets? | [OpenAPI Interactive UI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-interactive-ui) |
| How does Fumadocs automatically generate code snippets for cURL, JavaScript, Python, Go, and C# from OpenAPI endpoint schemas? | [Code Sample Generators](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/code-sample-generators) |
| How are AsyncAPI specifications loaded, dereferenced, and converted into asynchronous messaging documentation? | [AsyncAPI Document Processing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-document-processing) |
| How does Fumadocs render protocol-specific message configurations for Kafka, MQTT, WebSockets, AMQP, and SQS? | [AsyncAPI Protocol Bindings](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-protocol-bindings) |
| How does Fumadocs read Obsidian vaults and convert wikilinks, callouts, block IDs, and comments to standard MDX? | [Obsidian Vault Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/obsidian-vault-integration) |
| How does fumadocs-local-md parse pure markdown and execute embedded expressions with Node and browser clients? | [Local Markdown Runtime](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/local-markdown-runtime) |
| How does Fumadocs integrate with Content Collections for static type-safe document fetching and metadata mapping? | [Content Collections Adapter](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/content-collections-adapter) |
| How does the fumapy Python module inspect docstrings and generate structured documentation data for Fumadocs? | [Python Docstring Extractor](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/python-docstring-extractor) |
| How does Fumadocs ingest structured portable text and document trees from Sanity headless CMS into docs pages? | [Sanity CMS Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/sanity-cms-integration) |
| How does Fumadocs fetch and render documentation collections stored within BaseHub headless CMS? | [BaseHub Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/basehub-integration) |
| How does Fumadocs provide manual and automated installations of documentation components compatible with shadcn/ui? | [shadcn/ui Docs Registry](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/shadcn-ui-docs-registry) |
| How do the CLI commands customize components, add registry snippets, export EPUB documents, and inspect file trees? | [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli) |
| How does create-fumadocs-app scaffold projects across frameworks (Next.js, React Router, TanStack Start) and linters? | [Create App Generator](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator) |
| How does the built-in Waku-based preview server provide live hot reloading, AI chat search, and dynamic OG image generation? | [Preview Server](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/preview-server) |
| How does Fumadocs extract TypeScript AST interfaces, type aliases, and JSDoc tags to build interactive type tables? | [TypeScript Type Table Extraction](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/typescript-type-table-extraction) |
| How does fumadocs-twoslash integrate with Shiki to display compiler diagnostics, type hints, and hover popups? | [Twoslash Type Hover](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/twoslash-type-hover) |
| How does the fumadocs-story package parse component props and render live interactive playground controls inside documentation? | [Interactive Component Playground](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/interactive-component-playground) |
| How does STF parse, format, and render structured documentation payloads across server and client boundaries? | [Structured Text Format](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/structured-text-format) |
| How does fumadocs-epub bundle documentation pages, assets, stylesheets, and tables of contents into EPUB ebooks? | [EPUB Book Export](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/epub-book-export) |
| How do fumadocs-vite and vite-data provide HMR and data resolution for non-Next.js build tools? | [Vite Integration Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/vite-integration-plugins) |
## Related
- [Quick Start](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start)
- [Project Structure](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure)
- [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader)
---
## Technical docs: Search Query Regex Compilation
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/how-it-works/search-query-regex-compilation
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/search/orama/create-server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts)
- [packages/core/src/search/orama/search/simple.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts)
- [packages/core/src/search/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts)
## Overview
### Introduction
The execution flow from `createFromSource` down to `buildRegexFromQuery` represents the core lifecycle of a search request in Fumadocs, transitioning from document loader outputs to indexed search servers, execution against an Orama database instance, and finally result post-processing with dynamic search term highlighting.
```mermaid
sequenceDiagram
participant Source as create-server.ts
participant Simple as simple.ts
participant Index as index.ts
Source->>Source: createFromSource()
Source->>Source: getCurrentServer()
Source->>Source: initServer()
Source->>Source: createI18nSearchAPI() / initAdvancedSearch()
Source->>Source: initSearchServers()
Source->>Simple: initSimpleSearch() / searchSimple()
Simple->>Index: createContentHighlighter()
Index->>Index: buildRegexFromQuery()
Index-->>Simple: RegExp | null
Simple-->>Source: SortedResult[]
```
Sources: [packages/core/src/search/orama/create-server.ts:273-324](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L273-L324), [packages/core/src/search/orama/search/simple.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L27), [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43)
```mermaid
flowchart TD
A[createFromSource] --> B[getCurrentServer]
B --> C[initServer]
C --> D{Has i18n?}
D -- Yes --> E[createI18nSearchAPI]
D -- No --> F[initAdvancedSearch]
E --> G[initSearchServers]
G --> H[initSimpleSearch]
H --> I[searchSimple]
I --> J[createContentHighlighter]
J --> K[buildRegexFromQuery]
```
Sources: [packages/core/src/search/orama/create-server.ts:187-324](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L187-L324), [packages/core/src/search/orama/search/simple.ts:5-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L19), [packages/core/src/search/index.ts:36-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L48)
### Step 1: createFromSource
`createFromSource` initiates the search server configuration using a document loader or an asynchronous loader function. It sets up a WeakMap-based cache linked to specific loader outputs to optimize server initialization and handle re-indexing when loader instances change.
Sources: [packages/core/src/search/orama/create-server.ts:273-279](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L273-L279)
### Step 2: getCurrentServer
`getCurrentServer` resolves the current loader output—evaluating it if passed as a function—and checks the internal cache for an existing server promise. If a cached server instance does not exist for the current loader reference, it triggers server initialization and stores the resulting promise in the cache.
Sources: [packages/core/src/search/orama/create-server.ts:306-314](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L306-L314)
### Step 3: initServer
`initServer` processes all pages retrieved from the loader. It maps each page through `buildIndex` to create searchable index records, generates missing breadcrumbs automatically, assigns locale metadata, and inspects whether internationalization (`_i18n`) is configured.
Sources: [packages/core/src/search/orama/create-server.ts:280-304](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L280-L304)
### Step 4: createI18nSearchAPI
When internationalization is enabled (`loader._i18n`), `createI18nSearchAPI` wraps search operations across multiple language contexts. It initiates background server setup per language via `initSearchServers` and routes queries to the appropriate language handler based on user options or defaults.
Sources: [packages/core/src/search/orama/create-server.ts:178-259](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L178-L259)
### Step 5: initSearchServers
`initSearchServers` iterates through all configured languages in the internationalization settings, filters document indexes matching the current locale, maps locale codes to compatible stemmers or tokenizers, and instantiates language-specific search servers.
Sources: [packages/core/src/search/orama/create-server.ts:190-237](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L190-L237)
### Step 6: initSimpleSearch
`initSimpleSearch` constructs a simple search server instance over an Orama database (`createDBSimple`). It exposes export capabilities for static bundle generation and a `search` method that queries the underlying database instance using `searchSimple`.
Sources: [packages/core/src/search/orama/create-server.ts:78-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L78-L98)
### Step 7: searchSimple
`searchSimple` executes the search query against the Orama database with tolerance and term boosting configured. Upon receiving search hits, it invokes `createContentHighlighter` to generate highlighted content strings for presentation.
Sources: [packages/core/src/search/orama/search/simple.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L27)
### Step 8: createContentHighlighter
`createContentHighlighter` accepts a query string or precompiled regular expression. If given a string, it hands the query to `buildRegexFromQuery` to generate a case-insensitive matching pattern, returning helper methods for text and Markdown highlighting.
Sources: [packages/core/src/search/index.ts:47-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L47-L49)
### Step 9: buildRegexFromQuery
`buildRegexFromQuery` cleans and splits the query string into distinct search terms, escapes special regular expression characters via `escapeRegExp`, deduplicates terms, and builds a combined case-insensitive `RegExp` matching group for highlighting matches. If the query trims down to an empty string, it returns `null`.
Sources: [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43)
## Key Observations
- **Cross-Module Boundaries:** The flow bridges higher-level content source loading (`@/source/loader`) with Orama indexing infrastructure (`@orama/orama`), routing through server endpoint wrappers and text processing utilities in `@/search`.
- **Caching Strategy:** Server instances are cached using a `WeakMap` mapped to loader output references. This ensures memory efficiency while preventing redundant re-indexing unless a fresh loader instance is produced.
- **Robust Query Normalization:** Query strings undergo trimming, whitespace splitting, deduplication, and regex escaping inside `buildRegexFromQuery` to safely handle arbitrary user inputs without crashing parser or highlighter steps.
---
## Technical docs: MDX Configuration Preset Loading
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/how-it-works/mdx-configuration-preset-loading
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
- [packages/mdx/src/config/load-from-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts)
- [packages/mdx/src/config/build.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts)
- [packages/mdx/src/config/preset.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts)
## Overview
The execution flow from `createMDX` through `applyMdxPreset` bridges Next.js configuration integration with Fumadocs' content management engine. When initializing MDX for a Next.js project, the core framework compiles user-defined source configurations, builds collections, and automatically configures remark and rehype processor options. This ensures that markdown and MDX files are parsed correctly across different build environments (bundler vs. runtime).
Sources: [packages/mdx/src/next/index.ts:30-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L122)
## Execution Flow
### Step 1: createMDX
The process begins when `createMDX` is invoked with optional configuration options (`CreateMDXOptions`). It sets up the Next.js core environment using `createNextCore` and `applyDefaults`, and ensures that initialization occurs only once by checking the `_FUMADOCS_MDX` environment variable. It returns a curried function that injects custom Webpack and Turbopack rules for `.mdx`, `.md`, `.json`, and `.yaml` files into the Next.js configuration.
Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L38)
### Step 2: init
Invoked asynchronously during setup, the `init` function manages core initialization and coordinates the development server lifecycle. It defines internal helper routines (`initOrReload` and `devServer`) to load configurations and watch file changes during local development.
Sources: [packages/mdx/src/next/index.ts:124-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L124-L182)
### Step 3: devServer
If running in a development environment, `devServer` sets up a file watcher using `chokidar`. It monitors the configuration file and all registered collection directories. When the configuration file changes, the watcher safely closes itself, reloads the configuration, restarts the development server routine, and re-initializes the server watcher.
Sources: [packages/mdx/src/next/index.ts:132-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L132-L176)
### Step 4: initOrReload
The `initOrReload` function orchestrates core startup by calling `core.init` with the result of loading the configuration file. Once initialized, it instructs the core to emit generated artifacts (such as index files or type definitions) with writing enabled (`write: true`).
Sources: [packages/mdx/src/next/index.ts:125-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L125-L130)
### Step 5: loadConfig
The `loadConfig` function handles compiling and importing the source configuration file. When the `build` flag is set to true, it triggers `compileConfig` using `esbuild` to bundle the source configuration into a portable ESM module (`.mjs`). It then appends a timestamp query parameter to bust module cache before dynamically importing the compiled config and passing the raw exports to `buildConfig`.
Sources: [packages/mdx/src/config/load-from-file.ts:35-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L35-L44)
### Step 6: buildConfig
The `buildConfig` function parses raw configuration exports, mapping collection objects and global settings. It constructs collection instances and exposes a `getMDXOptions` method. When MDX options are requested for a specific collection or environment, it evaluates global or collection-level options and delegates preset generation to `applyMdxPreset`.
Sources: [packages/mdx/src/config/build.ts:118-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts#L118-L180)
### Step 7: applyMdxPreset
Finally, `applyMdxPreset` takes the user's MDX options and returns an asynchronous function that resolves processor options for the specified build environment (`bundler` or `runtime`). If the preset is set to `'minimal'`, it returns the options unchanged. Otherwise, it loads `fumadocs-core/mdx-plugins` and configures standard remark plugins (such as `remarkGfm`, `remarkHeading`, `remarkImage`, and `remarkStructure`) and rehype plugins (such as `rehypeCode` and `rehypeToc`), adjusting options based on whether it is targeting a bundler or runtime environment.
Sources: [packages/mdx/src/config/preset.ts:50-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L132)
---
## Architecture Diagrams
### Sequence Diagram
```mermaid
sequenceDiagram
participant Next as Next.js Config
participant Index as packages/mdx/next
participant Core as Core Engine
participant Loader as loadConfig
participant Builder as buildConfig
participant Preset as applyMdxPreset
Next->>Index: createMDX(options)
Index->>Index: init(isDev, core)
Index->>Core: initOrReload()
Core->>Loader: loadConfig(core, true)
Loader->>Loader: compileConfig(core)
Loader->>Builder: buildConfig(loaded, cwd)
Builder->>Preset: applyMdxPreset(options)
Preset-->>Builder: ProcessorOptions
Builder-->>Loader: LoadedConfig
Loader-->>Core: Resolved config
Core-->>Index: Initialized
```
Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L38), [packages/mdx/src/config/load-from-file.ts:35-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L35-L44), [packages/mdx/src/config/build.ts:118-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts#L118-L180), [packages/mdx/src/config/preset.ts:50-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L132)
### Flowchart
```mermaid
flowchart TD
A[createMDX] --> B[init]
B --> C{isDev?}
C -->|Yes| D[devServer & initOrReload]
C -->|No| E[initOrReload]
D --> F[loadConfig]
E --> F[loadConfig]
F --> G[compileConfig with esbuild]
G --> H[buildConfig]
H --> I[applyMdxPreset]
I --> J[Return ProcessorOptions]
```
Sources: [packages/mdx/src/next/index.ts:30-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L182), [packages/mdx/src/config/load-from-file.ts:6-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L6-L44), [packages/mdx/src/config/build.ts:118-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts#L118-L180), [packages/mdx/src/config/preset.ts:50-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L132)
---
## Key Observations
- **Cross-Module Boundaries:** The flow bridges Next.js integration hooks (`packages/mdx/src/next/index.ts`) with configuration building (`packages/mdx/src/config/load-from-file.ts` and `build.ts`) and unified plugin management (`packages/mdx/src/config/preset.ts`).
- **Error Handling:** Configuration compilation checks `transformed.errors.length` and throws an error if `esbuild` fails. Dynamic imports and file watcher logic ensure that updates to config files gracefully restart the development environment.
- **Caching & Dynamic Reloading:** `loadConfig` invalidates import caches by appending a millisecond timestamp hash query parameter to the file URL, ensuring fresh configuration loads during development reloads.
Sources: [packages/mdx/src/config/load-from-file.ts:25-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L25-L41)
---
## Technical docs: Quick Start
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts)
- [packages/create-app/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts)
- [packages/preview/src/cli/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts)
- [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml)
- [packages/python/fumapy/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py)
- [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx)
- [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json)
- [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json)
- [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts)
- [packages/create-app/scripts/sync.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/scripts/sync.ts)
- [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx)
- [packages/local-md/src/dev/react-client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts)
- [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts)
- [packages/preview/fumadocs.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/fumadocs.config.ts)
- [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts)
- [packages/cli/src/commands/export-epub.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/export-epub.ts)
- [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
- [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json)
- [packages/create-app/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/index.ts)
- [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json)
- [packages/cli/src/commands/add.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/add.ts)
- [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json)
- [packages/local-md/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json)
- [packages/preview/src/cli/commands.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts)
- [packages/asyncapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json)
- [packages/python/fumapy/mksource/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py)
## Overview
Getting started with Fumadocs involves bootstrapping a dedicated documentation workspace, configuring content collections, rendering routing hierarchies, and managing development environments. The initialization workflow is powered by [Create App Generator](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator) and the [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli), which scaffold template applications, install dependencies, and configure linters across supported frameworks.
Sources: [packages/create-app/src/bin.ts:22-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts#L22-L54), [packages/cli/src/index.ts:17-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L17-L27)
## Bootstrapping with CLI tooling
### Scaffolding Workspaces and Command Options
Fumadocs provides dedicated command-line utilities to initialize documentation projects, manage configuration files, and interact with component registries. The primary package for scaffolding workspaces is `create-fumadocs-app`, which is versioned at `16.0.123` and bundles dependencies such as `@clack/prompts`, `tinyexec`, and `ts-morph`.
Sources: [packages/create-app/package.json:3-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L3-L52)
Once inside a workspace, the `fumadocs` CLI (`@fumadocs/cli`) offers core routines for workspace initialization, layout customization, component downloads, and tree transformations. The CLI is powered by `commander` and `picocolors`.
Sources: [packages/cli/src/index.ts:4-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L4-L20)
| Command | Aliases | Options | Description |
| :--- | :--- | :--- | :--- |
| `fumadocs` (default) | none | `--config ` | Initializes a `./cli.json` configuration file if one does not already exist |
| `customise` | `customize` | `--dir `, `--config ` | Simple way to customize layouts with Fumadocs UI |
| `add` | none | `--dir `, `--config ` | Downloads and adds new components to your docs |
| `export epub` | none | `--framework `, `--output `, `--scaffold-only` | Exports documentation to EPUB format |
| `tree` | none | `--js`, `--no-root`, `--import-name ` | Generates JavaScript or MDX file trees from JSON or directory arguments |
Sources: [packages/cli/src/index.ts:17-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L17-L83)
> [!NOTE]
> The default action of the `fumadocs` binary checks for the existence of `./cli.json`. If it does not exist, it initializes the file and logs a success message; if it already exists, it emits a notice indicating that the config file is already present.
> Sources: [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L21-L27)
### Registry Connectors and Framework Targets
When executing commands that fetch remote or local components or layouts, the CLI resolves registry sources using `createClientFromDir`. Short-form directory shortcuts map specific keywords to designated endpoints.
```typescript
const dirShortcuts: Record = {
':preview': 'https://preview.fumadocs.dev/registry',
':dev': 'http://localhost:3000/registry',
};
```
Sources: [packages/cli/src/index.ts:39-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L39-L42)
The `createClientFromDir` function inspects the directory path or shortcut. If the destination begins with `http://` or `https://`, it instantiates an `HttpRegistryConnector`; otherwise, it returns a `LocalRegistryConnector`.
```typescript
function createClientFromDir(dir = 'https://fumadocs.dev/registry') {
if (dir in dirShortcuts) dir = dirShortcuts[dir];
return dir.startsWith('http://') || dir.startsWith('https://')
? new HttpRegistryConnector(dir)
: new LocalRegistryConnector(dir);
}
```
Sources: [packages/cli/src/index.ts:108-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L108-L114)
> [!WARNING]
> When executing `fumadocs export epub`, the `--framework` option is required. The supported framework names accepted by the command parser are `next`, `tanstack-start`, `react-router`, and `waku`.
> Sources: [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L57-L63)
## Configuring content collections and schemas
### Declaring Document Collections
Documentation sources are structured through collection configuration helpers provided by `@fumadocs/content`. The `docsCollection` function binds MDX documentation documents and metadata files into a unified store, accepting directory paths and custom validation schemas for both types of content.
```typescript
export interface DocsCollectionConfig<
FrontmatterSchema extends StandardSchemaV1 | undefined,
MetaSchema extends StandardSchemaV1 | undefined,
> {
dir: string;
docs: Omit, 'dir'>;
meta: Omit, 'dir'>;
}
export function docsCollection<
FrontmatterSchema extends StandardSchemaV1 | typeof pageSchema = typeof pageSchema,
MetaSchema extends StandardSchemaV1 | typeof metaSchema = typeof metaSchema,
>(config: DocsCollectionConfig) {
return {
index: new DocsCollection(),
meta: dataCollection({ dir: config.dir, ...config.meta }),
doc: docsMdxCollection({ dir: config.dir, ...config.docs }),
};
}
```
Sources: [packages/content/src/index.ts:35-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L35-L53)
The underlying `DocsCollection` class extends the base `Collection` implementation from `fuma-content/collections`. During its emit lifecycle (`onEmit.pipe`), it dynamically generates code files for code generation workflows, writing module imports and export definitions for runtime stores.
```typescript
export class DocsCollection extends Collection {
constructor() {
super();
this.onEmit.pipe(async (data, ctx) => {
const file = await ctx.createCodeGenerator(`${this.name}.ts`, ({ codegen }) => {
const docName = `${this.name}$doc`;
const metaName = `${this.name}$meta`;
codegen.addNamedImport([docName], `./${docName}`);
codegen.addNamedImport([metaName], `./${metaName}`);
codegen.addNamedImport(['docsStore'], '@fumadocs/content/runtime');
codegen.push(`export const ${this.name} = docsStore(${docName}, ${metaName})`);
});
data.push(file);
return data;
});
}
```
Sources: [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70)
> [!NOTE]
> The `DocsCollection` generator creates code files named `.ts` that import the respective document and metadata files, import `docsStore` from `@fumadocs/content/runtime`, and export a combined store constant.
> Sources: [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L59-L65)
### Defining Content Schemas and Runtime Stores
Content schemas validate frontmatter attributes against standard schema specifications such as `@Standard-schema/spec`. By default, `docsMdxCollection` and `docsCollection` fall back to `pageSchema` and `metaSchema` imported from `fumadocs-core/source/schema`.
```typescript
export function docsMdxCollection<
FrontmatterSchema extends StandardSchemaV1 | typeof pageSchema = typeof pageSchema,
>(config: DocsMDXCollectionConfig) {
const { options = {}, frontmatter = pageSchema, ...rest } = config;
return mdxCollection({
...rest,
frontmatter: frontmatter as never,
async options() {
const mdxOptions = typeof options === 'object' ? options : await options();
const { remarkInclude } = await import('fuma-content/plugins/remark/include');
return mdxPreset({
...mdxOptions,
_include: remarkInclude,
});
},
});
}
```
Sources: [packages/content/src/index.ts:16-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L33)
The runtime integration layer converts raw MDX and metadata file stores into static source representations consumed by Fumadocs routing and layout utilities. The `toFumadocsSource` function iterates over the list of pages and metadata files, normalizing paths and combining compiled frontmatter properties.
```typescript
export function toFumadocsSource<
Mdx extends MDXStoreData | MDXStoreLazyData = MDXStoreData<
PageData,
unknown
>,
Meta extends { data: MetaData } = { data: MetaData },
>(mdxStore?: FileCollectionStore, metaStore?: FileCollectionStore) {
const out: StaticSource<{
pageData: ToPageData;
metaData: Meta['data'];
}> = { files: [] };
for (const page of mdxStore?.list() ?? []) {
out.files.push({
type: 'page',
data: ('compiled' in page
? { ...page, ...page.compiled.frontmatter }
: { ...page, ...page.frontmatter }) as unknown as ToPageData,
path: page.path,
absolutePath: page.fullPath,
});
}
for (const file of metaStore?.list() ?? []) {
out.files.push({
type: 'meta',
data: file.data,
path: file.path,
absolutePath: file.fullPath,
});
}
return out;
}
```
Sources: [packages/content/src/runtime.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L42)
| Function / Class | Parameters | Return Type | Description |
| :--- | :--- | :--- | :--- |
| `docsMdxCollection` | `config: DocsMDXCollectionConfig` | MDX collection instance | Configures MDX collections with preset options and remark include plugins |
| `docsCollection` | `config: DocsCollectionConfig` | `{ index, meta, doc }` | Combines metadata and MDX collections into a unified documentation workspace |
| `DocsCollection` | none | `DocsCollection` class instance | Extends base collections to emit code generator output files during build pipelines |
| `toFumadocsSource` | `mdxStore`, `metaStore` | `StaticSource` | Transforms file collection stores into standard Fumadocs static source structures |
| `docsStore` | `mdxStore`, `metaStore` | `{ toFumadocsSource() }` | Wraps file stores with a method to export static source data |
Sources: [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53), [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70), [packages/content/src/runtime.ts:12-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L56)
> [!WARNING]
> When defining custom options for `docsMdxCollection`, the options parameter can be passed directly as an object or as an asynchronous factory function returning `MDXBundlerPresetOptions`. The runtime automatically injects the `remarkInclude` plugin into the bundler preset.
> Sources: [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L11-L31)
## Mounting documentation pages and layouts
### Layout and Preset Resolution
Documentation routes are handled by dynamic page components receiving URL slugs. The [preview server](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/preview-server) loads the runtime configuration and resolves the metadata source before determining whether to use the default `docs` layout preset or the alternative `flux` preset.
```tsx
export default async function DocPage({ slugs }: PageProps<'/docs/[...slugs]'>) {
const config = await getConfigRuntime();
const source = await getSource(config);
const page = source.getPage(slugs);
const mdPreset = config.layout.presets?.md ?? 'docs';
let mdPresetComponents: MdPresetComponents;
if (mdPreset === 'docs') {
mdPresetComponents = {
layout: await import('fumadocs-ui/layouts/docs'),
page: await import('fumadocs-ui/layouts/docs/page'),
};
} else {
mdPresetComponents = {
layout: await import('fumadocs-ui/layouts/flux'),
page: await import('fumadocs-ui/layouts/flux/page'),
};
}
return ;
}
```
Sources: [packages/preview/src/pages/...slugs.tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L76-L96)
| Layout Preset | Layout Component Import | Page Component Import |
| :--- | :--- | :--- |
| `docs` | `fumadocs-ui/layouts/docs` | `fumadocs-ui/layouts/docs/page` |
| `flux` | `fumadocs-ui/layouts/flux` | `fumadocs-ui/layouts/flux/page` |
Sources: [packages/preview/src/pages/...slugs.tsx:83-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L83-L93)
> [!NOTE]
> The layout preset is read directly from `config.layout.presets?.md`. If it is not explicitly configured, it defaults to the standard `docs` layout.
> Sources: [packages/preview/src/pages/[...slugs].tsx:80-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L80-L88)
### Markdown Compilation and Container Rendering
The `MdContent` component builds the surrounding container structure, integrating AI search capabilities if supported by the environment. It checks if the requested page exists in the source tree; if missing, it either presents a home overview cards listing or a standard 404 Not Found view.
```tsx
async function MdContent({
slugs,
page,
components,
}: {
slugs: string[];
page?: SourcePage;
components: MdPresetComponents;
}) {
const config = await getConfigRuntime();
const source = await getSource(config);
const layout = layoutConfig(config);
const { DocsLayout } = components.layout;
const { DocsBody, DocsTitle, DocsPage, DocsDescription } = components.page;
async function renderContainer(children: ReactNode) {
const hasAI = await isAISupported();
return (
{hasAI && (
Ask AI
)}
{children}
);
}
```
Sources: [packages/preview/src/pages/...slugs.tsx:98-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L98-L138)
Markdown strings are processed through a configured compiler instance equipped with remark and rehype plugins for GitHub-Flavored Markdown, math equations, diagrams, heading anchors, package managers, code tabs, and [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting).
```tsx
const compiler = createMarkdownCompiler({
remarkPlugins: [
remarkGfm,
remarkMath,
remarkMdxMermaid,
plugin(remarkHeading, { generateToc: false }),
plugin(remarkNpm, { persist: { id: 'package-manager' } }),
remarkCodeTab,
],
remarkRehypeOptions: {
passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'],
},
rehypePlugins: [
rehypeKatex,
plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }),
plugin(rehypeToc, { exportToc: { as: 'data' } }),
],
});
```
Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46)
> [!CAUTION]
> If compilation fails, the catch block intercepts the error and renders a dedicated error view displaying the error message and its stack trace inside a code block.
> Sources: [packages/preview/src/pages/[...slugs].tsx:170-194](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L170-L194)
## Running the live preview server
### Standalone CLI Execution and Port Allocation
The preview runtime is executed via the `fumadocs-preview` command-line interface, defined using the `commander` package. The CLI provides two primary commands: `init`, which scaffolds a default configuration file named `fumadocs.config.ts`, and `start`, which serves as the default action for starting the live preview server.
```typescript
program
.command('init')
.description('create configuration file')
.action(async () => {
if ((await findConfigPath()) === null) {
await fs.writeFile(
'fumadocs.config.ts',
`import { defineConfig } from "fumadocs-preview/config";\n\nexport default defineConfig();`,
);
console.log('note: make sure to install `fumadocs-preview` as a dev dependency too.');
}
});
program
.command('start', { isDefault: true })
.description('start Fumapress')
.argument('[dirs...]', 'a list of content directories to view')
.option('-p, --port ')
.option('-h, --host ')
.action(async (dirs: string[] | undefined, options: { port?: string; host?: string }) => {
await runStart({ ...options, dirs });
});
```
Sources: [packages/preview/src/cli/index.ts:8-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts#L8-L30)
| Command | Description | Arguments / Options |
| :--- | :--- | :--- |
| `init` | Create configuration file | None |
| `start` | Start Fumapress | `[dirs...]`, `-p, --port `, `-h, --host ` |
Sources: [packages/preview/src/cli/index.ts:8-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts#L8-L30)
When the `start` command executes, `runStart` loads environment variables via `loadEnv()` and overrides `NODE_ENV` to `production`. It invokes `getFreePort` starting from a default port of `8080` (or a custom port specified via options) to find an available TCP port by probing network sockets with `net.createServer()`. If the port is occupied with an `EADDRINUSE` error, it automatically increments the port number until an open socket is secured.
```typescript
async function getFreePort(startPort: number): Promise {
for (let port = startPort; ; port++) {
try {
await new Promise((resolve, reject) => {
const srv = net
.createServer()
.once('error', reject)
.once('listening', () => srv.close(() => resolve()))
.listen(port);
});
return port;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'EADDRINUSE') {
throw err;
}
}
}
}
```
Sources: [packages/preview/src/cli/commands.ts:36-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L36-L53)
> [!WARNING]
> If `getFreePort` encounters any socket error other than `EADDRINUSE`, it does not retry and immediately rejects with that error.
> Sources: [packages/preview/src/cli/commands.ts:47-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L47-L51)
### Environment Setup and Server Bootstrapping
Prior to launching the server bundle, `runStart` configures several required process environment variables to pass parameters down to the Waku server runtime.
```typescript
if (host) {
process.env.HOST = host;
}
process.env.PORT = String(port);
process.env.ROOT_DIR = process.cwd();
if (!dirs || dirs.length === 0) {
dirs = [''];
}
process.env.DEFAULT_PROJECT_DIR = JSON.stringify(dirs.map((v) => path.resolve(v)));
process.env.HOT_RELOAD = '1';
process.chdir(baseDir);
await import(serveFileUrl);
console.log(`ready: Listening on http://${host || 'localhost'}:${port}/`);
}
```
Sources: [packages/preview/src/cli/commands.ts:20-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L20-L34)
| Environment Variable | Assigned Value / Logic | Purpose |
| :--- | :--- | :--- |
| `HOST` | `host` option parameter (if provided) | Binds the server to a specific network host address |
| `PORT` | `String(port)` | Sets the listening port resolved by `getFreePort` |
| `ROOT_DIR` | `process.cwd()` | Establishes the root directory context for project file resolution |
| `DEFAULT_PROJECT_DIR` | JSON string of `dirs` mapped via `path.resolve()` | Specifies content directories to view; defaults to `['']` if empty |
| `HOT_RELOAD` | `'1'` | Enables dynamic hot-reloading behavior in the preview environment |
Sources: [packages/preview/src/cli/commands.ts:20-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L20-L29)
> [!TIP]
> After configuring environment variables, `runStart` changes the working directory to `baseDir` and dynamically imports the compiled Node server entry point (`dist/waku/serve-node.js`) using `pathToFileURL`.
> Sources: [packages/preview/src/cli/commands.ts:5-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L5-L31)
## Enabling dynamic local markdown updates
### Local Markdown Source Configuration and Compilation
The `@fumadocs/local-md` package provides the `localMd` factory function to manage local markdown and metadata files as a content source. It accepts a `LocalMarkdownConfig` object defining the root content directory (`dir`), glob patterns (`include`), frontmatter and metadata schemas, and optional compiler settings.
```typescript
export interface LocalMarkdownConfig<
FrontmatterSchema extends StandardSchemaV1,
MetaSchema extends StandardSchemaV1,
> extends MarkdownCompilerOptions {
/**
* root directory for content files.
*/
dir: string;
/**
* a list of glob patterns, customize the content files to be scanned.
*/
include?: string[];
rendererOptions?: Pick;
frontmatterSchema?: FrontmatterSchema;
metaSchema?: MetaSchema;
}
```
Sources: [packages/local-md/src/index.ts:24-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L24-L40)
| Configuration Property | Type | Default / Purpose |
| :--- | :--- | :--- |
| `dir` | `string` | Root directory for content files |
| `include` | `string[]` | Glob patterns to scan content files |
| `frontmatterSchema` | `StandardSchemaV1` | Validation schema for page frontmatter |
| `metaSchema` | `StandardSchemaV1` | Validation schema for metadata files |
Sources: [packages/local-md/src/index.ts:24-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L24-L40)
When `staticSource` or `dynamicSource` is invoked, `createFiles` reads pages and metadata via internal storage and builds virtual files. Each page includes a `load` function that checks a weak map cache (`compilerCache`) or compiles the markdown content using `createMarkdownCompiler`. Depending on the compiler result type, it delegates to `fromAst` or `fromJS` to generate the final renderer.
```typescript
async load() {
let promise = compilerCache.get(page);
if (!promise) {
promise = compiler.compile({
path: page.absolutePath,
value: page.content,
data: { frontmatter: page.frontmatter },
});
}
const res = await promise;
return res.type === 'ast'
? fromAst({
tree: res.tree,
filePath: res.file.path,
rehypeToc: res.file.data.rehypeToc,
structuredData: res.file.data.structuredData,
...config.rendererOptions,
})
: fromJS({
code: res.code,
filePath: res.file.path,
baseUrl: pathToFileURL(res.file.path).href,
structuredData: res.file.data.structuredData,
});
},
```
Sources: [packages/local-md/src/index.ts:125-150](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L125-L150)
> [!NOTE]
> The `compilerCache` uses a `WeakMap, Promise>` to memoize compilation promises per raw page object and prevent redundant parsing during development.
> Sources: [packages/local-md/src/index.ts:90-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L90-L92)
### Hot-Reloading via Development Server and WebSocket Clients
To support real-time editing, the `localMd` instance exposes a `devServer` method and an `invalidateFile` mechanism. When `devServer` is called, it connects to a WebSocket server, sends a `watch-dir` message with the configured directory and glob patterns, and listens for change events to invalidate modified files.
```typescript
async devServer(url = getDevServerUrlFromEnv()) {
if (!url) {
console.warn(
`[@fumadocs/local-md] dev server URL could not be found, try passing the URL to devServer() explicitly instead`,
);
return;
}
const { connectDevServer } = await import('@/dev/node-client');
const conn = connectDevServer(url);
conn.send({
type: 'watch-dir',
dir: path.resolve(config.dir),
includes: config.include ?? defaultInclude,
});
conn.subscribe((event) => {
if (event.type === 'change') {
this.invalidateFile(event.absolutePath);
}
});
},
```
Sources: [packages/local-md/src/index.ts:174-195](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L174-L195)
The React client component `DevClient` establishes a WebSocket connection to the development server using the URL resolved by `getDevServerUrlFromEnv`. Upon receiving an incoming message, it decodes the event using `decodeDevEvent`. If the decoded event type is a `change`, it logs the update and calls `router.refresh()` to trigger an immediate page reload in the framework router.
```typescript
export function DevClient(): ReactNode {
const router = useRouter();
const onUpdate = useEffectEvent((event: DevServerEvent) => {
if (event.type === 'change') {
console.log(`[@fumadocs/local-md] "${event.absolutePath}" updated`);
router.refresh();
}
});
useEffect(() => {
const url = getDevServerUrlFromEnv();
if (!url) return;
const ws = new WebSocket(url);
ws.onopen = () => {
console.log(`[@fumadocs/local-md] connected to dev server at ${url}`);
};
ws.onmessage = (event) => {
const decoded = decodeDevEvent(String(event.data));
if (decoded) onUpdate(decoded);
};
ws.onclose = () => {
console.log(`[@fumadocs/local-md] disconnected from dev server at ${url}`);
};
return () => {
ws.close();
};
}, []);
```
Sources: [packages/local-md/src/dev/react-client.ts:6-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts#L6-L38)
> [!WARNING]
> If `getDevServerUrlFromEnv` returns no URL during client initialization or inside `devServer()`, the connection attempt is aborted with a warning message or early return.
> Sources: [packages/local-md/src/index.ts:174-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L174-L180), [packages/local-md/src/dev/react-client.ts:16-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts#L16-L18)
## Related
- [Overview](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/overview)
- [Project Structure](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure)
- [Create App Generator](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator)
---
## Technical docs: Project Structure
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json)
- [packages/api-docs/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json)
- [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json)
- [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml)
- [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json)
- [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json)
- [packages/content/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json)
- [packages/base-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json)
- [packages/asyncapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json)
- [packages/obsidian/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/package.json)
- [packages/basehub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json)
- [packages/radix-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json)
- [packages/vite-data/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/vite-data/package.json)
- [packages/shared/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json)
- [packages/sanity/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/package.json)
- [packages/python/fumapy/mksource/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py)
- [packages/twoslash/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json)
- [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts)
- [packages/typescript/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json)
- [packages/python/fumapy/mksource/models.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py)
- [packages/epub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json)
- [packages/doc-gen/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json)
- [packages/create-app-versions/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app-versions/package.json)
- [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json)
- [packages/local-md/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json)
- [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx)
- [packages/story/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json)
- [packages/language/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json)
- [packages/sanity/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts)
- [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json)
## Overview
The Fumadocs monorepo is organized into specialized packages that power documentation generation, processing, and rendering. Workspace packages such as `fumadocs-core`, `fumadocs-ui`, `@fumadocs/base-ui`, `fumadocs-mdx`, and `@fumadocs/openapi` collaborate across build and runtime phases to support content transformation, UI layouts, and API spec tooling.
Sources: [packages/core/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L1-L4), [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4), [packages/base-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L1-L4), [packages/mdx/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L1-L4), [packages/openapi/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L1-L4)
## Core Architecture and Shared Utilities
### Core Package Responsibilities
The foundational runtime and processing logic of the workspace resides in `fumadocs-core` (`packages/core`), published under version `16.10.2` as an ES module package. It provides public entrypoints for breadcrumbs, content transformers, dynamic linking, framework adapters, code highlighters, internationalization, page trees, search indexers, and source loaders [packages/core/package.json:1-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L1-L97).
The package exports framework-specific routing and rendering adapters for Next.js, React Router, TanStack, and Waku through its framework entrypoints [packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33). Search capabilities span client-side search engines and server integrations for Algolia, Flexsearch, Mixedbread, and Orama Cloud [packages/core/package.json:66-80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L66-L80).
Sources: [packages/core/package.json:1-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L1-L97)
### Shared Utilities and Workspace Workspace Dependencies
Workspace configuration and tooling rely on private shared packages such as `shared` (`packages/shared`), which coordinates utility libraries and CLI dependencies across builds [packages/shared/package.json:1-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json#L1-L15).
> [!NOTE]
> The `shared` package is marked as `"private": true` and uses ES module imports, depending on `fuma-cli` and `tinyglobby` for file globbing and command execution during workspace operations.
Sources: [packages/shared/package.json:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json#L1-L8)
## User Interface Packages
### Radix UI and Base UI Packages
Fumadocs provides two distinct UI implementation packages for its presentation layer: `fumadocs-ui` (`packages/radix-ui`), which serves as the Radix UI version of Fumadocs UI under version `16.10.2`, and `@fumadocs/base-ui` (`packages/base-ui`), which implements the Base UI version under the same version [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4), [packages/base-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L1-L4). Both packages share identical public export paths for components, layouts, contexts, and providers, but differ in their underlying primitive dependencies.
The Radix UI implementation relies on specific `@radix-ui/react-*` primitive packages for accessibility and state management, whereas the Base UI variant depends on `@base-ui/react` for its unstyled component primitives [packages/radix-ui/package.json:131-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L131-L154), [packages/base-ui/package.json:127-141](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L127-L141).
Sources: [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4), [packages/base-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L1-L4), [packages/radix-ui/package.json:131-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L131-L154), [packages/base-ui/package.json:127-141](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L127-L141)]
### Component Exports and Framework Providers
Both UI packages export extensive sets of component entrypoints, framework providers, and layout slots. The provider entrypoints support multiple frontend architectures, including Next.js, React Router, TanStack, and Waku [packages/radix-ui/package.json:104-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L104-L108), [packages/base-ui/package.json:102-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L102-L106).
| Export Path | Target File (`dist/`) | Description |
| :--- | :--- | :--- |
| `./provider/base` | `./dist/provider/base.js` | Base UI/Radix provider implementation |
| `./provider/next` | `./dist/provider/next.js` | Next.js framework provider integration |
| `./provider/react-router` | `./dist/provider/react-router.js` | React Router framework provider |
| `./provider/tanstack` | `./dist/provider/tanstack.js` | TanStack framework provider |
| `./provider/waku` | `./dist/provider/waku.js` | Waku framework provider integration |
Sources: [packages/radix-ui/package.json:104-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L104-L108), [packages/base-ui/package.json:102-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L102-L106)]
> [!WARNING]
> While `fumadocs-ui` includes legacy compatibility exports (`./legacy/layout` and `./legacy/sidebar`) alongside standard UI elements, `@fumadocs/base-ui` omits these legacy paths entirely in favor of its modern layout and slot structure [packages/radix-ui/package.json:94-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L94-L95), [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114).
Sources: [packages/radix-ui/package.json:94-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L94-L95), [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114)]
## Content Processing and Schema Bundling
### Content Collection Schema Configuration
The `@fumadocs/content` package acts as the content adapter for Fumadocs, integrating with `fuma-content` and standard schema specifications via `@standard-schema/spec` [packages/content/package.json:2-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L2-L33). It configures MDX collections and metadata data collections through specialized builder functions such as `docsMdxCollection` and `docsCollection` [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53).
| Function / Class | Parameter / Return Type | Purpose |
| :--- | :--- | :--- |
| `docsMdxCollection` | `DocsMDXCollectionConfig` | Creates an MDX collection wrapping `mdxCollection` with preset options and remark include plugins [packages/content/src/index.ts:16-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L33). |
| `docsCollection` | `DocsCollectionConfig` | Returns an object containing `index`, `meta`, and `doc` collection handles [packages/content/src/index.ts:44-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L44-L53). |
| `DocsCollection` | Extends `Collection` | Subclass that registers code generators via `onEmit.pipe` to output store bindings [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70). |
Sources: [packages/content/src/index.ts:16-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L70)]
> [!NOTE]
> The `docsMdxCollection` utility dynamically evaluates option configurations (whether provided as a static object or an asynchronous factory function) and injects the `remarkInclude` plugin into the MDX bundler preset [packages/content/src/index.ts:24-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L24-L31).
Sources: [packages/content/src/index.ts:24-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L24-L31)]
### MDX Transformations and Bundler Integration
The `fumadocs-mdx` package (`packages/mdx/package.json`) provides the built-in content source and bundler integrations across multiple target environments and build systems [packages/mdx/package.json:2-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L2-L45). It exposes explicit subpath exports for Node, Next.js, Vite, Bun, Rolldown, and Webpack loaders and plugins [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44).
| Export Subpath | Target File (`dist/`) | Purpose |
| :--- | :--- | :--- |
| `.` | `./dist/index.js` | Main entry point |
| `./bin` | `./dist/bin.js` | CLI binary execution entry |
| `./bun` | `./dist/bun/index.js` | Bun runtime integration |
| `./config` | `./dist/config/index.js` | Configuration loader helpers |
| `./next` | `./dist/next/index.js` | Next.js source integration |
| `./node` | `./dist/node/index.js` | Node.js source bindings |
| `./node/loader` | `./dist/node/loader.js` | Node module loader |
| `./rolldown` | `./dist/rolldown/index.js` | Rolldown bundler plugin |
| `./vite` | `./dist/vite/index.js` | Vite bundler plugin |
| `./webpack/mdx` | `./dist/webpack/mdx.js` | Webpack MDX loader |
| `./webpack/meta` | `./dist/webpack/meta.js` | Webpack meta loader |
Sources: [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44)]
> [!WARNING]
> [Bundler plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins) and loaders such as `rolldown`, `vite`, and `webpack` are declared as optional peer dependencies alongside `next` and `mdast-util-directive`, allowing consumer projects to install only the toolchain integrations they require [packages/mdx/package.json:96-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L96-L132).
Sources: [packages/mdx/package.json:96-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L96-L132)]
## API Specification Tooling
### OpenAPI and AsyncAPI Processing Packages
The API specification ecosystem in Fumadocs is powered by three specialized packages: `@fumadocs/api-docs` (`packages/api-docs/package.json`), `fumadocs-openapi` (`packages/openapi/package.json`), and `@fumadocs/asyncapi` (`packages/asyncapi/package.json`) [packages/api-docs/package.json:2-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L2-L45), [packages/openapi/package.json:2-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L37), [packages/asyncapi/package.json:2-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L25). These packages supply shared utility modules, server bindings, request code generators, and UI presentation components for machine-readable API specifications.
| Package Name | Version | Description | Key Subpath Exports |
| :--- | :--- | :--- | :--- |
| `@fumadocs/api-docs` | `0.0.2` | Shared utils for API docs generation | `./schema`, `./schema/bundle`, `./schema/dereference`, `./components/schema` [packages/api-docs/package.json:2-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L2-L38) |
| `fumadocs-openapi` | `11.0.2` | Generate MDX docs for your OpenAPI spec | `.`, `./i18n`, `./scalar`, `./server`, `./ui`, `./requests/generators/all` [packages/openapi/package.json:2-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L36) |
| `@fumadocs/asyncapi` | `0.0.2` | Generate docs for your AsyncAPI spec | `.`, `./i18n`, `./server`, `./ui` [packages/asyncapi/package.json:2-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L24) |
Sources: [packages/api-docs/package.json:2-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L2-L38), [packages/openapi/package.json:2-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L36), [packages/asyncapi/package.json:2-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L24)]
> [!NOTE]
> `@fumadocs/api-docs` bundles and inlines critical JSON Schema processing tools such as `@apidevtools/json-schema-ref-parser`, `@fastify/deepmerge`, and `ajv` directly within its distribution configuration [packages/api-docs/package.json:97-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L97-L104).
Sources: [packages/api-docs/package.json:97-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L97-L104)]
### Request Generators and Code Generation Modules
The `fumadocs-openapi` package exposes modular request code generators under its `./requests/generators/*` export paths, enabling automatic generation of client request snippets across multiple target languages [packages/openapi/package.json:22-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L22-L29).
| Export Subpath | Target File (`dist/`) | Purpose |
| :--- | :--- | :--- |
| `./requests/generators` | `./dist/requests/generators/index.js` | Main generators dispatcher entry point [packages/openapi/package.json:22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L22) |
| `./requests/generators/all` | `./dist/requests/generators/all.js` | Bundle aggregator for all supported languages [packages/openapi/package.json:23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L23) |
| `./requests/generators/csharp` | `./dist/requests/generators/csharp.js` | C# HTTP request snippet generator [packages/openapi/package.json:24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L24) |
| `./requests/generators/curl` | `./dist/requests/generators/curl.js` | cURL command-line snippet generator [packages/openapi/package.json:25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L25) |
| `./requests/generators/go` | `./dist/requests/generators/go.js` | Go `net/http` request generator [packages/openapi/package.json:26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L26) |
| `./requests/generators/java` | `./dist/requests/generators/java.js` | Java HTTP request generator [packages/openapi/package.json:27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L27) |
| `./requests/generators/javascript` | `./dist/requests/generators/javascript.js` | JavaScript `fetch` snippet generator [packages/openapi/package.json:28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L28) |
| `./requests/generators/python` | `./dist/requests/generators/python.js` | Python `requests` snippet generator [packages/openapi/package.json:29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L29) |
Sources: [packages/openapi/package.json:22-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L22-L29)]
> [!WARNING]
> Optional peer dependencies such as `@scalar/api-client-react` and `json-schema-typed` must be explicitly installed by consuming applications when utilizing interactive Scalar API playground components or strict schema typing [packages/openapi/package.json:79-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L79-L98).
Sources: [packages/openapi/package.json:79-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L79-L98)]
## Language Analysis and Code Generation
### TypeScript and Twoslash Integrations
The workspace provides dedicated tooling for TypeScript code analysis, interactive type annotations, and documentation generation through `fumadocs-typescript`, `fumadocs-twoslash`, and `fumadocs-docgen`. These packages integrate syntax analysis, tree transformations, and build-time code transformations.
| Package Name | Main Entry Point (`dist/`) | Primary Export Subpaths | Description |
| :--- | :--- | :--- | :--- |
| `fumadocs-twoslash` | `./dist/index.js` [packages/twoslash/package.json:18-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L18-L18) | `./twoslash.css`, `/.`, `./ui`, `./cache-fs` [packages/twoslash/package.json:21-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L21-L33) | TypeScript Twoslash integration with Shiki and UI popover support [packages/twoslash/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L4), [packages/twoslash/package.json:46-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L46-L52) |
| `fumadocs-typescript` | `./dist/index.js` [packages/typescript/package.json:17-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L17-L17) | `.`, `./ui` [packages/typescript/package.json:20-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L20-L27) | TypeScript code intelligence and AST utilities via `ts-morph` [packages/typescript/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L4), [packages/typescript/package.json:46-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L46-L46) |
| `fumadocs-docgen` | `./dist/index.js` [packages/doc-gen/package.json:19-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L19-L19) | `.`, `./remark-ts2js` [packages/doc-gen/package.json:22-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L22-L29) | Remark plugins and utilities including TypeScript-to-JavaScript code transformation [packages/doc-gen/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L4), [packages/doc-gen/package.json:26-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L26-L29) |
| `@fumadocs/language` | Not applicable (exports individual translation files) [packages/language/package.json:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L17-L21) | `./zh-cn`, `./zh-tw`, `./package.json` [packages/language/package.json:18-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L18-L20) | Common localized language packs and integration metadata for Fumadocs packages [packages/language/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L2-L4), [packages/language/package.json:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L17-L21) |
Sources: [packages/twoslash/package.json:2-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L34), [packages/typescript/package.json:2-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L28), [packages/doc-gen/package.json:2-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L30), [packages/language/package.json:2-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L2-L21)]
> [!WARNING]
> `@fumadocs/language` declares peer dependencies on several workspace API and story components (`@fumadocs/api-docs`, `@fumadocs/asyncapi`, `@fumadocs/story`, `fumadocs-core`, `fumadocs-openapi`, `fumadocs-ui`) marked as optional, meaning consuming projects must provide the specific packages corresponding to the desired localized documentation tools [packages/language/package.json:43-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L43-L70).
Sources: [packages/language/package.json:43-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L43-L70)]
### Transformation Dependencies and Syntax Processing
Code analysis modules rely on syntax transformers and AST parsers to manipulate Markdown and code structures. `fumadocs-typescript` integrates `ts-morph` alongside `estree-util-value-to-estree`, `hast-util-to-estree`, and `hast-util-to-jsx-runtime` [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49). Similarly, `fumadocs-docgen` leverages `oxc-transform` and `zod` schema parsing to process and convert code snippets [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50).
> [!TIP]
> When configuring `fumadocs-twoslash`, consumers can import cache layers via the `./cache-fs` export path alongside `@shikijs/twoslash` and `twoslash` dependencies to persist type check results across builds [packages/twoslash/package.json:30-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L30-L33), [packages/twoslash/package.json:47-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L47-L47), [packages/twoslash/package.json:52-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L52-L52).
Sources: [packages/twoslash/package.json:30-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L30-L33), [packages/twoslash/package.json:47-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L47-L47), [packages/twoslash/package.json:52-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L52-L52), [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49), [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50)]
## Python Tooling and Components
### Fumapy Core Package Configuration
The `fumapy` Python library (`fumadocs-python`) extracts API documentation from source code and docstrings, serving as the back-end extraction engine for Fumadocs [packages/python/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L4), [packages/python/pyproject.toml:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L4). Managed via Hatchling as its build-backend, it requires Python 3.10 or newer and depends on `griffe` and `griffe_typingdoc` to inspect Python code structures [packages/python/pyproject.toml:7-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L7-L8), [packages/python/pyproject.toml:13-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L13-L15). The command-line script entrypoint `fumapy-generate` points directly to the `generate` function inside the package [packages/python/pyproject.toml:10-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L10-L11).
Sources: [packages/python/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L4), [packages/python/pyproject.toml:2-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L15)]
> [!NOTE]
> `fumapy` relies strictly on `griffe` (versions `>=1.13.0, <2.0.0`) and `griffe_typingdoc` (versions `>=0.2.8, <1.0.0`) for static analysis and docstring typing support [packages/python/pyproject.toml:8-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L8-L8).
Sources: [packages/python/pyproject.toml:8-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L8-L8)]
### Module and Type Models
The `fumapy.mksource` subpackage exports core parsing helpers and typed model structures that define how Python symbols are represented [packages/python/fumapy/mksource/__init__.py:1-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py#L1-9). The models utilize TypedDict definitions to represent modules, classes, functions, parameters, attributes, and docstring sections [packages/python/fumapy/mksource/models.py:6-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py#L6-60).
| Model | Key Fields | Description |
| :--- | :--- | :--- |
| `Module` | `name`, `path`, `filepath`, `description`, `docstring`, `attributes`, `modules`, `classes`, `functions`, `version` | Represents a parsed Python module container holding nested modules, classes, and functions. |
| `Class` | `name`, `path`, `description`, `parameters`, `attributes`, `docstring`, `functions`, `source` | Represents a Python class declaration including its source string and member functions. |
| `Function` | `name`, `path`, `signature`, `description`, `parameters`, `returns`, `docstring`, `source` | Represents a function or method signature, return annotations, and source code. |
| `Parameter` | `name`, `annotation`, `description`, `value` | Describes an individual function parameter or class argument with type annotations and defaults. |
| `Attribute` | `name`, `annotation`, `description`, `value` | Captures class or module-level attributes and field assignments. |
| `DocstringSection` | `kind`, `value` | Represents structural sections parsed out of docstrings. |
Sources: [packages/python/fumapy/mksource/__init__.py:1-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py#L1-L9), [packages/python/fumapy/mksource/models.py:6-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py#L6-L60)]
### React Presentation Components
The front-end package `fumadocs-python` exposes UI presentation components under its `./components` export path to render Python API documentation [packages/python/package.json:28-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L28-31), [packages/python/src/components/index.tsx:25-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L25-133). These components use Tailwind CSS, class-variance-authority, and Fumadocs UI primitives to display code symbols, badges, parameters, and collapsible source blocks.
| Component | Props | Purpose |
| :--- | :--- | :--- |
| `PyFunction` | `name`, `type`, `children` | Renders a function symbol card with a specialized `func` badge and type signature [packages/python/src/components/index.tsx:25-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L25-40). |
| `PyAttribute` | `name`, `type`, `value`, `children` | Displays an attribute card featuring an `attribute` badge, type, and default value [packages/python/src/components/index.tsx:42-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L42-69). |
| `PyParameter` | `name`, `type`, `value`, `children` | Formats function parameters inside a secondary container with a `param` badge [packages/python/src/components/index.tsx:71-101](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L71-101). |
| `PySourceCode` | `children` | Wraps raw source code blocks in a collapsible element with a toggle trigger [packages/python/src/components/index.tsx:103-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L103-121). |
| `PyFunctionReturn` | `type`, `children` | Presents function return types and descriptions within a structured box [packages/python/src/components/index.tsx:123-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L123-133). |
Sources: [packages/python/package.json:28-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L28-L31), [packages/python/src/components/index.tsx:25-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L25-L133)]
## Scaffolding and Authoring Integrations
### Project Scaffolding and Preview CLI
The package `create-fumadocs-app` initializes and scaffolds new documentation sites, relying on dependency version tracking managed by `create-fumadocs-versions` [packages/create-app/package.json:2-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-6), [packages/create-app-versions/package.json:2-5](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app-versions/package.json#L2-5). Concurrently, `fumadocs-preview` provides an opinionated framework for fast content previews using Waku and Hono [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-4), [packages/preview/package.json:29-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L29-32), [packages/preview/package.json:43-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f560770
## Related
- [Overview](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/overview)
- [Quick Start](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start)
---
## Technical docs: Flexsearch Query Regex Building
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/how-it-works/flexsearch-query-regex-building
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/search/flexsearch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts)
- [packages/core/src/search/flexsearch/utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts)
- [packages/core/src/search/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts)
## Overview
### Introduction
The `flexsearchI18n` to `buildRegexFromQuery` execution flow handles multi-language document searching and result highlighting in Fumadocs. When a user submits a search query with internationalization (i18n) enabled, the request is routed through language-specific FlexSearch document indices, executed against the search engine, and post-processed with content highlighters that convert terms into regular expressions. This pipeline ensures that search results respect locale boundaries and feature appropriately highlighted matched terms.
Sources: [packages/core/src/search/flexsearch.ts:72-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L72-L129), [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68), [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43)
## Execution Flow
### Step 1: flexsearchI18n
The execution begins when `flexsearchI18n` is invoked with `I18nOptions`. This function acts as the public entrypoint for setting up an internationalized search endpoint. It wraps the core `serverI18n` implementation inside an endpoint creator and returns a `SearchAPI` interface.
Sources: [packages/core/src/search/flexsearch.ts:135-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L135-L137)
### Step 2: serverI18n
`serverI18n` takes the i18n configuration options and initializes search servers for each locale. It defines the `export` and `search` handlers. When a `search` request arrives, it resolves the appropriate language server using `searchOptions.locale` or falls back to `options.i18n.defaultLanguage`. If a matching language handler is found, it delegates the query to that specific server instance.
Sources: [packages/core/src/search/flexsearch.ts:72-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L72-L129)
### Step 3: initSearchServers
Inside `serverI18n`, the asynchronous `initSearchServers` function groups the provided document indexes by their locale. If `inputIndexes` is provided as an asynchronous function, it awaits the result. It then iterates over the grouped indexes, applies any locale-specific overrides (such as CJK character encoding options), and instantiates a standard single-language `server` for each locale, storing them in a `Map`.
Sources: [packages/core/src/search/flexsearch.ts:75-105](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L75-L105)
### Step 4: server
The single-language `server` function manages the FlexSearch document index for a specific locale. It initializes the search index via `createDocument`, populates it with documents, and exposes `export` and `search` methods. When `search` is called, it awaits the index initialization promise and passes the query and options to the search utility.
Sources: [packages/core/src/search/flexsearch.ts:41-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L70)
### Step 5: search
The `search` utility function in `flexsearch/utils.ts` executes `index.searchAsync()` against the FlexSearch document store. If results are returned, it invokes `createContentHighlighter(query)` to prepare highlighters. It then groups matching sections by page ID, builds formatted results including page metadata, and highlights matching content markdown before returning the final sorted results array.
Sources: [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68)
### Step 6: createContentHighlighter
`createContentHighlighter` accepts the search query (or a prebuilt RegExp) and returns highlighting utilities. If a string query is passed, it delegates immediately to `buildRegexFromQuery` to compile the search terms into a case-insensitive regular expression.
Sources: [packages/core/src/search/index.ts:47-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L47-L49)
### Step 7: buildRegexFromQuery
`buildRegexFromQuery` takes the raw query string, trims whitespace, and splits it into unique terms by whitespace. It escapes any special regular expression characters in each term using `escapeRegExp`, joins them with the alternation operator (`|`), and returns a compiled global, case-insensitive `RegExp` object (or `null` if the query is empty).
Sources: [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43)
## Architecture Diagrams
### Sequence Diagram
```mermaid
sequenceDiagram
participant Client
participant FlexsearchI18n as flexsearchI18n (flexsearch.ts)
participant ServerI18n as serverI18n (flexsearch.ts)
participant InitServers as initSearchServers (flexsearch.ts)
participant Server as server (flexsearch.ts)
participant SearchUtil as search (flexsearch/utils.ts)
participant Highlighter as createContentHighlighter (index.ts)
participant RegexBuilder as buildRegexFromQuery (index.ts)
Client->>FlexsearchI18n: flexsearchI18n(options)
FlexsearchI18n->>ServerI18n: serverI18n(options)
Note over ServerI18n,InitServers: Search request triggers server initialization
ServerI18n->>InitServers: initSearchServers()
InitServers->>Server: server(localeOptions)
Client->>ServerI18n: search(query, searchOptions)
ServerI18n->>Server: search(query, searchOptions)
Server->>SearchUtil: search(index, query, tag, limit)
SearchUtil->>Highlighter: createContentHighlighter(query)
Highlighter->>RegexBuilder: buildRegexFromQuery(query)
RegexBuilder-->>Highlighter: RegExp
Highlighter-->>SearchUtil: highlighter instance
SearchUtil-->>Server: SortedResult[]
Server-->>ServerI18n: SortedResult[]
ServerI18n-->>Client: SortedResult[]
```
Sources: [packages/core/src/search/flexsearch.ts:41-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L137), [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68), [packages/core/src/search/index.ts:36-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L49)
### Flowchart
```mermaid
flowchart TD
A[flexsearchI18n] --> B[serverI18n]
B --> C[initSearchServers]
C -->|Group by locale & override| D[server]
D -->|Execute search| E[search util]
E -->|Create highlighter| F[createContentHighlighter]
F -->|Parse query string| G[buildRegexFromQuery]
G -->|Valid terms?| H{Yes / No}
H -->|Yes| I[Return RegExp]
H -->|No| J[Return null]
I --> K[Highlight Markdown / Text]
J --> K
K --> L[Return Sorted Results]
```
Sources: [packages/core/src/search/flexsearch.ts:41-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L137), [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68), [packages/core/src/search/index.ts:36-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L49)
## Key Observations
- **Cross-Module Boundaries:** The flow bridges higher-level i18n server orchestration (`flexsearch.ts`), low-level FlexSearch execution and document grouping (`flexsearch/utils.ts`), and text/Markdown parsing utilities (`index.ts`).
- **Locale Resolution and Fallback:** If a requested locale is missing during a search query, `serverI18n` gracefully falls back to `options.i18n.defaultLanguage`, or returns an empty array if no matching server handler exists.
- **Robust Query Normalization:** `buildRegexFromQuery` automatically filters out empty terms, deduplicates search keywords via `Set`, and escapes regular expression special characters to prevent syntax crashes on malformed queries.
Sources: [packages/core/src/search/flexsearch.ts:121-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L121-L127), [packages/core/src/search/flexsearch/utils.ts:7-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L24), [packages/core/src/search/index.ts:32-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L32-L43)
---
## Technical docs: Source Loader
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/preview/src/lib/source/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/storage.ts)
- [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts)
- [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts)
- [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/content-collections/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts)
- [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts)
- [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx)
- [packages/mdx/src/loaders/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts)
- [packages/core/src/source/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts)
- [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx)
- [packages/preview/src/lib/source/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts)
- [packages/local-md/src/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts)
- [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts)
- [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts)
- [packages/core/src/source/storage/content.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts)
- [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts)
- [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/openapi/src/utils/document/load.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts)
- [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx)
- [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts)
- [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts)
- [packages/obsidian/src/build-storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts)
- [packages/core/src/source/source.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts)
- [packages/core/src/source/plugins/slugs.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts)
- [packages/python/fumapy/mksource/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py)
- [packages/story/src/webpack/story.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts)
- [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts)
- [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts)
## Overview
Fumadocs source loaders ingest, normalize, and index document collections from diverse sources like local disk storage, Content Collections, and remote OpenAPI or AsyncAPI specs into a unified virtual file system. They expose public contracts and virtual file definitions via `source` and `StaticSource`, mapping files to typed page and metadata objects.
Sources: [packages/core/src/source/source.ts:1-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L1-L114), [packages/core/src/source/storage/content.ts:1-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L1-L42)
The core loader pipeline parses frontmatter, handles internationalization directories or extension codes, applies loader plugins for slugs and builds hierarchical page trees and search indices.
Sources: [packages/core/src/source/loader.ts:268-315](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L268-L315), [packages/core/src/source/storage/content.ts:50-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L50-L126), [packages/core/src/source/plugins/slugs.ts:15-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L15-L42)
Through dynamic loaders and client-side deserialization hooks, Fumadocs supports runtime revalidation, hot reloading, and preloaded remote document integration.
Sources: [packages/core/src/source/dynamic.ts:27-119](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L27-L119), [packages/core/src/source/client/index.tsx:14-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L60), [packages/local-md/src/index.ts:84-208](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L84-L208)
## Unified source interface and contracts
### Core data structures and virtual file contracts
Fumadocs source loaders rely on a shared type architecture defined by `SourceUnion`, distinguishing between `StaticSource` and `DynamicSource` objects via guard functions `isStaticSource` and `isDynamicSource`. Static sources maintain an array of `VirtualFile` items directly, whereas dynamic sources supply an asynchronous or synchronous builder function `files: () => Awaitable[]>` alongside an optional `configure` hook accepting a `DynamicLoader`.
Sources: [packages/core/src/source/source.ts:5-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L5-L21), [packages/core/src/source/source.ts:172-178](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L172-L178)
Every virtual file extends `BaseVirtualFile`, holding a virtualized relative path and an optional absolute path on disk. Depending on its `type` discriminant, a file resolves to either a `VirtualPage` carrying `slugs` and typed `pageData`, or a `VirtualMeta` carrying typed `metaData`.
Sources: [packages/core/src/source/source.ts:48-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L48-L78)
| Property / Type | Field Type | Purpose & Description |
| :--- | :--- | :--- |
| `path` | `string` | Virtualized path relative to the content directory (e.g. `docs/page.mdx`). |
| `absolutePath` | `string` (optional) | Absolute path of the underlying file on disk. |
| `type` | `'page' \| 'meta'` | Discriminant property identifying whether the virtual file is a page or metadata file. |
| `slugs` | `string[]` (optional) | Explicit route segments assigned to a virtual page. |
| `data` | `PageData \| MetaData` | Payload containing frontmatter attributes, titles, icons, or navigation controls. |
Sources: [packages/core/src/source/source.ts:52-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L52-L78)
> [!NOTE]
> The `multiple` helper utility is deprecated in favor of passing a record of source objects directly to the main `loader()` function, which automatically scopes namespaces and injects type tags.
> Sources: [packages/core/src/source/source.ts:80-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L80-L82)
### Metadata schemas and builder utilities
The base metadata structures define standard properties supported across documentation nodes. `MetaData` configures folder navigation and display parameters such as `icon`, `title`, `root`, `pages`, `pagesIndex`, `defaultOpen`, `collapsible`, and `description`. `PageData` configures individual document attributes including `icon`, `title`, `description`, and `structuredData` (which accepts search index payloads or asynchronous generators).
Sources: [packages/core/src/source/source.ts:28-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L28-L46)
```typescript
export function source(config: {
pages: VirtualPage[];
metas: VirtualMeta[];
}): StaticSource<{
pageData: Page;
metaData: Meta;
}> {
return {
files: [...config.pages, ...config.metas],
};
}
interface SourceUpdater {
files: (
fn: (files: VirtualFile[]) => (VirtualPage | VirtualMeta)[],
) => SourceUpdater<{
pageData: Page;
metaData: Meta;
}>;
page: (
fn: (page: VirtualPage) => VirtualPage,
) => SourceUpdater<{
pageData: V;
metaData: Config['metaData'];
}>;
meta: (
fn: (meta: VirtualMeta) => VirtualMeta,
) => SourceUpdater<{
pageData: Config['pageData'];
metaData: V;
}>;
build: () => StaticSource;
}
/**
* update a source object in-place.
*/
export function update(
source: StaticSource,
): SourceUpdater {
return {
files(fn) {
source.files = fn(source.files);
return this as SourceUpdater;
},
page(fn) {
for (let i = 0; i < source.files.length; i++) {
const file = source.files[i];
if (file.type === 'page') source.files[i] = fn(file);
}
return this as SourceUpdater;
},
meta(fn) {
for (let i = 0; i < source.files.length; i++) {
const file = source.files[i];
if (file.type === 'meta') source.files[i] = fn(file);
}
return this as SourceUpdater;
},
build() {
return source;
},
};
}
```
Sources: [packages/core/src/source/source.ts:104-170](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L104-L170)
### External adapters and runtime transformation
External integrations bridge third-party content providers into the standard Fumadocs source contract. The [Content Collections Adapter](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/content-collections-adapter) maps `allDocs` and `allMetas` arrays into `VirtualPage` and `VirtualMeta` structures via `createMDXSource`, binding `_meta.filePath` directly to file paths.
Sources: [packages/content-collections/src/index.ts:4-35](https://github.com/packages/content-collections/src/index.ts#L4-L35)
Similarly, runtime content stores convert compiled MDX collections and metadata stores into standard `StaticSource` objects through `toFumadocsSource` and `docsStore`. Frontmatter properties are merged directly into page data objects alongside absolute path tracking.
Sources: [packages/content/src/runtime.ts:12-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L56)
> [!WARNING]
> When integrating custom runtime stores, ensure frontmatter properties do not overwrite core `VirtualPage` discriminatory fields (`type`, `path`, `absolutePath`) during object spreading.
> Sources: [packages/content/src/runtime.ts:23-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L23-L32)
## In-memory filesystem and content storage
### Storage construction and plugin transformation
The `createContentStorageBuilder` function transforms raw static or multi-namespace content inputs into an indexed virtual file system. When internationalization is enabled, parser routines strip locale codes from file paths based on either directory structures or filename extensions, mapping entries into a shared `fileMap` indexed by target language or an `EmptyLang` symbol.
Sources: [packages/core/src/source/storage/content.ts:43-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L43-L93)
```typescript
export function createContentStorageBuilder(loaderConfig: ResolvedLoaderConfig) {
const { input, plugins, i18n } = loaderConfig;
let parser: (normalizedPath: string) => [string, (string | string[])?];
if (!i18n) {
parser = (path) => [path];
} else if (i18n.parser === 'dir') {
const langSet = new Set(i18n.languages);
parser = (path) => {
const [locale, ...segs] = path.split('/');
if (!locale || segs.length === 0) return [path];
if (langSet.has(locale)) return [segs.join('/'), locale];
if (locale === '$') return [segs.join('/'), i18n.languages];
return [path];
};
} else {
const langSet = new Set(i18n.languages);
parser = (path) => {
const segs = path.split('/');
const base = segs.pop();
if (!base) return [path];
const parts = base.split('.');
if (parts.length < 3) return [path];
const [locale] = parts.splice(parts.length - 2, 1);
segs.push(parts.join('.'));
if (langSet.has(locale)) return [segs.join('/'), locale];
if (locale === '$') return [segs.join('/'), i18n.languages];
return [path];
};
}
```
Sources: [packages/core/src/source/storage/content.ts:50-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L50-L87)
During the scanning phase, input files are categorized as either page or metadata files. Each file receives a normalized path, format descriptor, source type, and underlying data payload before being inserted into the storage map.
Sources: [packages/core/src/source/storage/content.ts:94-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L94-L126)
| Storage File Type | Format Discriminant | Required Properties | Optional Properties |
| :--- | :--- | :--- | :--- |
| `ContentStoragePageFile` | `'page'` | `format`, `path`, `slugs`, `data` | `type`, `absolutePath` |
| `ContentStorageMetaFile` | `'meta'` | `format`, `path`, `data` | `type`, `absolutePath` |
Sources: [packages/core/src/source/storage/content.ts:17-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L17-L41)
> [!NOTE]
> When evaluating language parsers, if a file path segment equals `$`, the parser maps the file across all configured internationalization languages simultaneously.
> Sources: [packages/core/src/source/storage/content.ts:64-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L64-L83)
Once files are indexed within `fileMap`, `makeStorage` instantiates a `FileSystem` instance for a given locale. It populates the filesystem with corresponding storage entries and executes any registered plugin storage transformation hooks.
Sources: [packages/core/src/source/storage/content.ts:134-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L134-L146)
```typescript
function makeStorage(locale: string | typeof EmptyLang, inherit?: ContentStorage) {
const storage = new FileSystem(inherit) as ContentStorage;
for (const [storageKey, file] of fileMap.get(locale) ?? []) {
storage.write(storageKey, file);
}
const context = { storage };
for (const plugin of plugins) {
plugin.transformStorage?.(context);
}
return storage;
}
```
Sources: [packages/core/src/source/storage/content.ts:134-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L134-L146)
## Dynamic loader resolution and caching
```mermaid
sequenceDiagram
participant dynamicLoader as dynamic.ts
participant resolveSources as dynamic.ts
participant resolveSource as dynamic.ts
participant isStaticSource as source.ts
dynamicLoader->>resolveSources: get()
resolveSources->>resolveSource: map input items
resolveSource->>isStaticSource: check static vs dynamic
```
Sources: [packages/core/src/source/dynamic.ts:52-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L52-L79), [packages/core/src/source/source.ts:172-174](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L172-L174)
The `dynamicLoader` factory handles runtime content resolution, source configuration, and memoization for dynamic and static documentation sources. During initialization, `configureSources` iterates over input sources and executes `v.configure?.(dynamicLoader)` when an input matches dynamic source criteria.
Sources: [packages/core/src/source/dynamic.ts:40-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L40-L50), [packages/core/src/source/dynamic.ts:116-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L116-L116)
The resolution pipeline follows a strict call chain: `dynamicLoader` invokes `resolveSources`, which calls `resolveSource` on each source object, delegating to `isStaticSource` for type discrimination.
Sources: [packages/core/src/source/dynamic.ts:52-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L52-L79)
```typescript
async function resolveSources(skipCache = false): Promise {
if (isStaticSource(input) || isDynamicSource(input)) {
return resolveSource(input, skipCache);
}
const entries = await Promise.all(
Object.entries(input).map(async ([k, v]) => [k, await resolveSource(v, skipCache)]),
);
return Object.fromEntries(entries);
}
```
Sources: [packages/core/src/source/dynamic.ts:52-62](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L52-L62)
> [!WARNING]
> Bypassing cache via `skipCache = true` forces `resolveSource` to re-execute `v.files()` and overwrite existing entries in `sourceCache`, discarding previously memoized virtual file arrays.
> Sources: [packages/core/src/source/dynamic.ts:64-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L64-L79)
Source equality is evaluated by `isEqual`, which checks reference identity for static sources or compares key counts and strict reference equality for multi-source records.
Sources: [packages/core/src/source/dynamic.ts:121-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L121-L133)
```typescript
function isEqual(a: ResolvedSource, b: ResolvedSource): boolean {
if (isStaticSource(a) && isStaticSource(b)) {
return a === b;
}
if (!isStaticSource(a) && !isStaticSource(b)) {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
return aKeys.length === bKeys.length && aKeys.every((k) => a[k] === b[k]);
}
return false;
}
```
Sources: [packages/core/src/source/dynamic.ts:121-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L121-L133)
## Loader configuration, plugin pipeline, and execution walkthrough
```mermaid
sequenceDiagram
participant dynamicLoader as dynamic.ts
participant loader as loader.ts
participant resolveConfig as loader.ts
dynamicLoader->>loader: dynamicLoader invokes loader(resolved, options)
loader->>resolveConfig: loader calls resolveConfig(source, options)
resolveConfig-->>loader: returns resolved config containing plugins
```
Sources: [packages/core/src/source/dynamic.ts:90-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L90-L93), [packages/core/src/source/loader.ts:287-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L287-L301), [packages/core/src/source/loader.ts:474-499](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L474-L499)
The execution walkthrough for building plugins and resolving configurations traces through `dynamicLoader` → `loader` → `resolveConfig`. When `dynamicLoader` computes its cache via `get()`, it invokes `loader()` with the resolved source and options. The `loader` function immediately delegates to `resolveConfig()`, which merges base settings, slugs options, icons, and plugins into a unified `ResolvedLoaderConfig`.
Sources: [packages/core/src/source/dynamic.ts:27-119](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L27-L119), [packages/core/src/source/loader.ts:287-499](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L287-L499)
```typescript
export function loader(
...args:
| [
LoaderOptions & {
source: I;
},
]
| [I, LoaderOptions]
): LoaderOutput<{
meta: GenerateMeta;
page: GeneratePage;
i18n: I18n;
}> {
const loaderConfig =
args.length === 2 ? resolveConfig(args[0], args[1]) : resolveConfig(args[0].source, args[0]);
```
Sources: [packages/core/src/source/loader.ts:287-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L287-L301)
> [!NOTE]
> `resolveConfig` unpacks base loader configurations and validates internationalization parameters before content storage builder initialization.
> Sources: [packages/core/src/source/loader.ts:474-479](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L474-L479)
The slugs plugin (`slugsPlugin`) inspects files via `storage.getFiles()`, processing non-page items or files with pre-existing slugs. When a custom `slugFn` is absent, it identifies index files via `isIndex`, pushing them to an index queue to prevent collision conflicts between `dir/index.mdx` and `dir.mdx`.
Sources: [packages/core/src/source/plugins/slugs.ts:15-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L15-L35)
```typescript
transformStorage({ storage }) {
const indexFiles: string[] = [];
const taken = new Set();
for (const path of storage.getFiles()) {
const file = storage.read(path);
if (!file || file.format !== 'page' || file.slugs) continue;
const customSlugs = slugFn?.(file);
// for custom slugs function, don't handle conflicting cases like `dir/index.mdx` vs `dir.mdx`
if (customSlugs === undefined && isIndex(path)) {
indexFiles.push(path);
continue;
}
file.slugs = customSlugs ?? getSlugs(path);
const key = file.slugs.join('/');
if (taken.has(key)) throw new Error(`Duplicated slugs: ${key}`);
taken.add(key);
}
```
Sources: [packages/core/src/source/plugins/slugs.ts:22-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L22-L41)
> [!WARNING]
> Duplicate slug keys detected across storage entries trigger an immediate error throw via `if (taken.has(key)) throw new Error(...)`.
> Sources: [packages/core/src/source/plugins/slugs.ts:38-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L38-L40)
Path segregation filters out empty directory names and folder groups matching `GroupRegex` (`/^\(.+\)$/`). Any attempt to use a folder group directly inside a file name throws an error.
Sources: [packages/core/src/source/plugins/slugs.ts:69-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L69-L85)
```typescript
export function getSlugs(file: string): string[] {
const dir = dirname(file);
const name = basename(file, extname(file));
const slugs: string[] = [];
for (const seg of dir.split('/')) {
// filter empty names and file groups like (group_name)
if (seg.length > 0 && !GroupRegex.test(seg)) slugs.push(encodeURI(seg));
}
if (GroupRegex.test(name)) throw new Error(`Cannot use folder group in file names: ${file}`);
if (name !== 'index') {
slugs.push(encodeURI(name));
}
return slugs;
```
Sources: [packages/core/src/source/plugins/slugs.ts:74-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L74-L90)
## Local markdown and disk storage
### File scanning and storage implementation
```mermaid
graph TD
subgraph Storage Flow
A[glob include patterns] -->|cwd: dir| B[chunked file promises]
B -->|CHUNK_SIZE: 100| C[buildFile]
C -->|extname: .json| D[json meta parser]
C -->|extname: .md or .mdx| E[md frontmatter parser]
end
```
Sources: [packages/local-md/src/storage.ts:23-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L23-L56), [packages/local-md/src/storage.ts:110-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L110-L126)
Local markdown collections are managed by `createStorage`, which scans content directories using `tinyglobby` with configurable include patterns. Discovered files are batched into chunks of 100 items (`CHUNK_SIZE`) and processed concurrently via `buildFile`. Files are discriminated by extension: `.json` files are parsed as metadata collections, while `.md` and `.mdx` files are processed for frontmatter and body content.
Sources: [packages/local-md/src/storage.ts:23-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L23-L56), [packages/local-md/src/storage.ts:110-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L110-L126)
```typescript
async getPages() {
const files = await glob(include, {
cwd: dir,
});
const chunks: Promise<($Page | $Meta | undefined)[]>[] = [];
for (let i = 0; i < files.length; i += CHUNK_SIZE) {
const promises: Promise<$Page | $Meta | undefined>[] = [];
const L = Math.min(files.length, i + CHUNK_SIZE);
for (let j = i; j < L; j++) {
promises.push(buildFile(files[j]));
}
chunks.push(Promise.all(promises));
}
const pages: $Page[] = [];
const metas: $Meta[] = [];
for await (const chunk of chunks) {
for (const item of chunk) {
if (!item) continue;
if ('frontmatter' in item) pages.push(item);
else metas.push(item);
}
}
return { pages, metas };
},
```
Sources: [packages/local-md/src/storage.ts:110-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L110-L138)
> [!WARNING]
> If building a file throws an error, the catch block logs the failure to the console and deletes the corresponding absolute path entry from `filesCache`.
> Sources: [packages/local-md/src/storage.ts:62-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L62-L66)
### Frontmatter parsing and schema validation
```typescript
async function md(absolutePath: string, file: string): Promise<$Page> {
const content = await fs.readFile(absolutePath, 'utf-8');
const parsed = parseFrontmatter(content);
const frontmatterResult = await frontmatterSchema['~standard'].validate(parsed.data);
if (frontmatterResult.issues) {
const message = frontmatterResult.issues
.map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message))
.join('\n');
throw new Error(`invalid frontmatter in "${absolutePath}": ${message}`);
}
return {
path: file,
absolutePath,
content: parsed.content,
frontmatter: frontmatterResult.value,
};
}
```
Sources: [packages/local-md/src/storage.ts:68-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L68-L86)
Markdown and MDX files are read from disk and processed with `parseFrontmatter` to separate content from metadata headers. The extracted frontmatter object is validated against standard schemas using `frontmatterSchema['~standard'].validate()`. If validation fails, issues are mapped into a detailed multi-line error string reporting path and message specifics.
Sources: [packages/local-md/src/storage.ts:68-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L68-L86)
| Extension | Target Interface | Validation Schema | Parser Utility |
| :--- | :--- | :--- | :--- |
| `.md`, `.mdx` | `RawPage` | `frontmatterSchema` | `parseFrontmatter` |
| `.json` | `RawMeta` | `metaSchema` | `JSON.parse` |
Sources: [packages/local-md/src/storage.ts:10-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L10-L21), [packages/local-md/src/storage.ts:72-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L72-L97)
> [!CAUTION]
> Schema validation errors halt execution immediately by throwing an `Error` containing formatted validation issues for either invalid frontmatter or invalid JSON data.
> Sources: [packages/local-md/src/storage.ts:73-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L73-L78), [packages/local-md/src/storage.ts:92-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L92-L97)
### Runtime adapters and dev server integration
```typescript
export function localMd<
FrontmatterSchema extends StandardSchemaV1 = typeof defaultSchemas.pageSchema,
MetaSchema extends StandardSchemaV1 = typeof defaultSchemas.metaSchema,
>(
config: LocalMarkdownConfig,
): LocalMarkdown {
const storage = createStorage(config);
const compiler = createMarkdownCompiler(config);
const compilerCache = new WeakMap, Promise>();
const registeredLoaders = new Set();
let cachedStaticSource: Promise<
StaticSource<{
pageData: LocalMarkdownPage, never>;
metaData: StandardSchemaV1.InferOutput & MetaData;
}>
> | null = null;
async function createFiles(options?: SourceOptions) {
const { metas, pages } = await storage.getPages();
const baseDir = options?.baseDir;
const files: VirtualFile<{
pageData: LocalMarkdownPage, never>;
metaData: StandardSchemaV1.InferOutput & MetaData;
}>[] = [];
for (const page of pages) {
const frontmatter = page.frontmatter as PageData & { _openapi?: unknown };
files.push({
type: 'page',
path: baseDir ? path.join(baseDir, page.path) : page.path,
absolutePath: page.absolutePath,
data: {
title: frontmatter.title ?? path.basename(page.path, path.extname(page.path)),
description: frontmatter.description,
icon: frontmatter.icon,
// for Fumadocs OpenAPI
['_openapi' as never]: frontmatter._openapi,
content: page.content,
frontmatter: page.frontmatter,
async load() {
let promise = compilerCache.get(page);
if (!promise) {
promise = compiler.compile({
path: page.absolutePath,
value: page.content,
data: { frontmatter: page.frontmatter },
});
}
const res = await promise;
return res.type === 'ast'
? fromAst({
tree: res.tree,
filePath: res.file.path,
rehypeToc: res.file.data.rehypeToc,
structuredData: res.file.data.structuredData,
...config.rendererOptions,
})
: fromJS({
code: res.code,
filePath: res.file.path,
baseUrl: pathToFileURL(res.file.path).href,
structuredData: res.file.data.structuredData,
});
},
},
});
}
```
Sources: [packages/local-md/src/index.ts:84-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L84-L153)
The `localMd` function exposes `staticSource` and `dynamicSource` runtime adapters that transform raw storage entities into virtual files consumed by core loaders. Each page object provides an asynchronous `load` method that compiles content via a markdown compiler instance, utilizing `compilerCache` to memoize compilation promises per page. When connected to a development server via `devServer`, the runner watches the target directory and dispatches file invalidation events.
Sources: [packages/local-md/src/index.ts:84-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L84-L153), [packages/local-md/src/index.ts:174-195](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L174-L195)
> [!NOTE]
> Calling `invalidateFile` resets `cachedStaticSource` to `null`, evicts the path from `storage`, and triggers invalidation callbacks on all registered dynamic loaders.
> Sources: [packages/local-md/src/index.ts:168-173](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L168-L173)
## Client deserialization and preview runtime
### Client-side page tree consumption
```tsx
export function deserializePageTree(serialized: SerializedPageTree): PageTree.Root {
const root = serialized.data as PageTree.Root;
visit(root, (item) => {
if ('icon' in item && typeof item.icon === 'string') {
item.icon = (
);
}
if (typeof item.name === 'string') {
item.name = (
);
}
});
return root;
}
```
Sources: [packages/core/src/source/client/index.tsx:14-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L39)
The client package handles serialized navigation trees generated by the server-side loader through `deserializePageTree`. It inspects incoming objects using `isSerializedPageTree`, verifying that `$fumadocs_loader` is set to `'page-tree'`. Once validated, `visit` traverses the tree nodes, parsing raw HTML strings for item icons and names into React span elements configured with `dangerouslySetInnerHTML`.
Sources: [packages/core/src/source/client/index.tsx:5-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L5-L8), [packages/core/src/source/client/index.tsx:14-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L39), [packages/core/src/source/client/index.tsx:62-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L62-L69)
```tsx
export function useFumadocsLoader(serialized: V): Serialized {
return useMemo(() => {
const out: Record = {};
for (const k in serialized) {
const v = serialized[k];
if (isSerializedPageTree(v)) {
out[k] = deserializePageTree(v);
} else {
out[k] = v;
}
}
return out as Serialized;
}, [serialized]);
}
```
Sources: [packages/core/src/source/client/index.tsx:47-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L47-L60)
The `useFumadocsLoader` hook memoizes deserialization across re-renders. It iterates over the properties of the provided serialized object, converting matching page tree structures while preserving all unrelated properties in the output.
Sources: [packages/core/src/source/client/index.tsx:47-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L47-L60)
> [!NOTE]
> `useFumadocsLoader` preserves any non-loader properties present on the input object alongside the freshly parsed page tree elements.
> Sources: [packages/core/src/source/client/index.tsx:42-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L42-L46), [packages/core/src/source/client/index.tsx:54-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L54-L56)
### Preview revalidation hooks and route rendering
```typescript
export const getSource = revalidable({
async create(config: ParsedAppConfig) {
return loader({
source: source(await getPages(config.content)),
plugins: [lucideIconsPlugin()],
baseUrl: '/',
});
},
});
```
Sources: [packages/preview/src/lib/source/index.ts:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts#L7-L15)
The preview application defines `getSource` via a revalidable wrapper that instantiates a content loader using `source` with local page data and the `lucideIconsPlugin`. Document paths and page image routes are managed by `getPageImage`, which appends `image.webp` segments to the URL path array.
Sources: [packages/preview/src/lib/source/index.ts:7-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts#L7-L27)
```tsx
export default async function DocPage({ slugs }: PageProps<'/docs/[...slugs]'>) {
const config = await getConfigRuntime();
const source = await getSource(config);
const page = source.getPage(slugs);
const mdPreset = config.layout.presets?.md ?? 'docs';
let mdPresetComponents: MdPresetComponents;
if (mdPreset === 'docs') {
mdPresetComponents = {
layout: await import('fumadocs-ui/layouts/docs'),
page: await import('fumadocs-ui/layouts/docs/page'),
};
} else {
mdPresetComponents = {
layout: await import('fumadocs-ui/layouts/flux'),
page: await import('fumadocs-ui/layouts/flux/page'),
};
}
return ;
}
```
Sources: [packages/preview/src/pages/...slugs.tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L76-L96)
The dynamic route component `DocPage` resolves runtime configurations and dynamic layout presets (`docs` or `flux`) before rendering document contents. During compilation, remark and rehype plugins process markdown tables, mathematics, mermaid diagrams, code blocks, and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) data.
Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46), [packages/preview/src/pages/...slugs.tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L76-L96)
| Preset Name | Layout Import | Page Import |
| :--- | :--- | :--- |
| `docs` | `fumadocs-ui/layouts/docs` | `fumadocs-ui/layouts/docs/page` |
| Other | `fumadocs-ui/layouts/flux` | `fumadocs-ui/layouts/flux/page` |
Sources: [packages/preview/src/pages/...slugs.tsx:83-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L83-L93)
> [!WARNING]
> If markdown compilation encounters an error, `DocPage` catches the exception and renders a fallback error view containing the exception message and stack trace inside a code block.
> Sources: [packages/preview/src/pages/[...slugs].tsx:169-194](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L169-L194)
## Related
- [Page Tree Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation)
- [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline)
---
## Technical docs: Page Tree Generation
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/source/page-tree/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts)
- [packages/radix-ui/src/components/sidebar/page-tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx)
- [packages/base-ui/src/components/sidebar/page-tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/page-tree.tsx)
- [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx)
- [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx)
- [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx)
- [packages/base-ui/src/components/sidebar/tabs/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx)
- [packages/radix-ui/src/components/sidebar/tabs/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/tabs/index.tsx)
- [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts)
- [packages/core/src/source/plugins/status-badges.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx)
- [packages/radix-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts)
- [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx)
- [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx)
- [packages/core/src/source/llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/llms.ts)
- [packages/cli/src/commands/file-tree.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts)
- [packages/base-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts)
- [packages/radix-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx)
- [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx)
- [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx)
- [packages/base-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx)
- [packages/core/src/source/page-tree/transformer-fallback.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts)
- [packages/core/src/page-tree/utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts)
- [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts)
- [packages/core/src/breadcrumb.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/breadcrumb.tsx)
- [packages/epub/src/toc-builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/src/toc-builder.ts)
- [packages/openapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts)
- [packages/asyncapi/src/utils/pages/preset-auto.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts)
- [packages/base-ui/src/components/sidebar/link-item.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/link-item.tsx)
- [packages/radix-ui/src/components/sidebar/link-item.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/link-item.tsx)
- [packages/radix-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx)
## Overview
Page tree generation constructs and manages the hierarchical navigation models that organize documentation content across the Fumadocs framework ecosystem. By parsing content files, resolving directory structures, and processing metadata, the builder turns raw file storage into structured node primitives including roots, folders, items, and separators.
Sources: [packages/core/src/source/page-tree/builder.ts:72-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L72-L87), [packages/core/src/source/loader.ts:1-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L1-L15)
## Page Tree Data Structures
### Node Types and Primitives
The core page tree architecture represents documentation structures through a set of primitive node schemas and symbols. Internal builder structures attach metadata such as `SymbolUnfinished`, `SymbolName`, and `SymbolOwner` to track ownership priority and resolve references when multiple folders claim the same node.
Sources: [packages/core/src/source/page-tree/builder.ts:74-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L74-L82)
The builder interface exposes path resolution and root generation capabilities through the `PageTreeBuilder` contract.
```typescript
export interface PageTreeBuilder {
resolveFlattenPath(name: string, format: string): string;
root(id?: string, path?: string): PageTree.Root;
}
```
Sources: [packages/core/src/source/page-tree/builder.ts:84-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L84-L87)
Tree traversal utilities operate on nodes and roots, flattening hierarchical structures into ordered arrays of page items, locating neighboring nodes for pagination, and discovering parent containers via depth-first searches.
Sources: [packages/core/src/page-tree/utils.ts:6-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L6-L19), [packages/core/src/page-tree/utils.ts:24-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L24-L33), [packages/core/src/page-tree/utils.ts:105-119](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L105-L119)
## Hierarchical Tree Builder
### File Scanning and Path Resolution
The builder initializes by scanning storage instances via `createPageTreeBuilder`, mapping every file and its content format into a flattened path lookup table. The `excludePrefix` constant (`!`) identifies excluded items during tree construction, while internal symbols track state: `SymbolUnfinished` marks incomplete nodes, `SymbolName` stores display identifiers, and `SymbolOwner` records ownership objects consisting of an owner path and priority.
```typescript
const excludePrefix = '!';
const SymbolUnfinished = Symbol('unfinished');
const SymbolName = Symbol('name');
const SymbolOwner = Symbol('owner');
interface Attached {
[SymbolName]?: string;
[SymbolUnfinished]?: boolean;
[SymbolOwner]?: { owner: string; priority: number };
}
```
Sources: [packages/core/src/source/page-tree/builder.ts:72-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L72-L82)
Content storages are iterated to register file paths by stripping their extensions and concatenating format extensions into `flattenPathToFullPath` mapping entries. The `resolveFlattenPath` method retrieves the full file path from a given name and format or falls back to the original name.
```typescript
for (const file of storage.getFiles()) {
const content = storage.read(file)!;
const flattenPath = file.substring(0, file.length - extname(file).length);
flattenPathToFullPath.set(flattenPath + '.' + content.format, file);
}
function resolveFlattenPath(name: string, format: string) {
return flattenPathToFullPath.get(name + '.' + format) ?? name;
}
```
Sources: [packages/core/src/source/page-tree/builder.ts:140-149](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L140-L149)
### Ownership Tracking and Transfer
When multiple folders reference the same node, ownership tracking determines container assignment based on priority values. The `own` function checks if a node is unfinished, evaluates existing ownership, updates matching ownership priorities, or revokes ownership from lower-priority folders by splicing nodes out of their children lists and clearing folder index references.
```typescript
function own(ownerPath: string, node: PageTree.Node & Attached, priority: number): boolean {
if (node[SymbolUnfinished]) return false;
const existing = node[SymbolOwner];
if (!existing) {
node[SymbolOwner] = { owner: ownerPath, priority };
return true;
}
if (existing.owner === ownerPath) {
existing.priority = Math.max(existing.priority, priority);
return true;
}
if (existing.priority >= priority) return false;
// return ownership
const folder = pathToNode.get(existing.owner);
if (folder && folder.type === 'folder') {
if (folder.index === node) {
delete folder.index;
} else {
const idx = folder.children.indexOf(node);
if (idx !== -1) folder.children.splice(idx, 1);
}
}
existing.owner = ownerPath;
existing.priority = priority;
return true;
}
function transferOwner(ownerPath: string, node: PageTree.Node & Attached) {
const existing = node[SymbolOwner];
if (existing) existing.owner = ownerPath;
}
```
Sources: [packages/core/src/source/page-tree/builder.ts:158-190](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L158-L190)
> [!NOTE]
> Lower priority owners attempting to claim a node already owned by a higher priority parent will have their claim rejected, returning `false` without modifying existing ownership boundaries.
Sources: [packages/core/src/source/page-tree/builder.ts:169-169](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L169-L169)
### Fallback Transformation
The fallback mechanism implemented in `transformerFallback` captures unreferenced files and directories that were not visited during standard tree building. It isolates remaining storage items and generates a secondary fallback page tree prefixed with `fallback`.
```typescript
export function transformerFallback(): PageTreeTransformer {
const addedFiles = new Set();
function shouldIgnore(context: PageTreeBuilderContext) {
return context.custom?._fallback === true;
}
return {
root(root) {
if (shouldIgnore(this)) return root;
const isolatedStorage = new FileSystem() as ContentStorage;
if (addedFiles.size === this.storage.files.size) return root;
for (const file of this.storage.getFiles()) {
if (addedFiles.has(file)) continue;
isolatedStorage.write(file, this.storage.read(file)!);
}
root.fallback = createPageTreeBuilder(isolatedStorage, {
...this.options,
idPrefix: this.options.idPrefix ? `fallback:${this.options.idPrefix}` : 'fallback',
generateFallback: false,
context: { ...this.custom, _fallback: true },
}).root();
addedFiles.clear();
return root;
},
file(node, file) {
if (shouldIgnore(this)) return node;
if (file) addedFiles.add(file);
return node;
},
folder(node, _dir, metaPath) {
if (shouldIgnore(this)) return node;
if (metaPath) addedFiles.add(metaPath);
return node;
},
};
}
```
Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:5-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L5-L45)
## Tree Navigation and Traversal Utilities
### Depth-First Tree Visitation and Mutation
The `visit` function executes a depth-first search across a page tree or node collection, invoking a visitor callback for each encountered node. The visitor callback can return `'skip'` to bypass children of the current node, `'break'` to terminate the search entirely via a thrown `VisitBreak` symbol caught internally, or a modified node object to perform in-place tree transformations.
```typescript
export function visit(
root: Root,
visitor: (
node: T,
parent?: PageTree.Root | PageTree.Folder,
) => 'skip' | 'break' | T | void,
): Root {
function onNode(
node: T,
parent?: PageTree.Root | PageTree.Folder,
): T {
const result = visitor(node, parent);
switch (result) {
case 'skip':
return node;
case 'break':
throw VisitBreak;
default:
if (result) node = result;
}
if ('index' in node && node.index) {
node.index = onNode(node.index, node);
}
if ('fallback' in node && node.fallback) {
node.fallback = onNode(node.fallback, node);
}
if ('children' in node) {
for (let i = 0; i < node.children.length; i++) {
node.children[i] = onNode(node.children[i], node);
}
}
return node;
}
try {
return onNode(root);
} catch (e) {
if (e === VisitBreak) return root;
throw e;
}
}
```
Sources: [packages/core/src/page-tree/utils.ts:176-220](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L176-L220)
> [!WARNING]
> Returning `'break'` from a visitor callback throws an internal `VisitBreak` symbol that is intercepted by `visit` to cleanly return the unmodified root reference, avoiding unhandled exceptions during traversal aborts.
Sources: [packages/core/src/page-tree/utils.ts:168-175](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L168-L175), [packages/core/src/page-tree/utils.ts:214-219](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L214-L219)
### Path Lookup and Neighbor Resolution
Path lookup and list flattening utilities transform hierarchical tree structures into linear arrays or specific ancestor trails. The `flattenTree` function iterates over nodes, extracting folder indices and nested children recursively into a flat list of page items.
```typescript
export function flattenTree(nodes: PageTree.Node[]): PageTree.Item[] {
const out: PageTree.Item[] = [];
for (const node of nodes) {
if (node.type === 'folder') {
if (node.index) out.push(node.index);
out.push(...flattenTree(node.children));
} else if (node.type === 'page') {
out.push(node);
}
}
return out;
}
```
Sources: [packages/core/src/page-tree/utils.ts:6-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L6-L19)
The `findPath` function searches for a node matching a predicate, optionally including separators in the returned path array. Breadcrumb generation leverages `searchPath` to resolve the current URL against normalized tree paths.
```typescript
export function findPath(
nodes: PageTree.Node[],
matcher: (node: PageTree.Node) => boolean,
options: {
includeSeparator?: boolean;
} = {},
): PageTree.Node[] | null {
const { includeSeparator = true } = options;
function run(nodes: PageTree.Node[]): PageTree.Node[] | undefined {
let separator: PageTree.Separator | undefined;
for (const node of nodes) {
if (matcher(node)) {
const items: PageTree.Node[] = [];
if (separator) items.push(separator);
items.push(node);
return items;
}
if (node.type === 'separator' && includeSeparator) {
separator = node;
continue;
}
if (node.type === 'folder') {
const items = node.index && matcher(node.index) ? [node.index] : run(node.children);
if (items) {
items.unshift(node);
if (separator) items.unshift(separator);
return items;
}
}
}
}
return run(nodes) ?? null;
}
```
Sources: [packages/core/src/page-tree/utils.ts:126-166](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L126-L166)
| Utility Function | Parameters | Return Type | Description |
| :--- | :--- | :--- | :--- |
| `flattenTree` | `nodes: PageTree.Node[]` | `PageTree.Item[]` | Flattens folders, index nodes, and pages into a single sequential list. |
| `findNeighbour` | `tree: PageTree.Root`, `url: string`, `options?: { separateRoot?: boolean }` | `{ previous?: PageTree.Item, next?: PageTree.Item }` | Resolves adjacent previous and next page items for pagination controls. |
| `getPageTreeRoots` | `pageTree: PageTree.Root \| PageTree.Folder` | `(PageTree.Root \| PageTree.Folder)[]` | Collects all root nodes and nested root folders. |
| `getPageTreePeers` | `treeOrTrees: PageTree.Root \| Record`, `url: string` | `PageTree.Item[]` | Retrieves peer page nodes residing under the same parent container. |
| `findSiblings` | `treeOrTrees: PageTree.Root \| Record`, `url: string` | `PageTree.Node[]` | Retrieves all sibling tree nodes under the same parent. |
| `findParent` | `from: PageTree.Root \| PageTree.Folder`, `url: string` | `PageTree.Root \| PageTree.Folder \| undefined` | Locates the parent container of a page matched by its URL. |
| `findPath` | `nodes: PageTree.Node[]`, `matcher: (node: PageTree.Node) => boolean`, `options?: { includeSeparator?: boolean }` | `PageTree.Node[] \| null` | Finds the array of nodes forming the path to a matched node. |
Sources: [packages/core/src/page-tree/utils.ts:6-166](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L6-L166)
## Status Badges and Tree Transformation
### Status Badges Plugin Architecture
The `statusBadgesPlugin` function returns a loader plugin named `fumadocs:status-badges` that decorates navigation items with status indicators by inspecting document frontmatter. When processing a file node, the transformer checks whether the file format is `'page'` and whether a string-typed `status` property exists within `file.data`.
```tsx
export function statusBadgesPlugin(
options: {
renderBadge?: (status: string) => ReactNode;
} = {},
): LoaderPlugin {
const { renderBadge = (status) => {status} } = options;
return {
name: 'fumadocs:status-badges',
transformPageTree: {
file(node, filePath) {
if (!filePath) return node;
const file = this.storage.read(filePath);
if (
file?.format === 'page' &&
'status' in file.data &&
typeof file.data.status === 'string'
) {
const status = file.data.status;
node.name = (
<>
{node.name}
{renderBadge(status)}
>
);
(node as Item).status = status;
}
return node;
},
},
};
```
Sources: [packages/core/src/source/plugins/status-badges.tsx:50-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx#L50-L83)
If a valid status string is located, the plugin modifies `node.name` by appending a rendered badge element alongside the original node name, and assigns the raw status string directly to `(node as Item).status`. Consumers can customize badge rendering by passing a `renderBadge` callback option; if omitted, the plugin defaults to rendering a `` element equipped with a `data-status` attribute.
```tsx
const { renderBadge = (status) => {status} } = options;
return {
name: 'fumadocs:status-badges',
transformPageTree: {
file(node, filePath) {
if (!filePath) return node;
const file = this.storage.read(filePath);
if (
file?.format === 'page' &&
'status' in file.data &&
typeof file.data.status === 'string'
) {
const status = file.data.status;
node.name = (
<>
{node.name}
{renderBadge(status)}
>
);
(node as Item).status = status;
}
```
Sources: [packages/core/src/source/plugins/status-badges.tsx:55-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx#L55-L78)
> [!NOTE]
> The `statusBadgesPlugin` strictly requires `filePath` to be defined on the node and relies on `this.storage.read(filePath)` to access document frontmatter during tree transformation.
Sources: [packages/core/src/source/plugins/status-badges.tsx:60-63](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx#L60-L63)
### Fallback Tree Transformation
The `transformerFallback` function constructs a secondary fallback page tree builder by intercepting root, file, and folder transformation hooks. It tracks processed files in an internal `addedFiles` set and inspects the builder context via `shouldIgnore` to verify whether `context.custom?._fallback` is enabled, preventing recursive fallback generation loops.
```typescript
export function transformerFallback(): PageTreeTransformer {
const addedFiles = new Set();
function shouldIgnore(context: PageTreeBuilderContext) {
return context.custom?._fallback === true;
}
return {
root(root) {
if (shouldIgnore(this)) return root;
const isolatedStorage = new FileSystem() as ContentStorage;
if (addedFiles.size === this.storage.files.size) return root;
for (const file of this.storage.getFiles()) {
if (addedFiles.has(file)) continue;
isolatedStorage.write(file, this.storage.read(file)!);
}
root.fallback = createPageTreeBuilder(isolatedStorage, {
...this.options,
idPrefix: this.options.idPrefix ? `fallback:${this.options.idPrefix}` : 'fallback',
generateFallback: false,
context: { ...this.custom, _fallback: true },
}).root();
addedFiles.clear();
return root;
},
file(node, file) {
if (shouldIgnore(this)) return node;
if (file) addedFiles.add(file);
return node;
},
folder(node, _dir, metaPath) {
if (shouldIgnore(this)) return node;
if (metaPath) addedFiles.add(metaPath);
return node;
},
};
```
Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:5-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L5-L45)
When the root transformer executes, it initializes an isolated file system storage instance, copies unindexed files that are absent from `addedFiles`, and instantiates a nested page tree builder with a modified `idPrefix` and a restricted context where `_fallback` is set to `true`.
```typescript
root(root) {
if (shouldIgnore(this)) return root;
const isolatedStorage = new FileSystem() as ContentStorage;
if (addedFiles.size === this.storage.files.size) return root;
for (const file of this.storage.getFiles()) {
if (addedFiles.has(file)) continue;
isolatedStorage.write(file, this.storage.read(file)!);
}
root.fallback = createPageTreeBuilder(isolatedStorage, {
...this.options,
idPrefix: this.options.idPrefix ? `fallback:${this.options.idPrefix}` : 'fallback',
generateFallback: false,
context: { ...this.custom, _fallback: true },
}).root();
```
Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:12-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L12-L29)
> [!WARNING]
> The fallback transformer clears `addedFiles` immediately after constructing the fallback tree root, ensuring subsequent transformation passes evaluate file additions correctly.
Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L30-L31)
## Client Serialization and State Contexts
### Serialization and Hydration
Page trees generated by server-side loaders are serialized into a standard format before transmission across client-server boundaries. The `SerializedPageTree` interface wraps data using the `$fumadocs_loader` discriminator set to `'page-tree'`.
```tsx
export interface SerializedPageTree {
$fumadocs_loader: 'page-tree';
data: object;
}
```
Sources: [packages/core/src/source/client/index.tsx:5-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L5-L8)
The `useFumadocsLoader` hook processes serialized loader data, identifying serialized page trees and passing them to `deserializePageTree` for hydration.
```tsx
export function useFumadocsLoader(serialized: V): Serialized {
return useMemo(() => {
const out: Record = {};
for (const k in serialized) {
const v = serialized[k];
if (isSerializedPageTree(v)) {
out[k] = deserializePageTree(v);
} else {
out[k] = v;
}
}
return out as Serialized;
}, [serialized]);
}
```
Sources: [packages/core/src/source/client/index.tsx:47-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L47-L60)
During deserialization, `visit` traverses the page tree nodes to parse and inject HTML strings for `icon` and `name` properties via `dangerouslySetInnerHTML`.
```tsx
export function deserializePageTree(serialized: SerializedPageTree): PageTree.Root {
const root = serialized.data as PageTree.Root;
visit(root, (item) => {
if ('icon' in item && typeof item.icon === 'string') {
item.icon = (
);
}
if (typeof item.name === 'string') {
item.name = (
);
}
});
return root;
}
```
Sources: [packages/core/src/source/client/index.tsx:14-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L39)
> [!NOTE]
> `deserializePageTree` inspects every visited node and converts string-based icons and names into React element structures containing `dangerouslySetInnerHTML` wrappers.
Sources: [packages/core/src/source/client/index.tsx:16-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L16-L35)
### Tree Contexts and Path Tracking
The `TreeContextProvider` component manages active tree state, path breadcrumbs, and unique root identifiers across client navigation. It computes the active breadcrumb path by searching the tree and its fallback children against the current pathname.
Sources: [packages/radix-ui/src/contexts/tree.tsx:17-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L17-L47)
| Context/Hook | Return Type | Purpose |
| --- | --- | --- |
| `TreeContext` | `TreeContextType` | Holds the active root node (`root`) and the complete page tree (`full`). |
| `PathContext` | `PageTree.Node[]` | Tracks the hierarchical node path leading to the current active pathname. |
| `useTreePath()` | `PageTree.Node[]` | Retrieves the current path node array from `PathContext`. |
| `useTreeContext()` | `TreeContextType` | Retrieves the active tree context, throwing an error if uninitialized. |
Sources: [packages/radix-ui/src/contexts/tree.tsx:9-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L9-L12), [packages/radix-ui/src/contexts/tree.tsx:15-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L15-L15), [packages/radix-ui/src/contexts/tree.tsx:49-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L49-L57)
> [!WARNING]
> `useTreeContext` throws an explicit error if invoked outside of a component wrapped under ``.
Sources: [packages/radix-ui/src/contexts/tree.tsx:53-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L53-L57)
## Sidebar Node Rendering and Navigation
### Recursive Folder Hierarchies and Active States
The `createPageTreeRenderer` function generates React component trees from page tree structures by recursively traversing nodes via `renderList` and `PageTreeNode`. It evaluates each node type—separator, folder, or page item—and dispatches rendering to either custom user-supplied components or default UI primitives.
```tsx
export function createPageTreeRenderer({
SidebarFolder,
SidebarFolderContent,
SidebarFolderLink,
SidebarFolderTrigger,
SidebarSeparator,
SidebarItem,
}: InternalComponents) {
function renderList(nodes: PageTree.Node[]) {
return nodes.map((node, i) => );
}
function PageTreeNode({ node }: { node: PageTree.Node }) {
const { Separator, Item, Folder, pathname } = use(RendererContext)!;
if (node.type === 'separator') {
if (Separator) return ;
return (
{node.icon}
{node.name}
);
}
if (node.type === 'folder') {
// eslint-disable-next-line react-hooks/rules-of-hooks -- assume node type unchanged
const path = useTreePath();
if (Folder) return {renderList(node.children)};
return (
{node.index ? (
{node.icon}
{node.name}
) : (
{node.icon}
{node.name}
)}
{renderList(node.children)}
);
}
if (Item) return ;
return (
{node.name}
);
}
```
Sources: [packages/radix-ui/src/components/sidebar/page-tree.tsx:31-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L31-L98)
Active states for individual items and index links are determined by comparing their target URLs against the current router pathname using the `isActive` utility. For folders, the `useTreePath` hook checks whether the folder is included in the current branch path to set expansion and highlight states.
```tsx
if (node.type === 'folder') {
// eslint-disable-next-line react-hooks/rules-of-hooks -- assume node type unchanged
const path = useTreePath();
if (Folder) return {renderList(node.children)};
return (
{node.index ? (
{node.icon}
{node.name}
) : (
{node.icon}
{node.name}
)}
{renderList(node.children)}
);
}
if (Item) return ;
return (
{node.name}
);
```
Sources: [packages/radix-ui/src/components/sidebar/page-tree.tsx:56-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L56-L97)
> [!NOTE]
> `RendererContext` caches the active pathname alongside custom component overrides using `useMemo`, ensuring minimal re-renders during client-side navigation.
Sources: [packages/radix-ui/src/components/sidebar/page-tree.tsx:14-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L14-L19), [packages/radix-ui/src/components/sidebar/page-tree.tsx:109-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L109-L114)
### Tab Partitioning and Folder Scanning
The `getSidebarTabs` utility extracts layout tabs from root page trees by scanning folders recursively. It identifies root-level sections and builds a collection of valid navigation endpoints.
```tsx
export function getSidebarTabs(
tree: PageTree.Root,
{ transform = defaultTransform }: GetSidebarTabsOptions = {},
): SidebarTab[] {
const results: SidebarTab[] = [];
function scanOptions(node: PageTree.Root | PageTree.Folder, unlisted?: boolean) {
if ('root' in node && node.root) {
const urls = getFolderUrls(node);
if (urls.size > 0) {
const option: SidebarTab = {
url: urls.values().next().value ?? '',
title: node.name,
icon: node.icon,
unlisted,
description: node.description,
urls,
};
const mapped = transform ? transform(option, node) : option;
if (mapped) results.push(mapped);
}
}
for (const child of node.children) {
if (child.type === 'folder') scanOptions(child, unlisted);
}
}
scanOptions(tree);
if (tree.fallback) scanOptions(tree.fallback, true);
return results;
}
```
Sources: [packages/base-ui/src/components/sidebar/tabs/index.tsx:23-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L23-L57)
| Helper Function | Input Parameters | Return Type | Description |
| --- | --- | --- | --- |
| `getSidebarTabs` | `tree: PageTree.Root, options?: GetSidebarTabsOptions` | `SidebarTab[]` | Scans root nodes and fallback trees to construct partition tabs. |
| `getFolderUrls` | `folder: PageTree.Folder, output?: Set` | `Set` | Collects all non-external page URLs and folder index links within a branch. |
Sources: [packages/base-ui/src/components/sidebar/tabs/index.tsx:23-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L23-L26), [packages/base-ui/src/components/sidebar/tabs/index.tsx:59-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L59-L67)
> [!WARNING]
> If a scanned folder contains no resolvable child pages or index URLs, it is omitted from the resulting sidebar tabs array.
Sources: [packages/base-ui/src/components/sidebar/tabs/index.tsx:30-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L30-L45)
### Sequential Footer Item Navigation
The `useFooterItems` hook produces a flattened, linear array of page tree items suitable for generating footer pagination and sequential next/previous navigation links.
```typescript
export function useFooterItems(): PageTree.Item[] {
const { root } = useTreeContext();
const cached = footerCache.get(root);
if (cached) return cached;
const list: PageTree.Item[] = [];
function onNode(node: PageTree.Node) {
if (node.type === 'folder') {
if (node.index) onNode(node.index);
for (const child of node.children) onNode(child);
} else if (node.type === 'page' && !node.external) {
list.push(node);
}
}
for (const child of root.children) onNode(child);
footerCache.set(root, list);
return list;
```
Sources: [packages/radix-ui/src/utils/use-footer-items.ts:10-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L10-L27)
During traversal, `onNode` processes folders by recursively inspecting folder index nodes and child elements, while filtering out external links and non-page entries before pushing items onto the linear list.
```typescript
function onNode(node: PageTree.Node) {
if (node.type === 'folder') {
if (node.index) onNode(node.index);
for (const child of node.children) onNode(child);
} else if (node.type === 'page' && !node.external) {
list.push(node);
}
}
```
Sources: [packages/radix-ui/src/utils/use-footer-items.ts:16-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L16-L23)
> [!TIP]
> `useFooterItems` caches generated item lists per root reference using a `WeakMap`, avoiding redundant tree traversals across repeated hook calls.
Sources: [packages/radix-ui/src/utils/use-footer-items.ts:5-5](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L5-L5), [packages/radix-ui/src/utils/use-footer-items.ts:12-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L12-L13), [packages/radix-ui/src/utils/use-footer-items.ts:26-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L26-L26)
## Related
- [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader)
- [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture)
---
## Technical docs: Search Server Indexing
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/search/orama/create-server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts)
- [packages/base-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx)
- [packages/radix-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-orama.tsx)
- [packages/core/src/search/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud-legacy.ts)
- [packages/core/src/search/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts)
- [packages/core/src/search/client/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud-legacy.ts)
- [packages/core/src/search/client/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts)
- [packages/core/src/search/orama/create-db.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts)
- [packages/core/src/search/flexsearch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts)
- [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx)
- [packages/core/src/search/algolia.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts)
- [packages/create-app/src/plugins/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts)
- [packages/preview/src/pages/_api/api/search.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/_api/api/search.ts)
- [packages/core/src/search/client/orama-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts)
- [packages/create-app/template/+orama-cloud/@app/lib/export-static-indexes.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/lib/export-static-indexes.ts)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/core/src/search/server/build-index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts)
- [packages/core/src/search/server/build-doc.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts)
- [packages/core/src/search/client/flexsearch-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts)
- [packages/core/src/search/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server.ts)
- [packages/core/src/search/flexsearch/utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts)
- [packages/core/src/search/mixedbread.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts)
- [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/core/src/search/orama/search/simple.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts)
- [packages/core/src/search/orama/search/advanced.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/advanced.ts)
- [packages/create-app/template/+orama-cloud/@app/components/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/components/search.tsx)
- [packages/core/src/search/client/algolia.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts)
- [packages/core/src/search/orama/_stemmers.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/_stemmers.ts)
- [packages/core/src/search/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts)
## Overview
Search Server Indexing transforms raw MDX documentation and source collections into structured, searchable records and indexes for search backends like local databases, Orama Cloud, Algolia, and Mixedbread. It extracts document content, headings, descriptions, and breadcrumbs, supplying consistent search endpoints across localized page trees.
Sources: [packages/core/src/search/server/build-index.ts:6-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L6-L48), [packages/core/src/search/orama/create-server.ts:78-134](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L78-L134)
## Document extraction and structured indexing
### SharedIndex and SharedDocument interfaces
The search indexing pipeline transforms page collections into search-ready payloads using two foundational data structures: `SharedIndex` and `SharedDocument`. A `SharedIndex` captures page-level metadata alongside preprocessed `StructuredData`, while `SharedDocument` decomposes that record into granular searchable entries categorized by type (`page`, `heading`, or `text`).
```typescript
export interface SharedIndex {
id: string;
title: string;
description?: string;
breadcrumbs?: string[];
tag?: string | string[];
structuredData: StructuredData;
url: string;
}
export interface SharedDocument {
id: string;
content: string;
page_id: string;
type: 'page' | 'heading' | 'text';
breadcrumbs?: string[];
tags: string[];
url: string;
}
```
Sources: [packages/core/src/search/server/build-index.ts:6-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L6-L22), [packages/core/src/search/server/build-doc.ts:3-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts#L3-L11)
### Page index building and resolution
The `buildIndexDefault` function resolves structured data from a `Page` object by checking `page.data.structuredData` (evaluating it if defined as a function) or falling back to invoking `page.data.load()` if present. If neither source yields structured data, an error is thrown. Titles default to `page.data.title` or fall back to the filename derived via `basename` and `extname`.
```typescript
export async function buildIndexDefault(page: Page): Promise {
let structuredData: StructuredData | undefined;
if (page.data.structuredData) {
structuredData =
typeof page.data.structuredData === 'function'
? await page.data.structuredData()
: page.data.structuredData;
} else if ('load' in page.data && typeof page.data.load === 'function') {
structuredData = (await page.data.load()).structuredData;
}
if (!structuredData)
throw new Error(
'Cannot find structured data from page, please define the page to index function.',
);
return {
title: page.data.title ?? basename(page.path, extname(page.path)),
description: page.data.description,
url: page.url,
id: page.url,
structuredData,
};
}
```
Sources: [packages/core/src/search/server/build-index.ts:24-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L24-L48)
> [!WARNING]
> Omitting structured data preprocessing on a page without a `load` method or static `structuredData` property causes `buildIndexDefault` to throw an explicit runtime error during index compilation.
Sources: [packages/core/src/search/server/build-index.ts:36-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L36-L39)
### Breadcrumb path resolution
The `buildBreadcrumbs` utility constructs hierarchical navigation paths for search records by querying the localized page tree obtained via `source.getPageTree(page.locale)`. It uses `findPath` to locate the target node, pops the final page segment, and collects valid non-empty string names from parent nodes and the page tree root.
```typescript
function isBreadcrumbItem(item: unknown): item is string {
return typeof item === 'string' && item.length > 0;
}
export function buildBreadcrumbs(
source: LoaderOutput,
page: C['page'],
): string[] | undefined {
const pageTree = source.getPageTree(page.locale);
const path = findPath(pageTree.children, (node) => node.type === 'page' && node.url === page.url);
if (path) {
const breadcrumbs: string[] = [];
path.pop();
if (isBreadcrumbItem(pageTree.name)) {
breadcrumbs.push(pageTree.name);
}
for (const segment of path) {
if (!isBreadcrumbItem(segment.name)) continue;
breadcrumbs.push(segment.name);
}
return breadcrumbs;
}
}
```
Sources: [packages/core/src/search/server/build-index.ts:50-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L50-L76)
### Document flattening and record generation
The `buildDocuments` function iterates over an array of `SharedIndex` objects to produce a flat list of `SharedDocument` records. Each page generates a primary document record (`type: 'page'`), an optional description record (`type: 'text'`), multiple heading records (`type: 'heading'`), and body text content chunks (`type: 'text'`).
| Document Type | ID Format | URL Format | Content Source |
| --- | --- | --- | --- |
| `page` | `page.id` | `page.url` | `page.title` |
| `text` (description) | `${page.id}-${id++}` | `page.url` | `page.description` |
| `heading` | `${page.id}-${id++}` | `${page.url}#${heading.id}` | `heading.content` |
| `text` (content chunk) | `${page.id}-${id++}` | `${page.url}#${content.heading}` or `page.url` | `content.content` |
Sources: [packages/core/src/search/server/build-doc.ts:13-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts#L13-L68)
## Local Orama database instantiation
### Database Schemas and Document Types
The Orama search engine supports two distinct schema configurations depending on whether simple or advanced search servers are initialized. The simple schema defines fields for `url`, `title`, `breadcrumbs`, `description`, `content`, and `keywords`. The advanced schema incorporates granular fields including `content`, `page_id`, `type`, `breadcrumbs`, an `enum[]` for `tags`, `url`, and a 512-dimensional vector field `embeddings`.
```typescript
export type SimpleDocument = TypedDocument>;
export const simpleSchema = {
url: 'string',
title: 'string',
breadcrumbs: 'string[]',
description: 'string',
content: 'string',
keywords: 'string',
} as const;
export type AdvancedDocument = TypedDocument>;
export const advancedSchema = {
content: 'string',
page_id: 'string',
type: 'string',
breadcrumbs: 'string[]',
tags: 'enum[]',
url: 'string',
embeddings: 'vector[512]',
} as const;
```
Sources: [packages/core/src/search/orama/create-db.ts:11-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts#L11-L30)
> [!NOTE]
> Advanced search vector queries require installing `@orama/plugin-embeddings` separately; invoking vector mode without this plugin throws an explicit runtime configuration error.
Sources: [packages/core/src/search/orama/create-server.ts:121-128](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L121-L128)
### Database Creation and Index Insertion
The `createDB` and `createDBSimple` functions instantiate in-memory Orama databases and populate them with records. If `indexes` is supplied as a dynamic function, it is awaited before index processing. Custom tokenizers take precedence when passed in configuration options, falling back to existing component tokenizers.
```typescript
export async function createDB({
indexes,
tokenizer,
search: _,
...rest
}: AdvancedOptions): Promise> {
const items = typeof indexes === 'function' ? await indexes() : indexes;
const db = create({
schema: advancedSchema,
...rest,
components: {
...rest.components,
tokenizer: tokenizer ?? rest.components?.tokenizer,
},
}) as Orama;
const mapTo: PartialSchemaDeep[] = buildDocuments(items);
await insertMultiple(db, mapTo);
return db;
}
```
Sources: [packages/core/src/search/orama/create-db.ts:32-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts#L32-L52)
```typescript
export async function createDBSimple({
indexes,
tokenizer,
...rest
}: SimpleOptions): Promise> {
const items = typeof indexes === 'function' ? await indexes() : indexes;
const db = create({
schema: simpleSchema,
...rest,
components: {
...rest.components,
tokenizer: tokenizer ?? rest.components?.tokenizer,
},
}) as Orama;
await insertMultiple(
db,
items.map((page) => ({
title: page.title,
description: page.description,
breadcrumbs: page.breadcrumbs,
url: page.url,
content: page.content,
keywords: page.keywords,
})),
);
return db;
}
```
Sources: [packages/core/src/search/orama/create-db.ts:54-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts#L54-L82)
### Stemmers and Internationalized Tokenizer Resolution
Internationalized search servers resolve language stemmers using a predefined mapping of full language names to language codes. The `STEMMERS` dictionary defines 32 supported language mappings for tokenization and stemming.
| Language Name | Code | Language Name | Code | Language Name | Code |
| --- | --- | --- | --- | --- | --- |
| `arabic` | `ar` | `irish` | `ie` | `slovenian` | `ru` |
| `armenian` | `am` | `italian` | `it` | `spanish` | `es` |
| `bulgarian` | `bg` | `lithuanian` | `lt` | `swedish` | `se` |
| `czech` | `cz` | `nepali` | `np` | `tamil` | `ta` |
| `danish` | `dk` | `norwegian` | `no` | `turkish` | `tr` |
| `dutch` | `nl` | `portuguese` | `pt` | `ukrainian` | `uk` |
| `english` | `en` | `romanian` | `ro` | `vietnamese` | `vi` |
| `finnish` | `fi` | `russian` | `ru` | `sanskrit` | `sk` |
| `french` | `fr` | `serbian` | `rs` | | |
| `german` | `de` | | | | |
| `greek` | `gr` | | | | |
| `hungarian` | `hu` | | | | |
| `indian` | `in` | | | | |
| `indonesian` | `id` | | | | |
Sources: [packages/core/src/search/orama/_stemmers.ts:2-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/_stemmers.ts#L2-L33)
The `getTokenizer` helper checks if a given locale string matches a registered stemmer key, returning the corresponding language code or falling back directly to the input locale string.
```typescript
function getTokenizer(locale: string): { language: string } | { tokenizer: Tokenizer } {
return {
language: Object.keys(STEMMERS).find((lang) => STEMMERS[lang] === locale) ?? locale,
};
}
```
Sources: [packages/core/src/search/orama/create-server.ts:172-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L172-L176)
## Flexsearch index generation and routing
### Initialization and Execution Walkthrough
Multi-locale Flexsearch indices are constructed and served by navigating through a strict call chain. The process executes through the following steps: `flexsearchI18n` calls `serverI18n`, which invokes `initSearchServers` to group indexes by locale and initialize per-locale servers via `server`. Each `server` call invokes `initIndex`, which builds documents via `buildDocuments` and generates unique identifiers using `nextId`.
```mermaid
sequenceDiagram
participant flexsearchI18n as flexsearch.ts
participant serverI18n as flexsearch.ts
participant initSearchServers as flexsearch.ts
participant server as flexsearch.ts
participant initIndex as flexsearch.ts
participant buildDocuments as build-doc.ts
participant nextId as build-doc.ts
flexsearchI18n->>serverI18n: flexsearchI18n(options)
serverI18n->>initSearchServers: initSearchServers()
initSearchServers->>server: server({ indexes: list, document })
server->>initIndex: initIndex(indexes)
initIndex->>buildDocuments: buildDocuments(indexes)
buildDocuments->>nextId: nextId()
```
Sources: [packages/core/src/search/flexsearch.ts:41-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L137), [packages/core/src/search/server/build-doc.ts:13-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts#L13-L68)
> [!NOTE]
> When `flexsearchFromSource` evaluates a loader function, it caches the resulting promise in a `WeakMap` mapped to the specific loader output instance. Re-indexing occurs automatically once a distinct loader instance is returned.
Sources: [packages/core/src/search/flexsearch.ts:149-186](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L149-L186)
### Document Construction and Search Options
The Flexsearch document schema configures tokenization, indexed fields, and storage options. By default, `createDocument` sets `tokenize` to `'full'`, indexes the `content` field, tags records using `tags`, and enables `store`.
```typescript
export function createDocument(options?: DocumentOptions) {
return new Search.Document({
tokenize: 'full',
...options,
document: {
id: 'id',
index: ['content'],
tag: ['tags'],
store: true,
...options?.document,
},
});
```
Sources: [packages/core/src/search/flexsearch/utils.ts:70-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L70-L81)
| Parameter / Property | Type | Default Value | Purpose |
| --- | --- | --- | --- |
| `tokenize` | string | `'full'` | Sets the string tokenization strategy for indexing. |
| `document.id` | string | `'id'` | Specifies the unique document identifier field. |
| `document.index` | string[] | `['content']` | Defines the document fields included in the search index. |
| `document.tag` | string[] | `['tags']` | Defines the fields used for tag-based filtering. |
| `document.store` | boolean | `true` | Enables field storage within the index for retrieval. |
Sources: [packages/core/src/search/flexsearch/utils.ts:70-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L70-L81)
> [!WARNING]
> Setting a `localeMap` entry to the literal string `'cjk'` automatically forces the document encoder configuration to `Search.Charset.CJK`. Any custom document options passed alongside are overridden or merged depending on the locale map specification.
Sources: [packages/core/src/search/flexsearch.ts:31-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L31-L39), [packages/core/src/search/flexsearch.ts:96-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L96-L100)
## Algolia search index synchronization
### Synchronization Flow and Settings Configuration
Synchronization is executed by the `sync` function, which calls `setIndexSettings` followed by `updateDocuments`. The `indexName` defaults to `'document'` when omitted in `SyncOptions`.
```typescript
export async function sync(client: Algoliasearch, options: SyncOptions): Promise {
const { indexName = 'document', documents } = options;
await setIndexSettings(client, indexName);
await updateDocuments(client, indexName, documents);
}
```
Sources: [packages/core/src/search/algolia.ts:49-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L49-L53)
The index settings are configured via `client.setSettings` with specific attributes for retrieval, faceting, searchability, and distinct filtering.
```typescript
export async function setIndexSettings(client: Algoliasearch, indexName: string): Promise {
await client.setSettings({
indexName,
indexSettings: {
attributeForDistinct: 'page_id',
attributesToRetrieve: ['title', 'section', 'content', 'url', 'section_id', 'breadcrumbs'],
searchableAttributes: ['title', 'section', 'content'],
attributesToSnippet: [],
attributesForFaceting: ['tag'],
},
});
}
```
Sources: [packages/core/src/search/algolia.ts:55-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L55-L66)
| Setting Field | Target Value / Type | Purpose |
| --- | --- | --- |
| `attributeForDistinct` | `'page_id'` | Groups search results by page identifier using distinct records. |
| `attributesToRetrieve` | `['title', 'section', 'content', 'url', 'section_id', 'breadcrumbs']` | Specifies the record attributes returned in search queries. |
| `searchableAttributes` | `['title', 'section', 'content']` | Defines attributes included in search ranking and matching. |
| `attributesToSnippet` | `[]` | Configures snippet generation for retrieved records. |
| `attributesForFaceting` | `['tag']` | Enables tag-based faceting and filtering on records. |
Sources: [packages/core/src/search/algolia.ts:58-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L58-L64)
> [!NOTE]
> The `sync` function replaces all objects in the target index rather than performing incremental updates, ensuring stale records are purged during synchronization.
Sources: [packages/core/src/search/algolia.ts:49-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L49-L53), [packages/core/src/search/algolia.ts:119-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L119-L122)
### Record Batch Transformation
The `toIndex` function processes each `DocumentRecord` to generate an array of `BaseIndex` objects. If a page contains a description, an initial record is created with `undefined` for `section` and `section_id`.
```typescript
function toIndex(page: DocumentRecord): BaseIndex[] {
let id = 0;
const indexes: BaseIndex[] = [];
const scannedHeadings = new Set();
function createIndex(
section: string | undefined,
sectionId: string | undefined,
content: string,
): BaseIndex {
return {
objectID: `${page._id}-${(id++).toString()}`,
breadcrumbs: page.breadcrumbs,
title: page.title,
url: page.url,
page_id: page._id,
tag: page.tag,
section,
section_id: sectionId,
content,
...page.extra_data,
};
}
if (page.description) indexes.push(createIndex(undefined, undefined, page.description));
```
Sources: [packages/core/src/search/algolia.ts:68-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L68-L92)
For each content item in `page.structured`, matching headings are resolved. When a heading is encountered for the first time, a dedicated heading index record is created and added before the content record.
```typescript
const { headings, contents } = page.structured;
for (const p of contents) {
const heading = p.heading ? headings.find((h) => p.heading === h.id) : null;
const index = createIndex(heading?.content, heading?.id, p.content);
if (heading && !scannedHeadings.has(heading.id)) {
scannedHeadings.add(heading.id);
indexes.push(createIndex(heading.content, heading.id, heading.content));
}
indexes.push(index);
}
```
Sources: [packages/core/src/search/algolia.ts:93-107](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L93-L107)
```typescript
return indexes;
}
```
Sources: [packages/core/src/search/algolia.ts:108-110](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L108-L110)
> [!WARNING]
> Object identifiers are constructed by appending an incrementing index counter to `page._id` separated by a hyphen (`${page._id}-${(id++).toString()}`). Collisions will occur if multiple documents share the same `_id`.
Sources: [packages/core/src/search/algolia.ts:78-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L78-L90)
## Orama Cloud integration and export
### Structured Document Export and Index Transformation
The `exportSearchIndexes` function extracts pages from the source collection and maps each entry into an `OramaDocument` containing its unique identifier, URL, title, description, and structured data.
```typescript
export async function exportSearchIndexes() {
return source.getPages().map((page) => {
return {
id: page.url,
structured: page.data.structuredData,
url: page.url,
title: page.data.title,
description: page.data.description,
} satisfies OramaDocument;
});
}
```
Sources: [packages/create-app/template/+orama-cloud/@app/lib/export-static-indexes.ts:4-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/lib/export-static-indexes.ts#L4-L14)
The `toIndex` function converts each `OramaDocument` into an array of `OramaIndex` records by iterating over structured contents and matching headings. If a page description exists, an initial record is created with undefined section identifiers.
```typescript
function toIndex(page: OramaDocument): OramaIndex[] {
let id = 0;
const indexes: OramaIndex[] = [];
const scannedHeadings = new Set();
function createIndex(
section: string | undefined,
sectionId: string | undefined,
content: string,
): OramaIndex {
return {
id: `${page.id}-${(id++).toString()}`,
title: page.title,
url: page.url,
page_id: page.id,
tag: page.tag,
section,
section_id: sectionId,
content,
breadcrumbs: page.breadcrumbs,
...page.extra_data,
};
}
if (page.description) indexes.push(createIndex(undefined, undefined, page.description));
```
Sources: [packages/core/src/search/orama-cloud.ts:118-143](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L118-L143)
```typescript
page.structured.contents.forEach((p) => {
const heading = p.heading ? page.structured.headings.find((h) => p.heading === h.id) : null;
const index = createIndex(heading?.content, heading?.id, p.content);
if (heading && !scannedHeadings.has(heading.id)) {
scannedHeadings.add(heading.id);
indexes.push(createIndex(heading.content, heading.id, heading.content));
}
indexes.push(index);
});
return indexes;
```
Sources: [packages/core/src/search/orama-cloud.ts:144-158](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L144-L158)
> [!WARNING]
> Unique index identifiers are generated by combining the document ID with an incrementing counter separated by a hyphen (``${page.id}-${(id++).toString()}``).
Sources: [packages/core/src/search/orama-cloud.ts:123-140](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L123-L140)
### Remote Synchronization and Framework Endpoints
The `sync` function opens a transaction on the specified Orama Cloud index, inserts the flattened document records, and commits the transaction if `autoDeploy` is enabled.
```typescript
export async function sync(orama: OramaCloud, options: SyncOptions): Promise {
const { autoDeploy = true } = options;
const index = orama.index.set(options.index);
await index.transaction.open();
await index.transaction.insertDocuments(
options.documents.flatMap(toIndex) as unknown as AnyObject[],
);
if (autoDeploy) await index.transaction.commit();
}
```
Sources: [packages/core/src/search/orama-cloud.ts:89-99](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L89-L99)
Internationalized synchronization is handled by `syncI18n`, which maps document locales to corresponding index identifiers and executes concurrent synchronization tasks for each locale.
```typescript
export async function syncI18n(orama: OramaCloud, options: I18nSyncOptions): Promise {
const { autoDeploy = true, indexes } = options;
const tasks = options.documents.map(async (document) => {
const index = orama.index.set(indexes[document.locale]);
await index.transaction.open();
await index.transaction.insertDocuments(
document.items.flatMap(toIndex) as unknown as AnyObject[],
);
if (autoDeploy) await index.transaction.commit();
});
await Promise.all(tasks);
}
```
Sources: [packages/core/src/search/orama-cloud.ts:101-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L101-L116)
Framework routing plugins configure static JSON export endpoints across different application routers.
| Framework Target | Route Path | Implementation Handler |
| --- | --- | --- |
| Next.js App Router | `/static.json` | `Response.json(await exportSearchIndexes())` |
| React Router / SPA | `static.json` | `loader` returning `Response.json(await exportSearchIndexes())` |
| Tanstack Start | `/static.json` | Server file route with `GET` handler returning `Response.json(await exportSearchIndexes())` |
| Waku | `/static.json` | `GET` handler with static configuration |
Sources: [packages/create-app/src/plugins/orama-cloud.ts:37-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts#L37-L65), [packages/create-app/src/plugins/orama-cloud.ts:109-140](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts#L109-L140)
## Mixedbread vector and semantic indexing
### Semantic Chunk Transformation and Endpoint Configuration
The `createMixedbreadSearchAPI` factory constructs a search endpoint that queries Mixedbread vector stores using `@mixedbread/sdk` clients. Options allow configuring client instances, store identifiers, top-k limits, and semantic options like re-ranking and query rewriting.
```typescript
export interface MixedbreadSearchOptions {
/**
* The Mixedbread SDK client instance
*/
client: Mixedbread;
/**
* The identifier of the store to search in
*/
storeIdentifier: string;
/**
* Maximum number of results to return
*
* @defaultValue 10
*/
topK?: number;
/**
* Re-rank search results for improved relevance (this adds latency to the search)
*/
rerank?: boolean;
/**
* Rewrite the query for better search results (this adds latency to the search)
*/
rewriteQuery?: boolean;
/**
* Minimum score threshold for results
*/
scoreThreshold?: number;
/**
* Custom transform function for search results
*/
transform?: (results: StoreSearchResult[], query: string) => SortedResult[];
}
```
Sources: [packages/core/src/search/mixedbread.ts:20-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L20-L57)
```typescript
export function createMixedbreadSearchAPI(options: MixedbreadSearchOptions): SearchAPI {
const {
client,
storeIdentifier,
topK = 10,
rerank,
rewriteQuery,
scoreThreshold,
transform,
} = options;
```
Sources: [packages/core/src/search/mixedbread.ts:113-123](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L113-L123)
> [!CAUTION]
> Exporting search indexes is explicitly unsupported for Mixedbread endpoints; attempting to invoke `export()` throws an error instructing administrators to use the Mixedbread dashboard for store management.
Sources: [packages/core/src/search/mixedbread.ts:167-172](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L167-L172)
### Result Formatting and Filtering
The default transformation engine processes raw store search results by extracting document metadata such as URLs and titles, producing structured page and heading entries. Headings are cleaned using `remove-markdown` and converted into URL anchor links via `github-slugger`.
```typescript
function defaultTransform(results: StoreSearchResult[]): SortedResult[] {
return results.flatMap((item) => {
const metadata = item.generated_metadata;
const url = metadata.url || '#';
const title = metadata.title || 'Untitled';
const chunkResults: SortedResult[] = [
{
id: `${item.file_id}-${item.chunk_index}-page`,
type: 'page',
content: title,
url,
},
];
const headingTitle = item.type === 'text' && item.text ? extractHeadingTitle(item.text) : '';
if (headingTitle) {
slugger.reset();
chunkResults.push({
id: `${item.file_id}-${item.chunk_index}-heading`,
type: 'heading',
content: headingTitle,
url: `${url}#${slugger.slug(headingTitle)}`,
});
}
return chunkResults;
});
}
```
Sources: [packages/core/src/search/mixedbread.ts:80-111](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L80-L111)
Search requests support optional tag filters applied directly to generated metadata fields within store queries.
```typescript
const { tag, limit } = searchOptions;
let filters: StoreSearchParams['filters'] | undefined;
if (Array.isArray(tag) && tag.length > 0) {
filters = {
key: 'generated_metadata.tag',
operator: 'in',
value: tag,
};
} else if (typeof tag === 'string') {
filters = {
key: 'generated_metadata.tag',
operator: 'eq',
value: tag,
};
}
```
Sources: [packages/core/src/search/mixedbread.ts:130-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L130-L144)
## Related
- [Search Client Integrations](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-client-integrations)
---
## Technical docs: Search Client Integrations
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-client-integrations
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/search/client/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts)
- [packages/base-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx)
- [packages/radix-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-orama.tsx)
- [packages/base-ui/src/components/dialog/search-algolia.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-algolia.tsx)
- [packages/radix-ui/src/components/dialog/search-algolia.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-algolia.tsx)
- [packages/base-ui/src/components/dialog/search-default.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-default.tsx)
- [packages/radix-ui/src/components/dialog/search-default.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx)
- [packages/core/src/search/client/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud-legacy.ts)
- [packages/core/src/search/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts)
- [packages/core/src/search/orama/create-server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts)
- [packages/core/src/search/client/mixedbread.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts)
- [packages/core/src/search/mixedbread.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts)
- [packages/core/src/search/client/orama-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts)
- [packages/create-app/template/+orama-cloud/@app/components/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/components/search.tsx)
- [packages/base-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx)
- [packages/radix-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx)
- [packages/core/src/search/client/fetch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts)
- [packages/preview/src/components/ai/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/ai/search.tsx)
- [packages/core/src/search/client/flexsearch-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts)
- [packages/core/src/search/client/algolia.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts)
- [packages/create-app/src/plugins/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts)
- [packages/core/src/search/flexsearch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts)
- [packages/base-ui/src/contexts/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx)
- [packages/radix-ui/src/contexts/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/search.tsx)
- [packages/core/src/search/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server.ts)
- [packages/core/src/search/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud-legacy.ts)
- [packages/core/src/search/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts)
- [packages/core/src/search/orama/create-db.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts)
- [packages/core/src/search/orama/search/advanced.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/advanced.ts)
- [packages/core/src/search/orama/search/simple.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts)
## Overview
Search Client Integrations provide client-side query execution, state coordination, and UI bindings for documentation search across multiple search engines. They bridge the gap between user input inside search dialogs and backend or in-browser search indexes, handling debouncing, result caching, dependency tracking, and asynchronous client loading.
Sources: [packages/core/src/search/client.ts:78-197](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L78-L197)
## Search Client React Hook Architecture
### Hook API and State Structure
The `useDocsSearch` hook manages user search input, debounced query execution, error handling, loading states, and result caching across different search provider backends. It accepts `clientOptions` containing preset configurations or a direct `SearchClient` instance, alongside an optional `customDeps` dependency list.
```typescript
export function useDocsSearch(
clientOptions: ClientPreset & {
/**
* The debounced delay for performing a search (in ms).
* .
* @defaultValue 100
*/
delayMs?: number;
/**
* still perform search even if query is empty.
*
* @defaultValue false
*/
allowEmpty?: boolean;
},
customDeps?: DependencyList,
): UseDocsSearch {
```
Sources: [packages/core/src/search/client.ts:83-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L83-L100)
The return value conforms to the `UseDocsSearch` interface, exposing the raw input string, its setter, and a query status object holding loading flags, result arrays, or errors.
```typescript
interface UseDocsSearch {
search: string;
setSearch: (v: string) => void;
query: {
isLoading: boolean;
data?: SortedResult[] | 'empty';
error?: Error;
};
}
```
Sources: [packages/core/src/search/client.ts:14-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L14-L22)
### Client Preset Resolution and Deprecation
`ClientPreset` supports both legacy string-keyed configuration types and modern direct `SearchClient` references. When a legacy `type` string is provided, `useDocsSearch` dynamically imports the respective client module and constructs the search client asynchronously.
```typescript
export type ClientPreset =
| ({
/**
* @deprecated Pass `client: fetchClient(...)` instead.
*/
type: 'fetch';
} & FetchOptions)
| ({
/**
* @deprecated Pass `client: oramaStaticClient(...)` instead.
*/
type: 'static';
} & StaticOptions)
| ({
/**
* @deprecated Pass `client: algoliaClient(...)` instead.
*/
type: 'algolia';
} & AlgoliaOptions)
| ({
/**
* @deprecated Pass `client: oramaCloudClient(...)` instead.
*/
type: 'orama-cloud';
} & OramaCloudOptions)
| ({
/**
* @deprecated Pass `client: oramaCloudLegacyClient(...)` instead.
*/
type: 'orama-cloud-legacy';
} & OramaCloudLegacyOptions)
| ({
/**
* @deprecated Pass `client: flexsearchStaticClient(...)` instead.
*/
type: 'flexsearch-static';
} & FlexsearchStaticOptions)
| ({
/**
* @deprecated Use `createMixedbreadSearchAPI` from `fumadocs-core/search/mixedbread` instead.
* This client-side approach exposes your API key in the browser.
* The server-side approach keeps the key secure and uses `client: fetchClient(...)` on the client.
*/
type: 'mixedbread';
} & MixedbreadOptions)
| {
client: SearchClient;
};
```
Sources: [packages/core/src/search/client.ts:24-71](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L24-L71)
| Preset Type | Module Import Path | Options Interface |
| :--- | :--- | :--- |
| `fetch` | `@/search/client/fetch` | `FetchOptions` |
| `static` | `@/search/client/orama-static` | `StaticOptions` |
| `algolia` | `@/search/client/algolia` | `AlgoliaOptions` |
| `orama-cloud` | `@/search/client/orama-cloud` | `OramaCloudOptions` |
| `orama-cloud-legacy` | `@/search/client/orama-cloud-legacy` | `OramaCloudLegacyOptions` |
| `flexsearch-static` | `./client/flexsearch-static` | `FlexsearchStaticOptions` |
| `mixedbread` | `@/search/client/mixedbread` | `MixedbreadOptions` |
Sources: [packages/core/src/search/client.ts:110-143](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L110-L143)
> [!WARNING]
> Using string-keyed presets like `type: 'fetch'` is deprecated. Pass a pre-instantiated client such as `client: fetchClient(...)` directly to avoid runtime dynamic imports and ensure type-safe dependency tracking.
Sources: [packages/core/src/search/client.ts:24-71](https://github.com/blade47/fumadopos/blob/HEAD/packages/core/src/search/client.ts#L24-L71)
### Debouncing and Task Interruption
Search input is processed through `useDebounce` with a configurable `delayMs` defaulting to `100` milliseconds. Setting `allowEmpty` to `true` forces search execution even when the query string is empty.
```typescript
const { delayMs = 100, allowEmpty = false, ...clientRest } = clientOptions;
const [search, setSearch] = useState('');
const [results, setResults] = useState('empty');
const [error, setError] = useState();
const [isLoading, setIsLoading] = useState(false);
const debouncedValue = useDebounce(search, delayMs);
```
Sources: [packages/core/src/search/client.ts:101-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L101-L106)
Active search tasks are tracked via `activeTaskRef`. When dependencies or debounced values change before an in-flight search resolves, the previous task is immediately marked as interrupted, preventing stale responses from overwriting newer query results.
```typescript
const [activeDeps, setActiveDeps] = useState(null);
const activeTaskRef = useRef<{
deps: DependencyList;
start: () => void;
interrupt: boolean;
} | null>(null);
if (
!isEqualShallow(activeDeps, deps) &&
(!activeTaskRef.current || !isEqualShallow(activeTaskRef.current.deps, deps))
) {
if (activeTaskRef.current) activeTaskRef.current.interrupt = true;
activeTaskRef.current = {
deps,
interrupt: false,
async start() {
try {
setIsLoading(true);
let res: SortedResult[] | 'empty';
if (debouncedValue.length === 0 && !allowEmpty) res = 'empty';
else res = await (await client).search(debouncedValue);
if (!this.interrupt) {
setActiveDeps(deps);
setError(undefined);
setResults(res);
}
} catch (err) {
if (!this.interrupt) setError(err as Error);
} finally {
if (!this.interrupt) setIsLoading(false);
}
},
};
void activeTaskRef.current.start();
}
```
Sources: [packages/core/src/search/client.ts:154-191](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L154-L191)
> [!NOTE]
> If `allowEmpty` is `false` and the debounced query length is zero, the hook bypasses the search client call entirely and sets the result data directly to `'empty'`.
Sources: [packages/core/src/search/client.ts:174-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L174-L176)
### Query Caching via Fetch Client
The built-in `fetchClient` utilizes an internal `Map` cache (`globalCache` by default, or a custom map passed via `FetchOptions`) keyed by the fully constructed request URL string. Before executing a network request, it checks for a cached `SortedResult[]` entry.
```typescript
const globalCache = new Map();
export function fetchClient({
api = '/api/search',
locale,
tag,
cache = globalCache,
}: FetchOptions = {}): SearchClient {
return {
deps: [api, locale, tag],
async search(query) {
const url = new URL(api, window.location.origin);
url.searchParams.set('query', query);
if (locale) url.searchParams.set('locale', locale);
if (tag) url.searchParams.set('tag', Array.isArray(tag) ? tag.join(',') : tag);
const key = url.toString();
const cached = cache.get(key);
if (cached) return cached;
const res = await fetch(url);
if (!res.ok) throw new Error(await res.text());
const result = (await res.json()) as SortedResult[];
cache.set(key, result);
return result;
},
};
```
Sources: [packages/core/src/search/client/fetch.ts:25-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L25-L51)
## Default Route Querying via Fetch
### Fetch Client Configuration and Parameters
The `fetchClient` factory function constructs a client adhering to the `SearchClient` interface by querying an API endpoint over HTTP. It accepts `FetchOptions` to customize the network request behavior and parameter serialization.
| Option Key | Type | Default Value | Purpose |
| :--- | :--- | :--- | :--- |
| `api` | `string` | `'/api/search'` | API route for the search endpoint, supporting absolute URLs. |
| `tag` | `string \| string[]` | `undefined` | Filter results with one or more tags (comma-joined if an array). |
| `locale` | `string` | `undefined` | Filter search results by language locale. |
| `cache` | `Map` | `globalCache` | Storage map used for query caching across searches. |
Sources: [packages/core/src/search/client/fetch.ts:4-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L4-L23), [packages/core/src/search/client/fetch.ts:25-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L25-L32)
When `search(query)` is invoked, `fetchClient` builds a `URL` instance using `window.location.origin` as the base, appending query parameters for `query`, `locale`, and `tag`. If `tag` is provided as an array, its elements are joined with commas.
```typescript
async search(query) {
const url = new URL(api, window.location.origin);
url.searchParams.set('query', query);
if (locale) url.searchParams.set('locale', locale);
if (tag) url.searchParams.set('tag', Array.isArray(tag) ? tag.join(',') : tag);
```
Sources: [packages/core/src/search/client/fetch.ts:35-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L35-L40)
> [!WARNING]
> If the fetch response status is not OK (`!res.ok`), `fetchClient` reads the response body as text and throws it immediately as an `Error`.
Sources: [packages/core/src/search/client/fetch.ts:45-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L45-L46)
### Default Search Dialog Integration
The `DefaultSearchDialog` component integrates `fetchClient` with [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) and Radix primitives, wrapping `useDocsSearch` to power accessible search dialogs.
```tsx
export default function DefaultSearchDialog({
defaultTag,
tags = [],
api,
delayMs,
allowClear = false,
links = [],
footer,
...props
}: DefaultSearchDialogProps) {
const { locale } = useI18n();
const [tag, setTag] = useState(defaultTag);
const { search, setSearch, query } = useDocsSearch({
client: fetchClient({
api,
locale,
tag,
}),
delayMs,
});
```
Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:50-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L50-L69)
| Prop Name | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `links` | `SearchLink[]` | `[]` | Default fallback links displayed when no search query is active. |
| `defaultTag` | `string` | `undefined` | Initial active filter tag. |
| `tags` | `TagItem[]` | `[]` | Available filter tags rendered in the dialog footer. |
| `api` | `string` | `undefined` | Custom search API URL passed to `fetchClient`. |
| `delayMs` | `number` | `undefined` | Debounce delay for executing search requests. |
| `allowClear` | `boolean` | `false` | Allows users to clear active tag filters. |
| `footer` | `ReactNode` | `undefined` | Custom React node rendered alongside the tag list in the footer. |
Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:25-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L25-L48)
`DefaultSearchDialog` synchronizes the dialog's tag state with locale changes and passes the resulting query items to `SearchDialogList`. When the query data evaluates to `'empty'`, it falls back to rendering the memoized default `links` converted into `SortedResult` items.
```tsx
const defaultItems = useMemo(() => {
if (links.length === 0) return null;
return links.map(([name, link]) => ({
type: 'page',
id: name,
content: name,
url: link,
}));
}, [links]);
```
Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:70-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L70-L78)
```tsx
```
Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:93-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L93-L93)
> [!TIP]
> If `tags` array length is greater than zero, `DefaultSearchDialog` automatically renders a `TagsList` component inside `SearchDialogFooter` equipped with tag selection handlers and clear options.
Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:96-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L96-L104)
## Orama Cloud Client Adapters
### Query Pipeline and Index Modes
Fumadocs provides client adapters for both modern Orama Cloud (`@orama/core`) and legacy Orama clients (`@oramacloud/client`) via `oramaCloudClient` and `oramaCloudLegacyClient`. Each adapter constructs a `SearchClient` configured with dependencies and an asynchronous `search(query)` execution pipeline.
```typescript
export function oramaCloudClient(options: OramaCloudOptions): SearchClient {
const { index = 'default', client, params: extraParams, tag } = options;
return {
deps: [index, client, tag],
```
Sources: [packages/core/src/search/client/orama-cloud.ts:40-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L40-L44)
```typescript
export function oramaCloudLegacyClient(options: OramaCloudLegacyOptions): SearchClient {
const { index = 'default', client, params: extraParams = {}, tag } = options;
return {
deps: [index, client, tag],
```
Sources: [packages/core/src/search/client/orama-cloud-legacy.ts:40-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud-legacy.ts#L40-L44)
The client supports two indexing strategies: `default` (structured Fumadocs JSON indexes) and `crawler` (web crawler indexes). When `index` is set to `'crawler'`, search queries target the web crawler datasource, grouping results into page and text items.
```typescript
if (index === 'crawler') {
const result = await client.search({
datasources: [],
...extraParams,
term: query,
where: {
category: tag
? {
eq: tag.slice(0, 1).toUpperCase() + tag.slice(1),
}
: undefined,
...extraParams?.where,
},
limit: 10,
});
```
Sources: [packages/core/src/search/client/orama-cloud.ts:49-63](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L49-L63)
In `default` mode, queries invoke `client.search` with a maximum limit of 20 results, grouping matches by `page_id` with up to 7 results per group. The resulting grouped hits are mapped into `SortedResult` objects using `createContentHighlighter` to process markdown highlights.
```typescript
const result = await client.search({
datasources: [],
...extraParams,
term: query,
limit: 20,
where: removeUndefined({
tag,
...extraParams?.where,
}),
groupBy: {
properties: ['page_id'],
max_results: 7,
...extraParams?.groupBy,
},
});
```
Sources: [packages/core/src/search/client/orama-cloud.ts:88-102](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L88-L102)
> [!WARNING]
> In `oramaCloudClient`, if the total mapped result list exceeds 80 items, the client slices the array to a maximum length of 80 before returning.
Sources: [packages/core/src/search/client/orama-cloud.ts:131-131](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L131-L131)
### Orama Search Dialog Integration
The `OramaSearchDialog` component integrates Orama Cloud search into application dialogs using [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components), accepting client instances, parameters, and tag configurations.
```tsx
export default function OramaSearchDialog({
client,
searchOptions,
tags = [],
defaultTag,
showOrama = true,
allowClear = false,
index,
footer,
links = [],
...props
}: OramaSearchDialogProps) {
const { locale } = useI18n();
const [tag, setTag] = useState(defaultTag);
const { search, setSearch, query } = useDocsSearch({
client: oramaCloudClient({
client,
index,
params: searchOptions,
locale,
tag,
}),
});
```
Sources: [packages/base-ui/src/components/dialog/search-orama.tsx:54-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx#L54-L76)
| Prop Name | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `client` | `OramaCloudOptions['client']` | — | Orama Cloud client instance. |
| `searchOptions` | `OramaCloudOptions['params']` | `undefined` | Additional search parameters. |
| `index` | `OramaCloudOptions['index']` | `undefined` | Index type (`'default'` or `'crawler'`). |
| `tags` | `TagItem[]` | `[]` | List of filter tags for the dialog footer. |
| `defaultTag` | `string` | `undefined` | Initial active filter tag. |
| `showOrama` | `boolean` | `true` | Controls the visibility of the "Search powered by Orama" branding label. |
| `allowClear` | `boolean` | `false` | Allows users to clear active tag filters. |
| `links` | `SearchLink[]` | `[]` | Fallback links when no search query is active. |
Sources: [packages/base-ui/src/components/dialog/search-orama.tsx:25-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx#L25-L49)
## Static Orama and Flexsearch Engines
### Static Orama Client Implementation
Fumadocs provides client execution for in-browser static search indices through `oramaStaticClient`. The client accepts `StaticOptions` configuration parameters governing index fetching, schema initialization, tag filtering, and localized database management.
```typescript
export interface StaticOptions {
/**
* Where to download exported search indexes (URL)
*
* @defaultValue '/api/search'
*/
from?: string;
initOrama?: (locale?: string) => AnyOrama | Promise;
/**
* Filter results with specific tag(s).
*/
tag?: string | string[];
/**
* Filter by locale (unsupported at the moment)
*/
locale?: string;
/**
* extra options for search
*/
search?: Partial>>;
}
```
Sources: [packages/core/src/search/client/orama-static.ts:8-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L8-L32)
| Option Name | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `from` | `string` | `'/api/search'` | URL endpoint to download exported search indexes. |
| `initOrama` | `(locale?: string) => AnyOrama \| Promise` | `create({ schema: { _: 'string' }, language: locale })` | Custom Orama instance initializer per locale. |
| `tag` | `string \| string[]` | `undefined` | Filter results by specific tag(s). |
| `locale` | `string` | `undefined` | Filter by locale. |
| `search` | `Partial>>` | `undefined` | Extra parameters for search execution. |
Sources: [packages/core/src/search/client/orama-static.ts:8-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L8-L32)
Database loading is handled asynchronously via `loadDB`, which fetches exported index payloads and populates an in-memory database map cache keyed by locale. When internationalization data types are encountered, instances are built per locale entry, whereas single-index payloads initialize a default empty locale key.
```typescript
async function loadDB(
from: string,
initOrama: StaticOptions['initOrama'] = (locale) =>
create({ schema: { _: 'string' }, language: locale }),
): Promise {
const res = await fetch(from);
if (!res.ok)
throw new Error(
`failed to fetch exported search indexes from ${from}, make sure the search database is exported and available for client.`,
);
const data = (await res.json()) as ExportedData;
const dbs: Database = new Map();
if (data.type === 'i18n') {
await Promise.all(
Object.entries(data.data).map(async ([k, v]) => {
const db = await initOrama(k);
load(db, v);
dbs.set(k, {
type: v.type,
db,
});
}),
);
} else {
const db = await initOrama();
load(db, data);
dbs.set('', {
type: data.type,
db,
});
}
return dbs;
}
```
Sources: [packages/core/src/search/client/orama-static.ts:45-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L45-L82)
> [!WARNING]
> If a requested locale is missing from the loaded database collection, `oramaStaticClient` logs a warning message and falls back to the first available database value in the map.
Sources: [packages/core/src/search/client/orama-static.ts:104-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L104-L109)
Execution branches between simple and advanced search helpers depending on the database type property (`'simple'` or `'advanced'`). Simple searches delegate to `searchSimple` with tolerance and title boost configurations, while advanced searches use `searchAdvanced` with `groupBy` page ID properties and tag filters.
```typescript
export async function searchSimple(
db: Orama,
query: string,
params: Partial, SimpleDocument>> = {},
): Promise {
const highlighter = createContentHighlighter(query);
const result = await search(db, {
term: query,
tolerance: 1,
...params,
boost: {
title: 2,
...('boost' in params ? params.boost : undefined),
},
});
```
Sources: [packages/core/src/search/orama/search/simple.ts:5-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L19)
```typescript
export async function searchAdvanced(
db: Orama,
query: string,
tag: string | string[] = [],
{
mode = 'fulltext',
...override
}: Partial, AdvancedDocument>> = {},
): Promise {
if (typeof tag === 'string') tag = [tag];
const params = {
limit: 60,
mode,
...override,
where: removeUndefined({
tags:
tag.length > 0
? {
containsAll: tag,
}
: undefined,
...override.where,
}),
groupBy: {
properties: ['page_id'],
maxResult: 8,
...override.groupBy,
},
properties: mode === 'fulltext' ? ['content'] : ['content', 'embeddings'],
} as SearchParams;
```
Sources: [packages/core/src/search/orama/search/advanced.ts:6-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/advanced.ts#L6-L36)
### Static Flexsearch Client Implementation
Local in-browser client execution using Flexsearch is provided by `flexsearchStaticClient`. The client accepts `FlexsearchStaticOptions` to configure endpoint fetching, default locales, and tags.
```typescript
export interface FlexsearchStaticOptions {
/**
* @defaultValue `/api/search`
*/
from?: string;
locale?: string;
tag?: string | string[];
}
```
Sources: [packages/core/src/search/client/flexsearch-static.ts:6-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L6-L13)
| Option Name | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `from` | `string` | `'/api/search'` | URL endpoint to download exported Flexsearch indexes. |
| `locale` | `string` | `''` | Target locale key for querying. |
| `tag` | `string \| string[]` | `undefined` | Optional tag filter for search queries. |
Sources: [packages/core/src/search/client/flexsearch-static.ts:6-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L6-L13)
The initialization routine checks whether `window` is defined before executing the asynchronous fetch function `init`. It parses exported JSON payloads, iterating over internationalized raw records or standard document maps to instantiate Flexsearch document wrappers via `initDocument`.
```typescript
function initDocument(data: Record) {
const document = createDocument();
for (const [k, v] of Object.entries(data)) document.import(k, v);
return document;
}
```
Sources: [packages/core/src/search/client/flexsearch-static.ts:15-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L15-L19)
```typescript
async function init(from: string) {
const res = await fetch(from);
if (!res.ok)
throw new Error(
`failed to fetch exported search indexes from ${from}, make sure the search database is exported and available for client.`,
);
const data = (await res.json()) as ExportedData;
const dbs = new Map>();
if (data.type === 'i18n') {
for (const [locale, map] of Object.entries(data.raw)) {
dbs.set(locale, initDocument(map));
}
return dbs;
} else {
dbs.set('', initDocument(data.raw));
}
return dbs;
```
Sources: [packages/core/src/search/client/flexsearch-static.ts:43-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L43-L64)
> [!NOTE]
> `flexsearchStaticClient` registers dependency tracking for `from`, `locale`, and `tag`, returning an empty array if the requested locale database has not been loaded into the map cache.
Sources: [packages/core/src/search/client/flexsearch-static.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L33-L39)
## Algolia Search Client and Grouping
### Algolia Lite Client Adapter
The Algolia client implementation provides search integration via `algoliaClient`, accepting `AlgoliaOptions` to configure the target index, search client instance, tag filters, locale, and an optional custom `onSearch` handler function.
```typescript
export interface AlgoliaOptions {
indexName: string;
client: LiteClient;
/**
* Filter results with specific tag.
*/
tag?: string;
locale?: string;
onSearch?: (
query: string,
tag?: string,
locale?: string,
) => Promise<{
results: SearchResponse[];
}>;
}
```
Sources: [packages/core/src/search/client/algolia.ts:6-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:6-24)
| Option Name | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `indexName` | `string` | *required* | Target Algolia index name. |
| `client` | `LiteClient` | *required* | Algolia lite client instance. |
| `tag` | `string` | `undefined` | Optional tag filter string (`tag:${tag}`). |
| `locale` | `string` | `undefined` | Optional locale identifier passed to custom search handlers. |
| `onSearch` | `Function` | `undefined` | Custom search function overriding default requests. |
Sources: [packages/core/src/search/client/algolia.ts:6-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:6-24)
> [!WARNING]
> If the search query string contains only whitespace or is empty after trimming (`query.trim().length === 0`), `algoliaClient` immediately returns an empty array without executing a network request.
Sources: [packages/core/src/search/client/algolia.ts:58-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:58-59)
### Hierarchical Hit Grouping and Execution Flow
When executing a search request, `algoliaClient` checks whether a custom `onSearch` function is provided; otherwise, it invokes `client.searchForHits` with a request configuration containing a distinct value of `5`, `hitsPerPage` set to `10`, and an optional tag filter. The resulting hits are processed by `groupResults` to construct a hierarchical list of pages, headings, and text blocks.
```typescript
const result = onSearch
? await onSearch(query, tag, locale)
: await client.searchForHits({
requests: [
{
type: 'default',
indexName,
query,
distinct: 5,
hitsPerPage: 10,
filters: tag ? `tag:${tag}` : undefined,
},
],
});
```
Sources: [packages/core/src/search/client/algolia.ts:61-75](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:61-75)
```mermaid
sequenceDiagram
participant AlgoliaSearchDialog as AlgoliaSearchDialog
participant algoliaClient as algoliaClient
participant groupResults as groupResults
AlgoliaSearchDialog->>algoliaClient: search(query)
algoliaClient->>groupResults: groupResults(hits)
groupResults-->>algoliaClient: SortedResult[]
algoliaClient-->>AlgoliaSearchDialog: highlighted results
```
Sources: [packages/base-ui/src/components/dialog/search-algolia.tsx:61-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-algolia.tsx#L61-L67), [packages/core/src/search/client/algolia.ts:26-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts#L26-L52), [packages/core/src/search/client/algolia.ts:58-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts#L58-L87)
The grouping function `groupResults` tracks scanned URLs in a `Set`. For each unique URL encountered, it pushes a parent page result into the accumulator array before appending individual section or text hits with constructed anchor URLs.
```typescript
function groupResults(hits: Hit[]): SortedResult[] {
const grouped: SortedResult[] = [];
const scannedUrls = new Set();
for (const hit of hits) {
if (!scannedUrls.has(hit.url)) {
scannedUrls.add(hit.url);
grouped.push({
id: hit.url,
type: 'page',
breadcrumbs: hit.breadcrumbs,
url: hit.url,
content: hit.title,
});
}
grouped.push({
id: hit.objectID,
type: hit.content === hit.section ? 'heading' : 'text',
url: hit.section_id ? `${hit.url}#${hit.section_id}` : hit.url,
content: hit.content,
});
}
return grouped;
}
```
Sources: [packages/core/src/search/client/algolia.ts:26-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:26-52)
## Mixedbread Client Vector Retrieval
### Mixedbread Options and Heading Transformations
The Mixedbread client integration supports vector search queries against a remote store via `mixedbreadClient` or server-side endpoints through `createMixedbreadSearchAPI`. `MixedbreadOptions` defines the configuration required to connect to a store instance using the Mixedbread SDK client.
```typescript
export interface MixedbreadOptions {
/**
* The identifier of the store to search in
*/
storeIdentifier: string;
/**
* The Mixedbread SDK client instance
*/
client: Mixedbread;
/**
* Filter results with specific tag.
*/
tag?: string;
/**
* Filter by locale (unsupported at the moment)
*/
locale?: string;
}
```
Sources: [packages/core/src/search/client/mixedbread.ts:8-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:8-28)
| Option Name | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `storeIdentifier` | `string` | *required* | The identifier of the store to search in. |
| `client` | `Mixedbread` | *required* | The Mixedbread SDK client instance. |
| `tag` | `string` | `undefined` | Filter results with a specific tag. |
| `locale` | `string` | `undefined` | Filter by locale (unsupported at the moment). |
Sources: [packages/core/src/search/client/mixedbread.ts:8-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:8-28)
> [!WARNING]
> `mixedbreadClient` is deprecated because running client-side SDK queries exposes your API key in the browser. The recommended approach is to use `createMixedbreadSearchAPI` on the server and connect with a fetch client on the client.
Sources: [packages/core/src/search/client/mixedbread.ts:63-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:63-67)
### Search Execution and Chunk Processing
When a search query is submitted, `mixedbreadClient` queries `client.stores.search` requesting a top-k limit of 10 items with metadata enabled and tag filtering applied via `generated_metadata.tag`. Each returned search result chunk is expanded into structured page and heading results.
```typescript
async search(query) {
if (!query.trim()) {
return [];
}
const res = await client.stores.search({
query,
store_identifiers: [storeIdentifier],
top_k: 10,
filters: {
key: 'generated_metadata.tag',
operator: 'eq',
value: tag,
},
search_options: {
return_metadata: true,
},
});
```
Sources: [packages/core/src/search/client/mixedbread.ts:73-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:73-90)
```typescript
return (res.data as StoreSearchResult[]).flatMap((item) => {
const metadata = item.generated_metadata;
const url = metadata.url || '#';
const title = metadata.title || 'Untitled';
const chunkResults: SortedResult[] = [
{
id: `${item.file_id}-${item.chunk_index}-page`,
type: 'page',
content: title,
url,
},
];
const headingTitle =
item.type === 'text' && item.text ? extractHeadingTitle(item.text) : '';
if (headingTitle) {
slugger.reset();
chunkResults.push({
id: `${item.file_id}-${item.chunk_index}-heading`,
type: 'heading',
content: headingTitle,
url: `${url}#${slugger.slug(headingTitle)}`,
});
}
return chunkResults;
});
```
Sources: [packages/core/src/search/client/mixedbread.ts:92-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:92-122)
The helper function `extractHeadingTitle` inspects text content to verify whether it starts with a markdown heading indicator (`#`). If it does, the first line is split, cleaned with `removeMarkdown` with image alt text disabled, and slugified using `github-slugger` for anchor URL generation.
```typescript
function extractHeadingTitle(text: string): string {
const trimmedText = text.trim();
if (!trimmedText.startsWith('#')) {
return '';
}
const lines = trimmedText.split('\n');
const firstLine = lines[0]?.trim();
if (firstLine) {
// Use remove-markdown to convert to plain text and remove colons
return removeMd(firstLine, {
useImgAltText: false,
});
}
return '';
}
```
Sources: [packages/core/src/search/client/mixedbread.ts:43-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:43-61)
> [!NOTE]
> `slugger.reset()` is invoked before processing each heading title to ensure deterministic slug generation across chunk result iterations.
Sources: [packages/core/src/search/client/mixedbread.ts:111-111](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:111-111)
## Search Context and Keyboard Shortcuts
### Global Search Context and Provider Architecture
The `SearchProvider` component establishes global search state using `SearchContext`, exposing options for dialog preloading, custom empty-state links, and hotkey bindings. When `preload` is enabled (defaulting to `true`), the search dialog state is initialized to `undefined` until the dialog is opened, triggering lazy loading of `DefaultSearchDialog`.
```tsx
export function SearchProvider({
SearchDialog = DefaultSearchDialog,
children,
preload = true,
options,
hotKey = DEFAULT_HOT_KEYS,
links,
}: SearchProviderProps) {
const [isOpen, setIsOpen] = useState(preload ? false : undefined);
const onKeyDown = useEffectEvent((e: KeyboardEvent) => {
if (hotKey.every((v) => (typeof v.key === 'string' ? e.key === v.key : v.key(e)))) {
setIsOpen((open) => !open);
e.preventDefault();
}
});
useEffect(() => {
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('keydown', onKeyDown);
};
}, []);
return (
({
enabled: true,
open: isOpen ?? false,
hotKey,
setOpenSearch: setIsOpen,
}),
[isOpen, hotKey],
)}
>
{isOpen !== undefined && (
)}
{children}
);
}
```
Sources: [packages/base-ui/src/contexts/search.tsx:112-162](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L112-L162)
| Property | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `preload` | `boolean` | `true` | Preload search dialog before opening it. |
| `links` | `SearchLink[]` | `undefined` | Custom links to be displayed if search is empty. |
| `hotKey` | `HotKey[]` | `DEFAULT_HOT_KEYS` | Hotkeys for triggering the search dialog. |
| `SearchDialog` | `ComponentType` | `DefaultSearchDialog` | Replace default search dialog (e.g. Algolia Search). |
| `options` | `Partial>` | `undefined` | Additional properties passed to the dialog. |
Sources: [packages/base-ui/src/contexts/search.tsx:36-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L36-L69)
> [!NOTE]
> The `SearchOnly` wrapper component inspects `search.enabled` from the context and renders its children only when search has been successfully initialized via a provider.
Sources: [packages/base-ui/src/contexts/search.tsx:164-171](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L164-L171)
### Hotkey Bindings and Platform Detection
Keyboard shortcuts are managed via global window event listeners registered inside `SearchProvider`. The default hotkey configuration `DEFAULT_HOT_KEYS` combines a modifier key condition with the `k` key.
```tsx
const DEFAULT_HOT_KEYS: HotKey[] = [
{
key: (e) => e.metaKey || e.ctrlKey,
display: ,
},
{
key: 'k',
display: 'K',
},
];
```
Sources: [packages/base-ui/src/contexts/search.tsx:99-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L99-L108)
The `MetaOrControl` helper component checks `window.navigator.userAgent` against a regular expression testing for Windows or Linux platforms to dynamically switch the displayed shortcut symbol between `⌘` and `Ctrl`.
```tsx
function MetaOrControl() {
const [key, setKey] = useState('⌘');
useEffect(() => {
if (/Windows|Linux/i.test(window.navigator.userAgent)) setKey('Ctrl');
}, []);
return key;
}
```
Sources: [packages/base-ui/src/contexts/search.tsx:89-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L89-L97)
> [!WARNING]
> `onKeyDown` evaluates every configured hotkey item in `hotKey` using `.every()`. If `v.key` is a function, it receives the native `KeyboardEvent`; otherwise, it matches `e.key === v.key`. When all match, `setIsOpen` toggles the dialog state and `e.preventDefault()` is invoked.
Sources: [packages/base-ui/src/contexts/search.tsx:121-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L121-L126)
### AI Search Context and Preview Trigger Integration
The `AISearch` component provides a separate React context specifically for AI chat search integration, wrapping state for `open`, `setOpen`, and `chat` helpers initialized via `@ai-sdk/react`.
```tsx
export function AISearch({ children }: { children: ReactNode }) {
const [open, setOpen] = useState(false);
const chat = useChat({
id: 'search',
transport: new DefaultChatTransport({
api: '/api/chat',
}),
});
return (
({ chat, open, setOpen }), [chat, open])}>{children}
);
}
```
Sources: [packages/preview/src/components/ai/search.tsx:292-304](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/ai/search.tsx#L292-L304)
Trigger components such as `AISearchTrigger` consume this context to toggle visibility and update `data-state` attributes (`open` or `closed`). When `position` is set to `float`, the trigger button fixes its layout at the bottom corner with transition animations.
```tsx
export function AISearchTrigger({
position = 'default',
className,
...props
}: ComponentProps<'button'> & { position?: 'default' | 'float' }) {
const { open, setOpen } = useAISearchContext();
return (
);
}
```
Sources: [packages/preview/src/components/ai/search.tsx:306-329](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/ai/search.tsx#L306-L329)
## Related
- [Search Server Indexing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing)
- [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components)
---
## Technical docs: Syntax Highlighting
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/mdx-plugins/rehype-code/shiki.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts)
- [packages/core/src/highlight/shiki/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts)
- [packages/core/src/mdx-plugins/rehype-code.core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.core.ts)
- [packages/twoslash/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/src/index.ts)
- [packages/core/src/mdx-plugins/transformer-icon.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts)
- [packages/base-ui/css/lib/shiki.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css)
- [packages/radix-ui/css/lib/shiki.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css)
- [packages/core/src/highlight/shiki/full.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/full.ts)
- [packages/core/src/mdx-plugins/remark-code-tab.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts)
- [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts)
- [packages/core/src/mdx-plugins/rehype-code.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.ts)
- [packages/shadcn/src/manual-installation.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts)
- [packages/typescript/src/lib/remark-auto-type-table.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/lib/remark-auto-type-table.ts)
- [packages/core/src/highlight/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts)
- [packages/core/src/highlight/shiki/react.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts)
- [packages/base-ui/src/components/codeblock.rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx)
- [packages/core/src/mdx-plugins/rehype-code/parsers.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts)
- [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts)
- [packages/core/src/mdx-plugins/codeblock-utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts)
- [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts)
- [packages/radix-ui/src/components/dynamic-codeblock.core.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx)
- [packages/typescript/src/markdown.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/markdown.ts)
- [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts)
- [packages/core/src/highlight/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/client.ts)
- [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts)
- [packages/preview/src/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/markdown.tsx)
- [packages/base-ui/src/components/dynamic-codeblock.core.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx)
- [packages/radix-ui/src/components/codeblock.rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx)
- [packages/core/src/mdx-plugins/remark-mdx-files.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts)
- [packages/core/src/mdx-plugins/stringifier.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/stringifier.ts)
## Overview
Syntax Highlighting provides robust code block and inline syntax highlighting in Fumadocs by integrating Shiki into unified and remark-rehype processing pipelines. It intercepts code and pre elements during AST traversal, parses meta string attributes such as line numbers and titles, applies transformers for diffing, focusing, and file icons, and supports asynchronous client-side highlighting via React hooks and runtime state management. Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:116-222](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L116-L222), [packages/core/src/mdx-plugins/rehype-code.core.ts:19-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.core.ts#L19-L46), [packages/core/src/highlight/shiki/react.ts:27-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L27-L59)
## Unified Rehype Shiki Pipeline
### Rehype AST Visitor and Element Interception
The processor traverses the HAST tree using `unist-util-visit` to locate specific elements targeted for syntax highlighting. When the visitor encounters an element node matching `pre` or an inline `code` element where inline parsing is enabled, it delegates parsing to specialized parsers such as `PreParser` or `InlineCodeParsers`. Each candidate node must possess a valid parent and index to permit safe HAST node replacement.
```typescript
return async (tree) => {
const queue: Promise[] = [];
visit(tree, 'element', (node, index, parent) => {
let parsed: ShikiParsedData | undefined;
// needed for hast node replacement
if (!parent || index == null) return;
if (node.tagName === 'pre') {
parsed = PreParser(tree, node);
} else if (node.tagName === 'code' && inline) {
parsed = InlineCodeParsers[inline](tree, node);
```
Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:210-222](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L210-L222)
> [!WARNING]
> Nodes lacking a parent or index in the HAST tree are silently skipped during the AST traversal visitor callback. This safeguard prevents runtime reference errors when mutating the syntax tree structure.
Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:216-217](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L216-L217)
### Highlighter Core Delegation and Caching
Once a code element or pre block is intercepted, `onNode` extracts its metadata string, language identifier, and raw code content. If the designated language is not currently loaded in the core highlighter instance and lazy loading is active, it attempts to load the grammar dynamically from bundled languages or apply a fallback language.
Before invoking the high-cost highlighter engine, the pipeline constructs a cache key incorporating the language, filtered meta string, and raw code. If a matching entry exists in the custom cache map, the cached HAST fragment is returned directly. Otherwise, transformers configured with post-enforcement extract asynchronous post-processing tasks, option mappings are assembled, trailing newlines are stripped when enabled, and `highlighter.codeToHast` is executed.
```typescript
async function onNode(
tree: Root,
node: Element,
parsed: ShikiParsedData,
): Promise {
let { meta: metaString = '', lang = defaultLanguage, code } = parsed;
if (!lang) return;
if (!isLanguageLoaded(lang)) {
if (lazy && lang in highlighter.getBundledLanguages()) {
await highlighter.loadLanguage(lang as never);
} else if (fallbackLanguage) {
lang = fallbackLanguage;
if (!isLanguageLoaded(fallbackLanguage))
await highlighter.loadLanguage(fallbackLanguage as never);
}
}
if (filterMetaString) {
metaString = filterMetaString(metaString);
}
const cacheKey = `${lang}:${metaString}:${code}`;
const cachedValue = cache?.get(cacheKey);
if (cachedValue) {
return cachedValue;
}
const transformers = rest.transformers ? [...rest.transformers] : [];
let _fd_postprocess: ShikiTransformerContextMeta['_fd_postprocess'];
transformers.push({
enforce: 'post',
root() {
_fd_postprocess = this.meta._fd_postprocess;
},
});
if (addLanguageClass) transformers.push(transformerAddLanguage(lang));
const codeOptions: CodeToHastOptions = {
...rest,
lang,
structure: parsed.structure,
transformers,
meta: {
...rest.meta,
__raw: metaString,
...parseMetaString?.(metaString, node, tree),
},
};
if (stripEndNewline && code.endsWith('\n')) code = code.slice(0, -1);
const fragment = highlighter.codeToHast(code, codeOptions);
if (_fd_postprocess && _fd_postprocess.length > 0) {
const ctx = { highlighter };
await Promise.all(_fd_postprocess.map((v) => v(ctx)));
}
cache?.set(cacheKey, fragment);
if (parsed.structure === 'classic') return fragment;
return {
type: 'element',
tagName: 'code',
properties: {
class: 'shiki',
},
children: fragment.children as ElementContent[],
};
}
```
Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:138-208](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L138-L208)
> [!NOTE]
> When `stripEndNewline` is set to `true`, trailing newline characters added by `mdast-util-to-hast` are automatically removed from the source string prior to passing it into Shiki's highlighter engine.
Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:54-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L54-L61), [packages/core/src/mdx-plugins/rehype-code/shiki.ts:189-189](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L189-L189)
### Extra Configuration Options Reference
The `RehypeShikiExtraOptions` interface governs behavior flags for language resolution, meta parsing, caching, and error handling during pipeline execution.
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `addLanguageClass` | `boolean` | `false` | Add `language-*` class to code element. |
| `defaultLanguage` | `string` | `undefined` | The default language to use when not specified. |
| `fallbackLanguage` | `string` | `undefined` | The fallback language to use when specified language is not loaded or bundled. |
| `lazy` | `boolean` | `true` | Load languages and themes on-demand. |
| `stripEndNewline` | `boolean` | `true` | Strip trailing newline added by `mdast-util-to-hast`. |
| `parseMetaString` | `Function` | `undefined` | Custom meta string parser returning an object to merge with `meta`. |
| `filterMetaString` | `Function` | `undefined` | Filter meta string before processing. |
| `inline` | `InlineCodeParser \| false` | `false` | Highlight inline code blocks (e.g., `tailing-curly-colon`). |
| `cache` | `MapLike` | `undefined` | Custom map to cache transformed `codeToHast` results. |
| `onError` | `Function` | `undefined` | Error handler callback; throws if not provided. |
Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:28-101](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L28-L101)
## Theme Resolution and Highlighting Engine
### Highlighter Factory Lifecycle
The management and initialization of Shiki instances are coordinated through the `ShikiFactory` interface and `createShikiFactory` builder function. The factory pattern holds a cached instance or awaits initialization when `getOrInit` is called, ensuring that highlighter instances are instantiated on demand without redundant creation overhead. Two predefined factories are supplied: `defaultShikiFactory`, which provisions a standard highlighter instance utilizing the JavaScript regular expression engine, and `wasmShikiFactory`, which initializes a highlighter powered by the Oniguruma WebAssembly regex engine via `createOnigurumaEngine(import('shiki/wasm'))`. Both factories initialize with empty language and theme arrays, letting callers register grammars dynamically.
```typescript
/**
* A factory for Fumadocs to manage Shiki instances.
*/
export interface ShikiFactory {
init: (options?: InitOptions) => Awaitable;
getOrInit: () => Awaitable;
}
export function createShikiFactory(config: Pick): ShikiFactory {
let instance: Awaitable | undefined;
return {
init(options) {
return (instance = config.init(options));
},
getOrInit() {
return instance ?? this.init();
},
};
}
```
Sources: [packages/core/src/highlight/shiki/index.ts:17-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L17-L36)
```typescript
export const defaultShikiFactory = createShikiFactory({
async init(options) {
const { createHighlighter, createJavaScriptRegexEngine } = await import('shiki');
return createHighlighter({
langs: [],
themes: [],
langAlias: options?.langAlias,
engine: createJavaScriptRegexEngine(),
});
},
});
/** factory using the WASM powered Regex engine */
export const wasmShikiFactory = createShikiFactory({
async init(options) {
const { createHighlighter, createOnigurumaEngine } = await import('shiki');
return createHighlighter({
langs: [],
themes: [],
langAlias: options?.langAlias,
engine: createOnigurumaEngine(import('shiki/wasm')),
});
},
```
Sources: [packages/core/src/highlight/shiki/full.ts:3-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/full.ts#L3-L27)
> [!NOTE]
> The `getOrInit` method returns the cached highlighter instance if available, falling back to invoking `init()` if the internal instance variable is undefined.
Sources: [packages/core/src/highlight/shiki/index.ts:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L32-L34)
### Theme and Language Loading
Theme resolution and grammar loading inspect incoming options against the active highlighter core. The high-level `highlight` and `highlightHast` functions accept `HighlightHastOptions`, which allow selecting the regex engine via the `engine` property (`'js'` or `'oniguruma'`).
1. `ServerCodeBlock` invokes `highlight` with the code string and options.
2. `highlight` retrieves or initializes the appropriate highlighter core via `factory.getOrInit()`.
3. `highlightHast` (base implementation) resolves the target language, checking special language status and verifying if it is present in bundled or loaded languages; if missing, it falls back to `fallbackLanguage` (defaulting to `'text'`).
4. `highlightHast` resolves missing themes using `loadMissingTheme` and loads the required language asynchronously using `highlighter.loadLanguage()`, before invoking `highlighter.codeToHast` to produce the HAST root tree.
```typescript
export async function highlightHast(
highlighter: HighlighterCore,
code: string,
options: HighlightHastOptions,
): Promise {
const { fallbackLanguage = 'text', ...resolved } = options;
const { isSpecialLang } = await import('shiki/core');
if (
!isSpecialLang(resolved.lang) &&
!(resolved.lang in highlighter.getBundledLanguages()) &&
!highlighter.getLoadedLanguages().includes(resolved.lang)
) {
resolved.lang = fallbackLanguage;
}
await Promise.all([
loadMissingTheme(highlighter, getRequiredThemes(resolved)),
highlighter.loadLanguage(resolved.lang as never),
]);
return highlighter.codeToHast(code, resolved);
```
Sources: [packages/core/src/highlight/shiki/index.ts:44-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L44-L64)
```typescript
export async function highlightHast(code: string, options: HighlightHastOptions): Promise {
const engine = options.engine ?? 'js';
const factory = engine === 'js' ? defaultShikiFactory : wasmShikiFactory;
const instance = await factory.getOrInit();
return highlightHastBase(instance, code, applyDefaultThemes(options));
}
```
Sources: [packages/core/src/highlight/index.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts#L33-L39)
```mermaid
sequenceDiagram
participant ServerCodeBlock as packages/radix-ui/src/components/codeblock.rsc.tsx
participant highlight as packages/core/src/highlight/index.ts
participant highlightHastBase as packages/core/src/highlight/shiki/index.ts
ServerCodeBlock->>highlight: highlight(code, options)
highlight->>highlightHastBase: highlightHast(instance, code, options)
highlightHastBase->>highlightHastBase: highlightHast(highlighter, code, options)
```
Sources: [packages/radix-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L16-L32), [packages/core/src/highlight/index.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts#L33-L39), [packages/core/src/highlight/shiki/index.ts:44-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L44-L64)
> [!CAUTION]
> If a requested language is neither a special language, present in bundled languages, nor loaded in the highlighter instance, it is silently overridden with the `fallbackLanguage`.
Sources: [packages/core/src/highlight/shiki/index.ts:51-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L51-L57)
### AST Formatting and React Node Rendering
Once `codeToHast` returns the HAST `Root` node, `highlight` transforms the syntax tree into React nodes using `toJsxRuntime`. The formatting pipeline integrates the JSX runtime elements with custom component overrides supplied via `options.components`, which map pre elements to specialized wrapper components such as `ServerCodeBlock`.
```typescript
export async function highlight(code: string, options: HighlightOptions): Promise {
return toJsxRuntime(await highlightHast(code, options), {
...JsxRuntime,
development: false,
components: options.components,
});
```
Sources: [packages/core/src/highlight/index.ts:64-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts#L64-L69)
```tsx
export async function ServerCodeBlock({ code, codeblock, ...options }: ServerCodeBlockProps) {
return await highlight(code, {
defaultColor: false,
...options,
components: {
pre: (props) => (
{props.children}
),
...options.components,
},
});
```
Sources: [packages/radix-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L16-L32)
## Code Block Attribute Parsing
### Pre Block Metadata and Inline Code Parsing
The parsing pipeline inspects HAST nodes to extract code block metadata, language tags, and raw content from both classic fenced code blocks and inline code expressions. The `PreParser` function examines the first child element of a pre node, verifying that its tag name is `code` and that it possesses valid properties. It searches `head.properties.className` for any class string starting with `language-`, slicing off the prefix to determine the language identifier. Concurrently, it extracts metadata by checking `head.data?.meta` or falling back to `head.properties.metastring` as a string, defaulting to an empty string if neither exists.
```typescript
export const PreParser: ShikiParser = (_tree, node) => {
const head = node.children[0];
if (!head || head.type !== 'element' || head.tagName !== 'code' || !head.properties) {
return;
}
const classes = head.properties.className;
const languageClass = Array.isArray(classes)
? classes.find((d) => typeof d === 'string' && d.startsWith(languagePrefix))
: undefined;
return {
structure: 'classic',
lang:
typeof languageClass === 'string' ? languageClass.slice(languagePrefix.length) : undefined,
code: flattenNodeHast(head),
meta: head.data?.meta ?? head.properties.metastring?.toString() ?? '',
};
```
Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:33-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L33-L51)
For inline code elements, the `InlineCodeParsers` record provides the `'tailing-curly-colon'` parser. This parser flattens the HAST node into a raw string and matches it against the regular expression `RE_TAILING_CURLY_COLON` (`/(+)\{:([\w-]+)\}$/`). When a match occurs, it yields an inline structure type, extracts the code content from the first capture group, and retrieves the language identifier from the second capture group using `match.at(2)`.
```typescript
const RE_TAILING_CURLY_COLON = /(.+)\{:([\w-]+)\}$/;
export interface ShikiParsedData {
meta?: string;
lang?: string;
code: string;
structure: 'inline' | 'classic';
}
export type ShikiParser = (tree: Root, node: Element) => ShikiParsedData | undefined;
export type InlineCodeParser = 'tailing-curly-colon';
export const InlineCodeParsers: Record = {
'tailing-curly-colon': (_tree, node) => {
const raw = flattenNodeHast(node);
const match = raw.match(RE_TAILING_CURLY_COLON);
if (!match) return;
return {
structure: 'inline',
code: match[1] ?? raw,
lang: match.at(2),
};
},
};
```
Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:4-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L4-L29)
> [!WARNING]
> If a pre element contains no children, or if its first child is not a code element, `PreParser` returns undefined without extracting any language or metadata.
Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:33-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L33-L38)
### Meta String Attribute Extraction
Fumadocs-style attributes embedded within code block meta strings—such as `title="hello world"`—are parsed via `parseCodeBlockAttributes`. This utility uses `AttributeRegex` (`/(?<=^|\s)(?[a-zA-Z0-9_-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g`) to scan the meta string. It extracts attribute names alongside double-quoted or single-quoted string values, storing them in an attributes dictionary while stripping matched attributes from the remaining string output (`rest`). If `allowedNames` are specified, any attribute whose name is absent from the allowed list is ignored and left in the rest string.
```typescript
export interface CodeBlockAttributes {
attributes: Partial>;
rest: string;
}
const AttributeRegex = /(?<=^|\s)(?[a-zA-Z0-9_-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g;
/**
* Parse Fumadocs-style code block attributes from meta string, like `title="hello world"`
*/
export function parseCodeBlockAttributes(
meta: string,
allowedNames?: Name[],
): CodeBlockAttributes {
const attributes: CodeBlockAttributes['attributes'] = {};
const rest = meta.replaceAll(AttributeRegex, (match, name, value_1, value_2) => {
if (allowedNames && !allowedNames.includes(name)) return match;
attributes[name] = value_1 ?? value_2 ?? null;
return '';
});
return {
rest,
attributes,
};
}
```
Sources: [packages/core/src/mdx-plugins/codeblock-utils.ts:89-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts#L89-L115)
| Function / Parser | Target Input | Return Structure | Key Behavior |
| :--- | :--- | :--- | :--- |
| `PreParser` | HAST `Element` (`pre`) | `ShikiParsedData` (`classic`) | Scans child code element classes for `language-` prefix and extracts `metastring` or `meta` data. |
| `InlineCodeParsers['tailing-curly-colon']` | HAST `Element` (`code`) | `ShikiParsedData` (`inline`) | Matches trailing `{:lang}` syntax to separate code content from inline language specifiers. |
| `parseCodeBlockAttributes` | Meta string (`string`) | `CodeBlockAttributes` | Parses key-value attributes via regex, optionally filtering against `allowedNames`, and returns unparsed remainder (`rest`). |
Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:6-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L6-L51), [packages/core/src/mdx-plugins/codeblock-utils.ts:89-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts#L89-L115)
## AST Transformers and Tab Grouping
### File Icon Mapping and Shortcut Resolution
Shiki code block decoration relies on language identifier translation and icon extraction. The transformer maps shorthand language aliases to normalized identifiers using `defaultShortcuts`. For example, `js` maps to `javascript`, `jsx` and `tsx` map to `react`, `ts` maps to `typescript`, `c#` and `cs` map to `csharp`, `gql` maps to `graphql`, `py` maps to `python`, and `bash`, `sh`, `shell`, and `zsh` all map to `shellscript`. C++ maps to `cpp`.
```typescript
const defaultShortcuts: Record = {
js: 'javascript',
jsx: 'react',
ts: 'typescript',
tsx: 'react',
'c#': 'csharp',
cs: 'csharp',
gql: 'graphql',
py: 'python',
bash: 'shellscript',
sh: 'shellscript',
shell: 'shellscript',
zsh: 'shellscript',
'c++': 'cpp',
};
```
Sources: [packages/core/src/mdx-plugins/transformer-icon.ts:11-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts#L11-L25)
The `CodeBlockIcon` type permits either an SVG path configuration object containing `viewBox`, `fill`, and `d` properties or a raw string identifier. Default icons sourced from Simple Icons are defined for languages including `react`, `shellscript`, `c`, `graphql`, `python`, `md`, `kotlin`, and `rust`.
```typescript
export type CodeBlockIcon =
| {
viewBox: string;
fill: string;
d: string;
}
| string;
const defaultShortcuts: Record = {
js: 'javascript',
jsx: 'react',
ts: 'typescript',
tsx: 'react',
'c#': 'csharp',
cs: 'csharp',
gql: 'graphql',
py: 'python',
bash: 'shellscript',
sh: 'shellscript',
shell: 'shellscript',
zsh: 'shellscript',
'c++': 'cpp',
};
// From https://simpleicons.org
// Java - Not supported, https://github.com/simple-icons/simple-icons/issues/7374
const defaultIcons: Record = {
react: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M14.23 12.004a2.236 2.236 0 0 1-2.235 2.236 2.236 2.236 0 0 1-2.236-2.236 2.236 2.236 0 0 1 2.235-2.236 2.236 2.236 0 0 1 2.236 2.236zm2.648-10.69c-1.346 0-3.107.96-4.888 2.622-1.78-1.653-3.542-2.602-4.887-2.602-.41 0-.783.093-1.106.278-1.375.793-1.683 3.264-.973 6.365C1.98 8.917 0 10.42 0 12.004c0 1.59 1.99 3.097 5.043 4.03-.704 3.113-.39 5.588.988 6.38.32.187.69.275 1.102.275 1.345 0 3.107-.96 4.888-2.624 1.78 1.654 3.542 2.603 4.887 2.603.41 0 .783-.09 1.106-.275 1.374-.792 1.683-3.263.973-6.365C22.02 15.096 24 13.59 24 12.004c0-1.59-1.99-3.097-5.043-4.032.704-3.11.39-5.587-.988-6.38-.318-.184-.688-.277-1.092-.278zm-.005 1.09v.006c.225 0 .406.044.558.127.666.382.955 1.835.73 3.704-.054.46-.142.945-.25 1.44-.96-.236-2.006-.417-3.107-.534-.66-.905-1.345-1.727-2.035-2.447 1.592-1.48 3.087-2.292 4.105-2.295zm-9.77.02c1.012 0 2.514.808 4.11 2.28-.686.72-1.37 1.537-2.02 2.442-1.107.117-2.154.298-3.113.538-.112-.49-.195-.964-.254-1.42-.23-1.868.054-3.32.714-3.707.19-.09.4-.127.563-.132zm4.882 3.05c.455.468.91.992 1.36 1.564-.44-.02-.89-.034-1.345-.034-.46 0-.915.01-1.36.034.44-.572.895-1.096 1.345-1.565zM12 8.1c.74 0 1.477.034 2.202.093.406.582.802 1.203 1.183 1.86.372.64.71 1.29 1.018 1.946-.308.655-.646 1.31-1.013 1.95-.38.66-.773 1.288-1.18 1.87-.728.063-1.466.098-2.21.098-.74 0-1.477-.035-2.202-.093-.406-.582-.802-1.204-1.183-1.86-.372-.64-.71-1.29-1.018-1.946.303-.657.646-1.313 1.013-1.954.38-.66.773-1.286 1.18-1.868.728-.064 1.466-.098 2.21-.098zm-3.635.254c-.24.377-.48.763-.704 1.16-.225.39-.435.782-.635 1.174-.265-.656-.49-1.31-.676-1.947.64-.15 1.315-.283 2.015-.386zm7.26 0c.695.103 1.365.23 2.006.387-.18.632-.405 1.282-.66 1.933-.2-.39-.41-.783-.64-1.174-.225-.392-.465-.774-.705-1.146zm3.063.675c.484.15.944.317 1.375.498 1.732.74 2.852 1.708 2.852 2.476-.005.768-1.125 1.74-2.857 2.475-.42.18-.88.342-1.355.493-.28-.958-.646-1.956-1.1-2.98.45-1.017.81-2.01 1.085-2.964zm-13.395.004c.278.96.645 1.957 1.1 2.98-.45 1.017-.812 2.01-1.086 2.964-.484-.15-.944-.318-1.37-.5-1.732-.737-2.852-1.706-2.852-2.474 0-.768 1.12-1.742 2.852-2.476.42-.18.88-.342 1.356-.494zm11.678 4.28c.265.657.49 1.312.676 1.948-.64.157-1.316.29-2.016.39.24-.375.48-.762.705-1.158.225-.39.435-.788.636-1.18zm-9.945.02c.2.392.41.783.64 1.175.23.39.465.772.705 1.143-.695-.102-1.365-.23-2.006-.386.18-.63.406-1.282.66-1.933zM17.92 16.32c.112.493.2.968.254 1.423.23 1.868-.054 3.32-.714 3.708-.147.09-.338.128-.563.128-1.012 0-2.514-.807-4.11-2.28.686-.72 1.37-1.536 2.02-2.44 1.107-.118 2.154-.3 3.113-.54zm-11.83.01c.96.234 2.006.415 3.107.532.66.905 1.345 1.727 2.035 2.446-1.595 1.483-3.092 2.295-4.11 2.295-.22-.005-.406-.05-.553-.132-.666-.38-.955-1.834-.73-3.703.054-.46.142-.944.25-1.438zm4.56.64c.44.02.89.034 1.345.034.46 0 .915-.01 1.36-.034-.44.572-.895 1.095-1.345 1.565-.455-.47-.91-.993-1.36-1.565z',
},
vue: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M24,1.61H14.06L12,5.16,9.94,1.61H0L12,22.39ZM12,14.08,5.16,2.23H9.59L12,6.41l2.41-4.18h4.43Z',
},
ruby: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M20.156.083c3.033.525 3.893 2.598 3.829 4.77L24 4.822 22.635 22.71 4.89 23.926h.016C3.433 23.864.15 23.729 0 19.139l1.645-3 2.819 6.586.503 1.172 2.805-9.144-.03.007.016-.03 9.255 2.956-1.396-5.431-.99-3.9 8.82-.569-.615-.51L16.5 2.114 20.159.073l-.003.01zM0 19.089zM5.13 5.073c3.561-3.533 8.157-5.621 9.922-3.84 1.762 1.777-.105 6.105-3.673 9.636-3.563 3.532-8.103 5.734-9.864 3.957-1.766-1.777.045-6.217 3.612-9.75l.003-.003z',
},
zig: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'm23.53 1.02-7.686 3.45h-7.06l-2.98 3.452h7.173L.47 22.98l7.681-3.607h7.065v-.002l2.978-3.45-7.148-.001 12.482-14.9zM0 4.47v14.901h1.883l2.98-3.45H3.451v-8h.942l2.824-3.45H0zm22.117 0-2.98 3.608h1.412v7.844h-.942l-2.98 3.45H24V4.47h-1.883z',
},
swift: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M7.508 0c-.287 0-.573 0-.86.002-.241.002-.483.003-.724.01-.132.003-.263.009-.395.015A9.154 9.154 0 0 0 4.348.15 5.492 5.492 0 0 0 2.85.645 5.04 5.04 0 0 0 .645 2.848c-.245.48-.4.972-.495 1.5-.093.52-.122 1.05-.136 1.576a35.2 35.2 0 0 0-.012.724C0 6.935 0 7.221 0 7.508v8.984c0 .287 0 .575.002.862.002.24.005.481.012.722.014.526.043 1.057.136 1.576.095.528.25 1.02.495 1.5a5.03 5.03 0 0 0 2.205 2.203c.48.244.97.4 1.498.495.52.093 1.05.124 1.576.138.241.007.483.009.724.01.287.002.573.002.86.002h8.984c.287 0 .573 0 .86-.002.241-.001.483-.003.724-.01a10.523 10.523 0 0 0 1.578-.138 5.322 5.322 0 0 0 1.498-.495 5.035 5.035 0 0 0 2.203-2.203c.245-.48.4-.972.495-1.5.093-.52.124-1.05.138-1.576.007-.241.009-.481.01-.722.002-.287.002-.575.002-.862V7.508c0-.287 0-.573-.002-.86a33.662 33.662 0 0 0-.01-.724 10.5 10.5 0 0 0-.138-1.576 5.328 5.328 0 0 0-.495-1.5A5.039 5.039 0 0 0 21.152.645 5.32 5.32 0 0 0 19.654.15a10.493 10.493 0 0 0-1.578-.138 34.98 34.98 0 0 0-.722-.01C17.067 0 16.779 0 16.492 0H7.508zm6.035 3.41c4.114 2.47 6.545 7.162 5.549 11.131-.024.093-.05.181-.076.272l.002.001c2.062 2.538 1.5 5.258 1.236 4.745-1.072-2.086-3.066-1.568-4.088-1.043a6.803 6.803 0 0 1-.281.158l-.02.012-.002.002c-2.115 1.123-4.957 1.205-7.812-.022a12.568 12.568 0 0 1-5.64-4.838c.649.48 1.35.902 2.097 1.252 3.019 1.414 6.051 1.311 8.197-.002C9.651 12.73 7.101 9.67 5.146 7.191a10.628 10.628 0 0 1-1.005-1.384c2.34 2.142 6.038 4.83 7.365 5.576C8.69 8.408 6.208 4.743 6.324 4.86c4.436 4.47 8.528 6.996 8.528 6.996.154.085.27.154.36.213.085-.215.16-.437.224-.668.708-2.588-.09-5.548-1.893-7.992z',
},
prisma: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M21.8068 18.2848L13.5528.7565c-.207-.4382-.639-.7273-1.1286-.7541-.5023-.0293-.9523.213-1.2062.6253L2.266 15.1271c-.2773.4518-.2718 1.0091.0158 1.4555l4.3759 6.7786c.2608.4046.7127.6388 1.1823.6388.1332 0 .267-.0188.3987-.0577l12.7019-3.7568c.3891-.1151.7072-.3904.8737-.7553s.1633-.7828-.0075-1.1454zm-1.8481.7519L9.1814 22.2242c-.3292.0975-.6448-.1873-.5756-.5194l3.8501-18.4386c.072-.3448.5486-.3996.699-.0803l7.1288 15.138c.1344.2856-.019.6224-.325.7128z',
},
typescript: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M1.125 0C.502 0 0 .502 0 1.125v21.75C0 23.498.502 24 1.125 24h21.75c.623 0 1.125-.502 1.125-1.125V1.125C24 .502 23.498 0 22.875 0zm17.363 9.75c.612 0 1.154.037 1.627.111a6.38 6.38 0 0 1 1.306.34v2.458a3.95 3.95 0 0 0-.643-.361 5.093 5.093 0 0 0-.717-.26 5.453 5.453 0 0 0-1.426-.2c-.3 0-.573.028-.819.086a2.1 2.1 0 0 0-.623.242c-.17.104-.3.229-.393.374a.888.888 0 0 0-.14.49c0 .196.053.373.156.529.104.156.252.304.443.444s.423.276.696.41c.273.135.582.274.926.416.47.197.892.407 1.266.628.374.222.695.473.963.753.268.279.472.598.614.957.142.359.214.776.214 1.253 0 .657-.125 1.21-.373 1.656a3.033 3.033 0 0 1-1.012 1.085 4.38 4.38 0 0 1-1.487.596c-.566.12-1.163.18-1.79.18a9.916 9.916 0 0 1-1.84-.164 5.544 5.544 0 0 1-1.512-.493v-2.63a5.033 5.033 0 0 0 3.237 1.2c.333 0 .624-.03.872-.09.249-.06.456-.144.623-.25.166-.108.29-.234.373-.38a1.023 1.023 0 0 0-.074-1.089 2.12 2.12 0 0 0-.537-.5 5.597 5.597 0 0 0-.807-.444 27.72 27.72 0 0 0-1.007-.436c-.918-.383-1.602-.852-2.053-1.405-.45-.553-.676-1.222-.676-2.005 0-.614.123-1.141.369-1.582.246-.441.58-.804 1.004-1.089a4.494 4.494 0 0 1 1.47-.629 7.536 7.536 0 0 1 1.77-.201zm-15.113.188h9.563v2.166H9.506v9.646H6.789v-9.646H3.375z',
},
javascript: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M0 0h24v24H0V0zm22.034 18.276c-.175-1.095-.888-2.015-3.003-2.873-.736-.345-1.554-.585-1.797-1.14-.091-.33-.105-.51-.046-.705.15-.646.915-.84 1.515-.66.39.12.75.42.976.9 1.034-.676 1.034-.676 1.755-1.125-.27-.42-.404-.601-.586-.78-.63-.705-1.469-1.065-2.834-1.034l-.705.089c-.676.165-1.32.525-1.71 1.005-1.14 1.291-.811 3.541.569 4.471 1.365 1.02 3.361 1.244 3.616 2.205.24 1.17-.87 1.545-1.966 1.41-.811-.18-1.26-.586-1.755-1.336l-1.83 1.051c.21.48.45.689.81 1.109 1.74 1.756 6.09 1.666 6.871-1.004.029-.09.24-.705.074-1.65l.046.067zm-8.983-7.245h-2.248c0 1.938-.009 3.864-.009 5.805 0 1.232.063 2.363-.138 2.711-.33.689-1.18.601-1.566.48-.396-.196-.597-.466-.83-.855-.063-.105-.11-.196-.127-.196l-1.825 1.125c.305.63.75 1.172 1.324 1.517.855.51 2.004.675 3.207.405.783-.226 1.458-.691 1.811-1.411.51-.93.402-2.07.397-3.346.012-2.054 0-4.109 0-6.179l.004-.056z',
},
php: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'M7.01 10.207h-.944l-.515 2.648h.838c.556 0 .97-.105 1.242-.314.272-.21.455-.559.55-1.049.092-.47.05-.802-.124-.995-.175-.193-.523-.29-1.047-.29zM12 5.688C5.373 5.688 0 8.514 0 12s5.373 6.313 12 6.313S24 15.486 24 12c0-3.486-5.373-6.312-12-6.312zm-3.26 7.451c-.261.25-.575.438-.917.551-.336.108-.765.164-1.285.164H5.357l-.327 1.681H3.652l1.23-6.326h2.65c.797 0 1.378.209 1.744.628.366.418.476 1.002.33 1.752a2.836 2.836 0 0 1-.305.847c-.143.255-.33.49-.561.703zm4.024.715l.543-2.799c.063-.318.039-.536-.068-.651-.107-.116-.336-.174-.687-.174H11.46l-.704 3.625H9.388l1.23-6.327h1.367l-.327 1.682h1.218c.767 0 1.295.134 1.586.401s.378.7.263 1.299l-.572 2.944h-1.389zm7.597-2.265a2.782 2.782 0 0 1-.305.847c-.143.255-.33.49-.561.703a2.44 2.44 0 0 1-.917.551c-.336.108-.765.164-1.286.164h-1.18l-.327 1.682h-1.378l1.23-6.326h2.649c.797 0 1.378.209 1.744.628.366.417.477 1.001.331 1.751zM17.766 10.207h-.943l-.516 2.648h.838c.557 0 .971-.105 1.242-.314.272-.21.455-.559.551-1.049.092-.47.049-.802-.125-.995s-.524-.29-1.047-.29z',
},
shellscript: {
viewBox: '0 0 24 24',
fill: 'currentColor',
d: 'm 4,4 a 1,1 0 0 0 -0.7070312,0.2929687 1,1 0 0 0 0,1.4140625 L 8.5859375,11 3.2929688,16.292969 a 1,1 0 0 0 0,1.414062 1,1 0 0 0 1.4140624,0 l 5.9999998,-6 a 1.0001,1.0001 0 0 0 0,-1.414062 L 4.7070312,4.2929687 A 1,1 0 0 0 4,4 Z m 8,14 a 1,1 0 0 0 -1,1 1,1 0 0 0 1,1 h 8 a 1,1 0 0 0 1,-1 1,1 0 0 0 -1,-1 z',
},
c: {
viewBox: '0 0 24 24',
fill: 'currentColor',
```
Sources: [packages/core/src/mdx-plugins/transformer-icon.ts:3-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts#L3-L115)
> [!NOTE]
> Java is not supported in the default icon set due to upstream limitations in Simple Icons.
Sources: [packages/core/src/mdx-plugins/transformer-icon.ts:27-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts#L27-L28)
### Tab Metadata Extraction and Multi-Tab Grouping
The `remarkCodeTab` unified transformer scans Markdown AST nodes for contiguous code blocks carrying `tab` attributes in their meta strings. It processes these sequences via `parseCodeBlockAttributes`, extracting `tab` and `tab-group` metadata and populating `child.data.tab` and `child.data.tabGroup` properties.
```typescript
if (child.type !== 'code' || !child.meta) {
close();
continue;
}
const meta = parseCodeBlockAttributes(child.meta, ['tab', 'tab-group']);
if (!meta.attributes.tab) {
close();
continue;
}
if (start === -1) start = end;
child.meta = meta.rest;
child.data ??= {};
child.data.tab = meta.attributes.tab;
if (meta.attributes['tab-group']) {
child.data.tabGroup = meta.attributes['tab-group'];
}
}
```
Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:250-268](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L250-L268)
The transformation delegates rendering to the `Types` handler record based on the configured `TabType`, which supports either `CodeBlockTabs` or `Tabs`.
| Tab Handler Type | Target Node Structure | Persistence Support | MDX Parsing Support |
| :--- | :--- | :--- | :--- |
| `CodeBlockTabs` | `CodeBlockTabsOptions` via `generateCodeBlockTabs` | Optional `persist: { id: tagGroup }` derived from the first tab's `tabGroup` | Optional via `mdxToAst` processor when `parseMdx` is enabled |
| `Tabs` | `MdxJsxFlowElement` (`Tabs`, `TabsList`, `TabsTrigger`, `TabsContent`) | None (relies on component props) | Full MDX element generation or simple attribute items mode |
Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:11-200](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L11-L200)
> [!WARNING]
> When `Tabs` operates in simple mode without MDX parsing (`withMdx` set to false), it does not support rich MDX tab names and emits comma-joined literal arrays into the `items` attribute.
Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:92-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L92-L146)
## Client-Side Dynamic Highlighting Hooks
### Asynchronous Shiki Execution and React Hooks
Browser-side syntax highlighting in Fumadocs relies on React state and suspense hooks that transform code strings into JSX nodes via Shiki and `hast-util-to-jsx-runtime`. The `useShikiDynamic` hook manages asynchronous highlighting tasks using `useEffect`, maintaining a task reference to prevent race conditions during rapid state changes. When a highlighting promise resolves, it checks whether `lastTask.current` matches the running promise before updating the node state.
```typescript
export function useShikiDynamic(
highlighter: HighlighterCore | (() => Awaitable),
code: string,
options: UseShikiOptions & { defaultValue?: ReactNode },
deps: DependencyList,
): ReactNode {
const [node, setNode] = useState(options.defaultValue);
const lastTask = useRef | null>(null);
useEffect(() => {
async function task() {
const instance = typeof highlighter === 'function' ? await highlighter() : highlighter;
return toJsxRuntime(await highlightHast(instance, code, options), {
...JsxRuntime,
components: options.components,
});
}
const promise = task();
lastTask.current = promise;
void promise.then((res) => {
if (lastTask.current === promise) setNode(res);
});
return () => {
lastTask.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return node;
}
```
Sources: [packages/core/src/highlight/shiki/react.ts:27-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L27-L59)
The `useShiki` hook integrates with the React `use` API for suspenseful data fetching. It caches compiled results using JSON-serialized dependency arrays derived from language identifiers and code contents by default, or custom dependency lists when specified.
```typescript
export function useShiki(
highlighter: HighlighterCore | (() => Awaitable),
code: string,
options: UseShikiOptions,
deps: DependencyList = [options.lang, code],
): ReactNode {
const key = useMemo(() => JSON.stringify(deps), [deps]);
async function run() {
const instance = typeof highlighter === 'function' ? await highlighter() : highlighter;
return toJsxRuntime(await highlightHast(instance, code, options), {
...JsxRuntime,
components: options.components,
});
}
return use((promises[key] ??= run()));
}
```
Sources: [packages/core/src/highlight/shiki/react.ts:66-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L66-L84)
A client-specific wrapper for `useShiki` initializes default themes automatically using `defaultShikiFactory.getOrInit()` combined with `applyDefaultThemes`.
```typescript
export function useShiki(
code: string,
options: HighlightOptions,
deps?: DependencyList,
): ReactNode {
return useShikiBase(
() => defaultShikiFactory.getOrInit(),
code,
applyDefaultThemes(options),
deps,
);
}
```
Sources: [packages/core/src/highlight/client.ts:13-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/client.ts#L13-L24)
> [!NOTE]
> Results in `useShiki` are cached using `(lang, code)` pairs as keys unless an explicit dependency list overrides the memoization key.
Sources: [packages/core/src/highlight/shiki/react.ts:64-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L64-L64)
### Dynamic Code Block Component Integration
The `DynamicCodeBlock` component wraps dynamic client highlighting in a structured UI container. It accepts a highlighter instance or factory function, target language, raw code string, and optional configuration props.
```tsx
export function DynamicCodeBlock({
lang,
code,
codeblock,
options,
wrapInSuspense = true,
highlighter,
}: DynamicCodeblockProps) {
const id = useId();
const shikiOptions: UseShikiOptions = {
lang,
defaultColor: false,
...options,
components: {
pre: DefaultPre,
...options.components,
},
};
let node = useShikiDynamic(highlighter, code, shikiOptions, [id, lang, code]);
if (wrapInSuspense) node ??= ;
return {node};
}
```
Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:45-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L45-L67)
| Property | Type | Default Value | Purpose |
| :--- | :--- | :--- | :--- |
| `highlighter` | `HighlighterCore \| (() => HighlighterCore \| PromiseLike)` | *Required* | Shiki core instance or asynchronous initialization factory. |
| `lang` | `string` | *Required* | Target programming language identifier for syntax grammar selection. |
| `code` | `string` | *Required* | Raw source code text content to highlight. |
| `codeblock` | `CodeBlockProps` | `undefined` | Extra properties passed to the underlying `CodeBlock` component. |
| `wrapInSuspense` | `boolean` | `true` | Toggles automatic wrapping in a React `Suspense` boundary with a fallback placeholder. |
| `options` | `DistributiveOmit` | *Required* | Highlighting configuration options excluding language. |
Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:8-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L8-L25)
When `wrapInSuspense` is enabled and the dynamic node has not yet resolved, a `Placeholder` component splits the raw code into individual line spans using `code.split('\n')` rendered inside `pre` and `code` elements.
```tsx
function Placeholder({
code,
components = {},
}: {
code: string;
components: UseShikiOptions['components'];
}) {
const { pre: Pre = 'pre', code: Code = 'code' } = components as Record;
return (
{code.split('\n').map((line, i) => (
{line}
))}
);
```
Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:69-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L69-L88)
> [!WARNING]
> Defining a custom `pre` component inside `options.components` ignores extra `codeblock` properties passed to `DynamicCodeBlock`.
Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:13-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L13-L16)
## Code Block Styling Architecture
### CSS Custom Properties and Layout
Code blocks rely on CSS custom properties defined in package stylesheets to manage horizontal spacing and alignment. The padding variables `--padding-left` and `--padding-right` are calculated as four times the spacing scale token.
```css
.shiki:not(.not-fumadocs-codeblock *) {
--padding-left: calc(var(--spacing) * 4);
--padding-right: calc(var(--spacing) * 4);
```
Sources: [packages/base-ui/css/lib/shiki.css:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L1-L4)
Each line element within a Shiki block establishes a relative positioning context and applies these padding rules. Empty lines are explicitly sized using line height units to preserve vertical rhythm.
```css
.line {
position: relative;
padding-left: var(--padding-left);
padding-right: var(--padding-right);
}
.line:empty {
height: 1lh;
}
```
Sources: [packages/base-ui/css/lib/shiki.css:10-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L10-L18)
> [!NOTE]
> Empty lines set `height: 1lh` to ensure they maintain the exact height of populated text lines.
Sources: [packages/base-ui/css/lib/shiki.css:16-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L16-L18)
### Token Color Containment
Token coloring is scoped through CSS variables generated by Shiki for light and dark themes. Under standard selector rules, `code span` elements pull their color and font style properties directly from `--shiki-light` and `--shiki-light-font-style`.
```css
code span {
color: var(--shiki-light);
font-style: var(--shiki-light-font-style);
}
```
Sources: [packages/base-ui/css/lib/shiki.css:5-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L5-L8)
When the `.dark` class is present on an ancestor container, token colors override the light variables by binding to `--shiki-dark` and `--shiki-dark-font-style`. Inline code elements follow an identical scoping strategy via `code.shiki`.
```css
.dark .shiki:not(.not-fumadocs-codeblock *) {
code span {
color: var(--shiki-dark);
font-style: var(--shiki-dark-font-style);
}
}
```
Sources: [packages/base-ui/css/lib/shiki.css:92-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L92-L97)
### Interactive Line States and Modifiers
Code blocks support specialized line decorations including diff indicators, focus blur effects, line numbering, and custom word highlighting. When `.has-focused` is active on the container, unselected lines receive a 2px blur filter that transitions smoothly over 200 milliseconds unless hovered.
```css
&.has-focused .line:not(.focused) {
filter: blur(2px);
transition: filter 200ms;
}
&.has-focused:hover .line:not(.focused) {
filter: blur(0);
}
```
Sources: [packages/base-ui/css/lib/shiki.css:20-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L20-L27)
| Class Selector | Applied Styles / Tailwind Mixins | Purpose |
| :--- | :--- | :--- |
| `.diff.remove` | `opacity: 0.7; bg-fd-diff-remove` | Styles removed lines in diff views with an opacity drop and background tint. |
| `.diff.add` | `bg-fd-diff-add` | Applies an addition background tint to newly introduced lines. |
| `.highlighted` | `bg-fd-primary/10` with primary border accent | Highlights specific target lines and renders an absolute left accent bar. |
| `.highlighted-word` | `border border-fd-primary/30 bg-fd-primary/10 rounded-md font-medium` | Outlines and backgrounds individual token words within code lines. |
Sources: [packages/base-ui/css/lib/shiki.css:34-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L34-L69)
When data line numbering is enabled (`[data-line-numbers]`), lines increment a CSS counter and prepend a pseudo-element displaying the current line index aligned to a fixed 7-spacing-unit column width.
```css
&[data-line-numbers] .line {
counter-increment: line;
padding-left: calc(var(--padding-left) + 7 * var(--spacing));
}
&[data-line-numbers] .line::after {
position: absolute;
content: counter(line);
color: color-mix(
in oklab,
var(--fd-counter-color, var(--color-fd-muted-foreground)) 60%,
transparent
);
@apply inset-y-0 left-0 w-7 text-right;
}
```
Sources: [packages/base-ui/css/lib/shiki.css:75-89](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L75-L89)
## Related
- [Code Block Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/code-block-components)
- [Twoslash Type Hover](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/twoslash-type-hover)
---
## Technical docs: Markdown AST Plugins
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/markdown-ast-plugins
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/mdx-plugins/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts)
- [packages/obsidian/src/remark/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/index.ts)
- [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts)
- [packages/mdx/src/loaders/mdx/remark-postprocess.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts)
- [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts)
- [packages/core/src/content/mdx/preset-bundler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts)
- [packages/core/src/mdx-plugins/rehype-toc.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts)
- [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts)
- [packages/core/src/mdx-plugins/remark-steps.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts)
- [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts)
- [packages/mdx/src/rolldown/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts)
- [packages/core/src/content/mdx/preset-runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts)
- [packages/obsidian/src/remark/remark-convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-convert.ts)
- [packages/doc-gen/src/remark-install.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-install.ts)
- [packages/core/src/mdx-plugins/remark-mdx-files.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts)
- [packages/typescript/src/lib/remark-auto-type-table.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/lib/remark-auto-type-table.ts)
- [packages/core/src/mdx-plugins/remark-directive-admonition.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts)
- [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts)
- [packages/core/src/mdx-plugins/remark-gfm.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-gfm.ts)
- [packages/core/src/mdx-plugins/remark-npm.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-npm.ts)
- [packages/core/src/mdx-plugins/remark-heading.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts)
- [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts)
- [packages/core/src/mdx-plugins/remark-code-tab.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts)
- [packages/mdx/src/config/preset.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts)
- [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts)
- [packages/core/src/mdx-plugins/rehype-code.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.ts)
- [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts)
- [packages/core/src/mdx-plugins/remark-admonition.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts)
- [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts)
- [packages/core/src/content/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/md.ts)
## Overview
Fumadocs processes documentation through an extensible pipeline of remark and rehype plugins that transform abstract syntax trees to support features like admonitions, code tabs, and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) generation. These plugins integrate directly with [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline), [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader), and [Content Collections Adapter](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/content-collections-adapter) to standardize markdown compilation across build tools and runtimes.
Sources: [packages/core/src/mdx-plugins/index.ts:1-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts#L1-L16), [packages/core/src/content/mdx/preset-bundler.ts:23-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L23-L92), [packages/content-collections/src/configuration.ts:58-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L58-L124)
## Admonition parsing and directive transformations
### Directive-Based Admonition Containers
The `remarkDirectiveAdmonition` plugin processes `containerDirective` nodes within the [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) to support standard callout syntaxes, particularly for migrations from Docusaurus. It inspects tree nodes using `unist-util-visit`, checking whether a node name matches any entry in the configured `types` mapping. When a match is found, the plugin transforms the AST node into an `mdxJsxFlowElement` representing a callout container.
```typescript
export function remarkDirectiveAdmonition({
tags: {
CalloutContainer = 'CalloutContainer',
CalloutTitle = 'CalloutTitle',
CalloutDescription = 'CalloutDescription',
} = {},
types = {
note: 'info',
tip: 'info',
info: 'info',
warn: 'warning',
warning: 'warning',
danger: 'error',
success: 'success',
},
}: RemarkDirectiveAdmonitionOptions = {}): Transformer {
```
Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:29-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L29-L44)
The mapping between input directive names and target callout types defaults to specific standard identifiers.
| Directive Name | Target Callout Type |
| -------------- | ------------------- |
| `note` | `info` |
| `tip` | `info` |
| `info` | `info` |
| `warn` | `warning` |
| `warning` | `warning` |
| `danger` | `error` |
| `success` | `success` |
Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:35-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L35-L43)
During transformation, any directive attributes present on the container are extracted into `mdxJsxAttribute` objects, alongside the primary `type` attribute. Children of the container are partitioned: paragraphs flagged with `directiveLabel` are routed into a title element named via `CalloutTitle`, while all remaining content blocks form the children of a description element named via `CalloutDescription`.
```typescript
const titleNodes: PhrasingContent[] = [];
const descriptionNodes: (BlockContent | DefinitionContent)[] = [];
for (const item of node.children) {
if (item.type === 'paragraph' && item.data?.directiveLabel) {
titleNodes.push(...item.children);
} else {
descriptionNodes.push(item);
}
}
const children: MdxJsxFlowElement[] = [];
if (titleNodes.length > 0) {
children.push({
type: 'mdxJsxFlowElement',
name: CalloutTitle,
attributes: [],
children: titleNodes as BlockContent[],
});
}
if (descriptionNodes.length > 0) {
children.push({
type: 'mdxJsxFlowElement',
name: CalloutDescription,
attributes: [],
children: descriptionNodes,
});
}
```
Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:65-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L65-L95)
> [!NOTE]
> `remarkDirectiveAdmonition` requires `remark-directive` to be configured beforehand in the unified pipeline to parse container directive syntax correctly.
> Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:26-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L26-L28)
### Legacy Admonition Syntax Rewriting
The legacy `remarkAdmonition` plugin provides backward compatibility for custom admonition tags (defaulting to `:::`) by scanning paragraph nodes, flattening their contents, and searching for matching type keys. While deprecated in favor of directive-based parsing, it maps alternative type names and extracts bracketed title meta strings into JSX attributes for standard `Callout` elements.
```typescript
export function remarkAdmonition(options: RemarkAdmonitionOptions = {}): Transformer {
const tag = options.tag ?? ':::';
// compatible with Docusaurus
const typeMap = options.typeMap ?? {
info: 'info',
warn: 'warn',
note: 'info',
tip: 'info',
warning: 'warn',
danger: 'error',
};
```
Sources: [packages/core/src/mdx-plugins/remark-admonition.ts:22-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts#L22-L34)
> [!WARNING]
> Using nested admonitions with the legacy `remarkAdmonition` parser sets an `hasIntercept` flag that recursively invokes `replaceNodes` on inner child slices.
> Sources: [packages/core/src/mdx-plugins/remark-admonition.ts:40-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts#L40-L41), [packages/core/src/mdx-plugins/remark-admonition.ts:80|80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts#L80-L80)
## Heading slugs and table generation
### Heading Slug Assignment and TOC Extraction
The `remarkHeading` plugin processes markdown trees using `unist-util-visit` to locate heading nodes and assign unique URL-safe identifiers via `github-slugger`. By default, it supports custom heading IDs through a regular expression that inspects the final text node of a heading for a bracketed slug pattern (`[#slug]`). When a custom ID is matched, the plugin assigns it to `heading.data.hProperties.id` and strips the trailing tag from the node value. If no custom ID is present, it flattens the node content and passes it to the configured slug function.
```typescript
const regex = /\s*\[#(?[^]+?)]\s*$/;
```
Sources: [packages/core/src/mdx-plugins/remark-heading.ts:16-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L16-L16), [packages/core/src/mdx-plugins/remark-heading.ts:63-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L63-L95)
When `generateToc` is enabled, the plugin constructs an array of `TOCItemType` entries storing the title text, hash URL, and heading depth, attaching the resulting collection directly to `file.data.toc`.
```typescript
if (generateToc) {
toc.push({
title: flattened ?? flattenNode(heading),
url: `#${props.id}`,
depth: heading.depth,
});
}
```
Sources: [packages/core/src/mdx-plugins/remark-heading.ts:86-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L86-L92), [packages/core/src/mdx-plugins/remark-heading.ts:97-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L97-L97)
> [!NOTE]
> `remarkHeading` initializes a fresh `Slugger` instance and resets it on each transformer execution to guarantee deterministic ID generation across builds.
> Sources: [packages/core/src/mdx-plugins/remark-heading.ts:53-62](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L53-L62)
### Structured Data Extraction
The `remarkStructure` plugin parses MDAST trees to build searchable structured data containing headings and content blocks. It scans nodes matching specified types, defaulting to paragraphs, blockquotes, table cells, headings, and leaf MDX flow elements.
```typescript
export const remarkStructureDefaultOptions = {
types: ['heading', 'paragraph', 'blockquote', 'tableCell', 'mdxJsxFlowElement'],
mdxTypes(node) {
return !node.children || node.children.length === 0;
},
exportAs: false,
} satisfies StructureOptions;
```
Sources: [packages/core/src/mdx-plugins/remark-structure.ts:94-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts#L94-L100)
If a heading node lacks an `hProperties.id`, `remarkStructure` emits a warning and skips it, requiring `remarkHeading` to run beforehand in the pipeline.
```typescript
if (typeof id !== 'string') {
console.warn(
'[remark-structure] hProperties.id is missing in heading node, it is required to generate heading data. You can add remark-heading prior to remark-structure to generate heading IDs.',
);
return 'skip';
}
```
Sources: [packages/core/src/mdx-plugins/remark-structure.ts:173-178](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts#L173-L178)
Collected blocks associate their content with the most recently encountered heading ID, storing the structured output in `file.data.structuredData` or serializing it as an MDX export when `exportAs` is configured.
```typescript
file.data.structuredData = data;
if (exportAs) {
tree.children.unshift(
toMdxExport(typeof exportAs === 'string' ? exportAs : 'structuredData', data),
);
}
```
Sources: [packages/core/src/mdx-plugins/remark-structure.ts:204-209](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts#L204-L209)
### Rehype Table of Contents Generation
The `rehypeToc` plugin inspects HTML element trees for heading tags (`h1` through `h6`) to build a table of contents directly from HAST nodes. It recognizes control tags appended to heading text to alter behavior: `[!toc]` suppresses the heading from the table of contents and strips the tag, while `[toc]` includes the heading but removes the tag from the rendered output.
```typescript
const TocOnlyTag = '[toc]';
const NoTocTag = '[!toc]';
const HeadingTags = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
```
Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:51-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L51-L53), [packages/core/src/mdx-plugins/rehype-toc.ts:77-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L77-L91)
| Configuration Property | Type | Default Value | Purpose |
| ---------------------- | ---- | ------------- | ------- |
| `exportToc` | `boolean \| { as: 'data' } \| { as: 'esm', name: string }` | `true` | Determines whether the table of contents is exported as an ESM variable or stored in virtual file data. |
Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:8-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L8-L30), [packages/core/src/mdx-plugins/rehype-toc.ts:55-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L55-L61)
When `exportToc` is configured as an ESM export (defaulting to the name `toc`), the plugin converts HAST heading nodes into ESTree JSX fragments using `hast-util-to-estree`.
```typescript
if (exportToc.as === 'esm') {
const esmItems: {
title: JSXElement;
url: string;
depth: number;
_step?: number;
}[] = [];
for (const item of items) {
const root = toEstree(item.title, {
elementAttributeNameCase: 'react',
stylePropertyNameCase: 'dom',
}).body[0];
if (root.type === 'ExpressionStatement' && root.expression.type === 'JSXElement') {
esmItems.push({
...item,
title: root.expression,
});
}
```
Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:110-128](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L110-L128)
> [!WARNING]
> Headings without a valid string identifier in their properties are skipped by `rehypeToc` and omitted from the generated table of contents.
> Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:73-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L73-L74)
## Sequential step list conversion
### Step Detection and Parsing
The `remarkSteps` plugin transforms consecutive step headings and their accompanying content into structured MDX JSX flow elements. It accepts an options object to customize CSS class names for both the outer steps container and individual step items.
| Configuration Property | Type | Default Value | Purpose |
| ---------------------- | ---- | ------------- | ------- |
| `steps` | `string` | `'fd-steps'` | Class name assigned to the outer wrapper container div element. |
| `step` | `string` | `'fd-step'` | Class name assigned to each individual step item container div element. |
Sources: [packages/core/src/mdx-plugins/remark-steps.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L7-L21), [packages/core/src/mdx-plugins/remark-steps.ts:29-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L29-L32)
To identify step headings, the plugin evaluates heading text against a regular expression pattern matching numeric prefixes like `1. Hello World`, or checks for the trailing tag `[step]` via `handleTag`. When a valid step pattern matches, the plugin strips the marker from the text node and injects a `data-fd-step` property containing the incremental step index onto the heading's data properties.
```typescript
const StepRegex = /^(\d+)\.\s(.+)$/;
const StepTag = '[step]';
```
Sources: [packages/core/src/mdx-plugins/remark-steps.ts:23-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L23-L24), [packages/core/src/mdx-plugins/remark-steps.ts:70-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L70-L90), [packages/core/src/mdx-plugins/remark-steps.ts:124-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L124-L132)
> [!WARNING]
> If a heading has a mismatched depth or fails step parsing while a sequence is actively collecting, the plugin immediately terminates the current step group via `onEnd()`.
> Sources: [packages/core/src/mdx-plugins/remark-steps.ts:118-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L118-L127)
## Code tabs and command generation
### Package Manager Conversion and Tabs Generation
Fumadocs provides remark plugins to rewrite code blocks into multi-tab package manager interfaces. The core pipeline includes `remarkNpm` and `remarkCodeTab`, alongside legacy support from `remarkInstall`.
| Plugin Name | Target Language / Marker | Output Element |
| ----------- | ------------------------ | -------------- |
| `remarkNpm` | `package-install`, `npm` | CodeBlockTabs / custom triggers |
| `remarkInstall` | `package-install` | Tabs, Tab |
| `remarkCodeTab` | Code blocks with `tab` attribute | CodeBlockTabs or Tabs / Tab |
Sources: [packages/core/src/mdx-plugins/remark-npm.ts:60-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-npm.ts#L60-L73), [packages/doc-gen/src/remark-install.ts:60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-install.ts#L60), [packages/core/src/mdx-plugins/remark-code-tab.ts:255-259](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L255-L259)
The `remarkNpm` plugin visits code blocks in the Markdown AST and detects nodes where the language is `package-install` or `npm`. For `package-install` blocks, if the text does not start with `npm` or `npx`, it automatically prepends `npm install`. It then maps over configured package managers to translate commands and generate code block tabs.
```typescript
export function remarkNpm({
persist = false,
packageManagers = [
{ command: (cmd) => cmd, name: 'npm' },
{ command: (cmd) => convertLines(cmd, 'pnpm'), name: 'pnpm' },
{ command: (cmd) => convertLines(cmd, 'yarn'), name: 'yarn' },
{ command: (cmd) => convertLines(cmd, 'bun'), name: 'bun' },
],
}: RemarkNpmOptions = {}): Transformer {
```
Sources: [packages/core/src/mdx-plugins/remark-npm.ts:46-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-npm.ts#L46-L54)
> [!NOTE]
> `remarkInstall` from `@fumadocs/doc-gen` is deprecated in favor of `remarkNpm` from `fumadocs-core/mdx-plugins`, which serves as a drop-in replacement.
> Sources: [packages/doc-gen/src/remark-install.ts:45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-install.ts#L45)
### Custom Code Tabs and Attribute Parsing
The `remarkCodeTab` plugin processes adjacent code blocks decorated with meta attributes like `tab` and `tab-group`. It supports two layout handlers defined in `Types`: `CodeBlockTabs` and `Tabs`.
| Option Property | Type | Default Value | Purpose |
| --------------- | ---- | ------------- | ------- |
| `Tabs` | `'CodeBlockTabs' \| 'Tabs'` | `'CodeBlockTabs'` | Determines the component name used for rendering grouped tab containers. |
| `parseMdx` | `boolean` | `false` | Enables parsing of embedded MDX inside tab trigger values. |
Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:11-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L11-L21), [packages/core/src/mdx-plugins/remark-code-tab.ts:206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L206)
During visitation, `remarkCodeTab` uses `parseCodeBlockAttributes` to extract `tab` and `tab-group` metadata from code block strings, assigns them to node data properties, and strips them from the raw meta string so syntax highlighters do not receive unknown flags.
```typescript
for (; end < node.children.length; end++) {
const child = node.children[end];
if (child.type !== 'code' || !child.meta) {
close();
continue;
}
const meta = parseCodeBlockAttributes(child.meta, ['tab', 'tab-group']);
if (!meta.attributes.tab) {
close();
continue;
}
if (start === -1) start = end;
child.meta = meta.rest;
child.data ??= {};
child.data.tab = meta.attributes.tab;
if (meta.attributes['tab-group']) {
child.data.tabGroup = meta.attributes['tab-group'];
}
}
```
Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:248-268](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L248-L268)
> [!WARNING]
> When processing `Tabs` in simple mode with `parseMdx` enabled, the plugin checks whether the existing node attributes contain an `items` property before attempting to parse tab names as MDX.
> Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:220-224](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L220-L224)
## Mermaid diagram code block conversion
### Remark Transformer and AST Replacement
The `remarkMdxMermaid` plugin transforms fenced code blocks containing diagram specifications into dynamic MDX JSX flow elements. It exports an options interface that accepts a custom language identifier.
| Option Property | Type | Default Value | Purpose |
| --------------- | ---- | ------------- | ------- |
| `lang` | `string` | `'mermaid'` | Specifies the target code block language identifier to match during AST visitation. |
Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:21-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L21-L26)
The plugin returns a unified transformer function that traverses the markdown abstract syntax tree using `unist-util-visit`. It targets nodes of type `code`, validates their positional indices and parent references, and compares their language property against the configured target language.
```typescript
export function remarkMdxMermaid(options: RemarkMdxMermaidOptions = {}): Transformer {
const { lang = 'mermaid' } = options;
return (tree) => {
visit(tree, 'code', (node, idx, parent) => {
if (node.lang !== lang || !node.value || typeof idx !== 'number' || !parent) return;
parent.children[idx] = toMDX(node.value);
});
};
```
Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:31-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L31-L40)
> [!CAUTION]
> The visitor function skips code block nodes where `idx` is not a number or where `parent` is undefined, preventing out-of-bounds mutations on root or unattached AST nodes.
> Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L36)
### MDX JSX Node Generation
When a matching code block is identified, the plugin delegates conversion to the `toMDX` helper function. This function constructs an `MdxJsxFlowElement` node configured to render the `` component.
```typescript
function toMDX(code: string): MdxJsxFlowElement {
return {
type: 'mdxJsxFlowElement',
name: 'Mermaid',
attributes: [
{
type: 'mdxJsxAttribute',
name: 'chart',
value: code.trim(),
},
],
children: [],
};
}
```
Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:6-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L6-L19)
> [!NOTE]
> The source code inside the matched code block is trimmed via `code.trim()` before being assigned to the `chart` attribute of the generated JSX element, removing leading and trailing whitespace from the diagram definition.
> Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L14)
## LLM exports and postprocessing pipeline
### Remark LLM Stringification and Placeholder Transformation
The `remarkLLMs` plugin processes markdown trees to generate clean plain-text representations and exportable string constants suitable for large language model ingestion. It accepts an options interface extending stringifier configurations with export name, heading identifier inclusion, element filtering, and placeholder conversion settings.
| Option Property | Type | Default Value | Purpose |
| --------------- | ---- | ------------- | ------- |
| `as` | `string` | `'_markdown'` | Defines the variable name for the exported markdown string. |
| `headingIds` | `boolean` | `true` | Appends explicit heading anchors (`[#id]`) to output headings when present. |
| `filterElement` | `StringifyOptions['filterElement']` | Custom function | Filters elements; excludes `mdxjsEsm` by default while retaining others. |
| `mdxAsPlaceholder` | `string[]` | `undefined` | Target MDX component tag names to stringify as runtime placeholders. |
| `_data` | `boolean` | `false` | Stores the generated markdown string inside `file.data.markdown`. |
Sources: [packages/core/src/mdx-plugins/remark-llms.ts:9-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts#L9-L55)
The internal stringifier customizes node serialization by invoking `placeholder` for matching `mdxJsxFlowElement` and `mdxJsxTextElement` nodes listed in `mdxAsPlaceholder`.
```typescript
stringify(node, parent, state, info, ctx) {
if (mdxAsPlaceholder) {
switch (node.type) {
case 'mdxJsxFlowElement':
case 'mdxJsxTextElement':
if (node.name && mdxAsPlaceholder.includes(node.name))
return placeholder(node, parent, state, info);
}
}
return rest.stringify?.(node, parent, state, info, ctx);
},
```
Sources: [packages/core/src/mdx-plugins/remark-llms.ts:80-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts#L80-L91)
> [!NOTE]
> The `placeholder` helper extracts valid non-expression attributes, formats element phrasing children, and serializes the resulting payload into a null-delimited JSON string format conforming to `PlaceholderData`.
> Sources: [packages/core/src/mdx-plugins/remark-llms.ts:112-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts#L112-L129)
### Postprocessing Pipeline and Frontmatter Extraction
The `remarkPostprocess` transformer orchestrates document metadata generation, reference extraction, and optional LLM string export. It inspects configuration options to determine which values to extract and export into the module AST.
| Option Property | Type | Default Value | Purpose |
| --------------- | ---- | ------------- | ------- |
| `_format` | `'md' \| 'mdx'` | Required | Specifies the underlying document format. |
| `valueToExport` | `string[]` | `[]` | Additional property keys from `file.data` to export as named variables. |
| `includeProcessedMarkdown` | `boolean \| LLMsOptions` | `false` | Enables `remarkLLMs` processing and exports the resulting string. |
| `extractLinkReferences` | `boolean` | `false` | Collects link href values and exports them via `extractedReferences`. |
| `includeMDAST` | `boolean \| { removePosition?: boolean }` | `false` | Serializes and exports the document MDAST via `_mdast`. |
Sources: [packages/mdx/src/loaders/mdx/remark-postprocess.ts:14-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts#L14-L40)
> [!WARNING]
> If `frontmatter.title` is missing, the postprocessor traverses the AST to find the first level-1 heading and flattens its text nodes to auto-populate the document title.
> Sources: [packages/mdx/src/loaders/mdx/remark-postprocess.ts:56-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts#L56-L64)
Exported declarations are injected into the AST by converting JavaScript values into estree nodes using `valueToEstree`, wrapped in an `mdxjsEsm` node via `getMdastExport`, and prepended to the tree's children array.
```typescript
function getMdastExport(name: string, value: unknown): RootContent {
return {
type: 'mdxjsEsm',
value: '',
data: {
estree: {
type: 'Program',
sourceType: 'module',
body: [
{
type: 'ExportNamedDeclaration',
attributes: [],
specifiers: [],
source: null,
declaration: {
type: 'VariableDeclaration',
kind: 'let',
declarations: [
{
type: 'VariableDeclarator',
id: {
type: 'Identifier',
name,
},
init: valueToEstree(value),
},
],
},
},
],
},
},
};
}
```
Sources: [packages/mdx/src/loaders/mdx/remark-postprocess.ts:128-161](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts#L128-L161)
## Plugin presets and runtime aggregation
### Pipeline Composition and Resolution
Fumadocs provides unified configuration presets that compose default remark and rehype plugin pipelines across different build environments and runtimes. The core package exports bundler and runtime preset factories (`mdxPreset`) alongside an MDX configuration preset (`applyMdxPreset`) that handles environments such as bundler or runtime.
| Preset Function | Package | Environment Context | Default Output Format |
| --------------- | ------- | ------------------- | --------------------- |
| `mdxPreset` | `fumadocs-core/content/mdx/preset-bundler` | Bundler build tools (Next.js, Vite, Webpack) | Unmodified / default |
| `mdxPreset` | `fumadocs-core/content/mdx/preset-runtime` | Local or runtime execution | `function-body` |
| `applyMdxPreset` | `fumadocs/config/preset` | Configurable (`bundler` or `runtime`) | `function-body` (for runtime) |
Sources: [packages/core/src/content/mdx/preset-bundler.ts:26-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L26-L92), [packages/core/src/content/mdx/preset-runtime.ts:23-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L23-L83), [packages/mdx/src/config/preset.ts:50-131](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L131)
The plugin resolution layer accepts user-defined arrays or functions, conditionally appending default remark plugins like `remarkGfm`, `remarkHeading`, `remarkImage`, `remarkCodeTab`, `remarkNpm`, and `remarkStructure`, as well as rehype plugins like `rehypeCode` and `rehypeToc`.
```typescript
const remarkPlugins = await resolvePlugins(
(v) => [
import('remark-gfm').then((mod) => mod.default),
remarkHeadingOptions !== false &&
import('@/mdx-plugins/remark-heading').then((mod) => [
mod.remarkHeading,
{
generateToc: false,
...remarkHeadingOptions,
},
]),
_include ?? false,
remarkImageOptions !== false &&
import('@/mdx-plugins/remark-image').then((mod) => [
mod.remarkImage,
{
...remarkImageOptions,
useImport: remarkImageOptions?.useImport ?? true,
},
]),
remarkCodeTabOptions !== false &&
import('@/mdx-plugins/remark-code-tab').then((mod) => [
mod.remarkCodeTab,
remarkCodeTabOptions,
]),
remarkNpmOptions !== false &&
import('@/mdx-plugins/remark-npm').then((mod) => [mod.remarkNpm, remarkNpmOptions]),
...v,
remarkStructureOptions !== false &&
import('@/mdx-plugins/remark-structure').then((mod) => [
mod.remarkStructure,
{
exportAs: 'structuredData',
...remarkStructureOptions,
} satisfies Plugins.StructureOptions,
]),
],
mdxOptions.remarkPlugins,
);
const rehypePlugins = await resolvePlugins(
(v) => [
rehypeCodeOptions !== false &&
import('@/mdx-plugins/rehype-code').then((mod) => [mod.rehypeCode, rehypeCodeOptions]),
...v,
import('@/mdx-plugins/rehype-toc').then((mod) => mod.rehypeToc),
],
mdxOptions.rehypePlugins,
);
```
Sources: [packages/core/src/content/mdx/preset-bundler.ts:38-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L38-L86)
> [!TIP]
> Setting any preset option to `false` (such as `remarkImageOptions: false` or `rehypeCodeOptions: false`) explicitly disables that specific plugin from the unified pipeline.
> Sources: [packages/core/src/content/mdx/preset-bundler.ts:15-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L15-L20), [packages/core/src/content/mdx/preset-bundler.ts:41-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L41-L73)
### Alternative Runtimes and Vault Compilers
For lightweight markdown rendering and preview components, `createMarkdownCompiler` and `createMarkdownRenderer` instantiate standalone unified processors using `remark`, `remarkRehype`, and user-supplied plugin lists without full MDX compilation baggage.
```typescript
const processor = remark()
.use(remarkPlugins)
.use(remarkRehype, remarkRehypeOptions)
.use(rehypePlugins);
```
Sources: [packages/preview/src/lib/md.ts:37-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts#L37-L40), [packages/core/src/content/md.ts:35-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/md.ts#L35-L38)
Similarly, the Obsidian integration builds a localized unified processor combining vault-specific remark plugins (`remarkWikilinks`, `remarkConvert`, `remarkObsidianComment`, and `remarkBlockId`) to transform vault files into compatible AST structures.
```typescript
export function getRemarkPlugins(storage: VaultStorage, resolver: VaultResolver): PluggableList {
return [
[remarkWikilinks, { resolver, storage }],
[remarkConvert, { resolver, storage }],
remarkObsidianComment,
remarkBlockId,
];
```
Sources: [packages/obsidian/src/remark/index.ts:9-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/index.ts#L9-L15), [packages/obsidian/src/mdx/index.ts:24-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts#L24-L24)
## Related
- [Syntax Highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting)
- [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline)
---
## Technical docs: Framework Routing Adapters
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/framework-routing-adapters
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/core/src/framework/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx)
- [packages/core/src/framework/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx)
- [packages/core/src/framework/react-router.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx)
- [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx)
- [packages/core/src/framework/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx)
- [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx)
- [packages/base-ui/src/provider/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx)
- [packages/core/src/framework/next.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx)
- [packages/radix-ui/src/provider/react-router.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx)
- [packages/radix-ui/src/provider/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/waku.tsx)
- [packages/base-ui/src/provider/react-router.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx)
- [packages/create-app/src/transform/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/transform/index.ts)
- [packages/core/src/dynamic-link.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx)
- [packages/preview/src/waku.server.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/waku.server.tsx)
- [packages/mdx/src/loaders/adapter.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts)
- [packages/base-ui/src/provider/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx)
- [packages/create-app/src/transform/react-router.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/transform/react-router.ts)
- [packages/radix-ui/src/provider/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx)
- [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx)
- [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx)
- [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx)
- [packages/preview/src/components/provider.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/provider.tsx)
- [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json)
- [packages/base-ui/src/provider/next.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/next.tsx)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/radix-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx)
- [packages/radix-ui/src/provider/next.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/next.tsx)
- [packages/asyncapi/src/ui/contexts/api.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/contexts/api.tsx)
- [packages/create-app/src/constants.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/constants.ts)
- [packages/base-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/index.tsx)
## Overview
Framework Routing Adapters provide a unified abstraction layer that decouples Fumadocs UI components from underlying framework-specific routing and navigation primitives. By defining a common contract for path resolution, parameter extraction, and navigation hooks, Fumadocs supports multiple meta-frameworks without binding its core logic to any single ecosystem.
Sources: [packages/core/src/framework/index.tsx:29-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L29-L41)
## Core Framework Abstraction Interface
### Public API Contract and Framework Context
The core abstraction layer defines the structural contract for framework integration in `fumadocs-core`. The `Framework` interface specifies required navigation and routing functions alongside optional component overrides for links and images. A React context initialized via `createContext` stores this interface, defaulting to `notImplemented` stubs that throw an error prompting developers to wrap their application inside `FrameworkProvider`.
```tsx
export interface Router {
push: (url: string) => void | Promise;
refresh: () => void | Promise;
}
export interface Framework {
usePathname: () => string;
useParams: () => Record;
useRouter: () => Router;
Link?: FC<
ComponentProps<'a'> & {
prefetch?: boolean;
}
>;
Image?: FC;
}
const notImplemented = () => {
throw new Error('You need to wrap your application inside `FrameworkProvider`.');
};
const FrameworkContext = createContext({
useParams: notImplemented,
useRouter: notImplemented,
usePathname: notImplemented,
});
```
Sources: [packages/core/src/framework/index.tsx:24-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L24-L51)
| Member | Type | Purpose |
| :--- | :--- | :--- |
| `usePathname` | `() => string` | Returns the current URL pathname string |
| `useParams` | `() => Record` | Extracts dynamic route parameters as a key-value record |
| `useRouter` | `() => Router` | Provides navigation primitives (`push` and `refresh`) |
| `Link` | `FC & { prefetch?: boolean }>` | Optional framework-specific anchor component override |
| `Image` | `FC` | Optional framework-specific image component override |
Sources: [packages/core/src/framework/index.tsx:29-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L29-L41)
> [!WARNING]
> Failing to wrap component trees in `FrameworkProvider` triggers a runtime error when any hook or core component attempts to access framework context, because the default stub functions throw immediately upon invocation.
>
> Sources: [packages/core/src/framework/index.tsx:43-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L43-L51)
### Provider Memoization and Routing Hooks
The `FrameworkProvider` component accepts `Link`, `useRouter`, `useParams`, `usePathname`, `Image`, and `children`. It wraps its children with `FrameworkContext.Provider` (rendered as ``) utilizing `useMemo` to memoize the context object based on its provider dependencies. Individual custom hooks (`usePathname`, `useRouter`, `useParams`) consume this context using React's `use` hook to extract the active framework implementation.
```tsx
export function FrameworkProvider({
Link,
useRouter,
useParams,
usePathname,
Image,
children,
}: Framework & { children: ReactNode }) {
const framework = useMemo(
() => ({
usePathname,
useRouter,
Link,
Image,
useParams,
}),
[Link, usePathname, useRouter, useParams, Image],
);
return {children};
}
export function usePathname() {
return use(FrameworkContext).usePathname();
}
export function useRouter() {
return use(FrameworkContext).useRouter();
}
export function useParams() {
return use(FrameworkContext).useParams();
}
```
Sources: [packages/core/src/framework/index.tsx:53-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L53-L85)
> [!TIP]
> The framework context consumption relies on React's `use` API, allowing hooks to be safely called within consumer components as long as a valid `FrameworkProvider` exists higher in the tree.
>
> Sources: [packages/core/src/framework/index.tsx:75-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L75-L85)
### Component Fallbacks for Images and Links
The core package provides robust fallback implementations for `Image` and `Link` components when no framework-specific override is supplied through the context. The `Image` component checks for a registered context `Image` component; if absent, it falls back to a standard `` element mapping the `priority` boolean prop to a `fetchPriority` attribute (`high` or `auto`). Similarly, the `Link` component falls back to a standard `` element when no framework link implementation is provided, destructuring out the `prefetch` prop to prevent invalid DOM attribute warnings.
```tsx
export function Image(props: ImageProps) {
const { Image } = use(FrameworkContext);
if (!Image) {
const { src, alt, priority, ...rest } = props;
return (
);
}
return ;
}
export function Link(props: LinkProps) {
const { Link } = use(FrameworkContext);
if (!Link) {
const { href, prefetch: _, ...rest } = props;
return ;
}
return ;
}
```
Sources: [packages/core/src/framework/index.tsx:87-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L87-L108)
## Next.js Routing Adapter Implementation
### NextProvider and App Router Primitives
The Next.js framework adapter bridges Next.js App Router navigation hooks and UI components into the core framework context. Defined in `packages/core/src/framework/next.tsx`, the `NextProvider` component marks itself with `'use client'` and passes Next.js routing hooks—`usePathname`, `useRouter`, and `useParams` from `next/navigation`—directly into the underlying `FrameworkProvider`. It also accepts optional custom overrides for `Link` and `Image`, defaulting to `next/link` and `next/image` when custom components are omitted.
```tsx
'use client';
import { type Framework, FrameworkProvider } from '@/framework/index';
import type { ReactNode } from 'react';
import { useParams, usePathname, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
export function NextProvider({
children,
Link: CustomLink,
Image: CustomImage,
}: {
children: ReactNode;
Link?: Framework['Link'];
Image?: Framework['Image'];
}) {
return (
{children}
);
```
Sources: [packages/core/src/framework/next.tsx:1-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx#L1-L27)
| Prop | Type | Default Value | Purpose |
| :--- | :--- | :--- | :--- |
| `children` | `ReactNode` | (Required) | React subtree wrapped by the provider |
| `Link` | `Framework['Link']` | `next/link` | Custom anchor component override |
| `Image` | `Framework['Image']` | `next/image` | Custom image component override |
Sources: [packages/core/src/framework/next.tsx:8-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx#L8-L27)
> [!NOTE]
> `NextProvider` relies on Next.js client-side navigation modules (`next/navigation`, `next/link`, `next/image`), requiring all consuming tree branches to execute within a Client Component boundary (`'use client'`).
>
> Sources: [packages/core/src/framework/next.tsx:1-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx#L1-L6)
### UI Package Integration Wrappers
The Radix UI and Base UI packages provide their own `RootProvider` components that encapsulate `NextProvider` alongside their respective design system providers (`BaseProvider`). Both `packages/base-ui/src/provider/next.tsx` and `packages/radix-ui/src/provider/next.tsx` accept `RootProviderProps` containing a `components` object with optional `Link` and `Image` overrides, forwarding them to `NextProvider` while spreading remaining props into `BaseProvider`.
```tsx
'use client';
import type { ComponentProps } from 'react';
import { RootProvider as BaseProvider } from '@/provider/base';
import { NextProvider } from 'fumadocs-core/framework/next';
import type { Framework } from 'fumadocs-core/framework';
export interface RootProviderProps extends ComponentProps {
/**
* Custom framework components to override Next.js defaults
*/
components?: {
Link?: Framework['Link'];
Image?: Framework['Image'];
};
}
export function RootProvider({ components, ...props }: RootProviderProps) {
return (
{props.children}
);
}
```
Sources: [packages/radix-ui/src/provider/next.tsx:1-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/next.tsx#L1-L23), [packages/base-ui/src/provider/next.tsx:1-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/next.tsx#L1-L22)
> [!TIP]
> By nesting `BaseProvider` inside `NextProvider`, UI packages ensure that design system primitives and documentation layouts access active Next.js routing context and custom component overrides simultaneously.
>
> Sources: [packages/radix-ui/src/provider/next.tsx:17-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/next.tsx#L17-L22), [packages/base-ui/src/provider/next.tsx:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/next.tsx#L17-L21)
## React Router Framework Integration
### Core Bridge and Navigation Hooks
The core React Router adapter translates React Router hooks into the Fumadocs framework interface contract. Located in `packages/core/src/framework/react-router.tsx`, the adapter extracts the current path via `useLocation().pathname` and retrieves route parameters through `useParams()`, casting them to `Record`.
```tsx
const framework: Framework = {
usePathname() {
return useLocation().pathname;
},
useParams() {
return useParams() as Record;
},
```
Sources: [packages/core/src/framework/react-router.tsx:5-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L5-L11)
Navigation actions are wrapped inside a memoized `useRouter` hook that combines `useNavigate` and `useRevalidator`. The `push` method delegates directly to `navigate(url)`, while `refresh` triggers `void revalidator.revalidate()`, with both actions dependent on `[navigate, revalidator]`.
```tsx
useRouter() {
const navigate = useNavigate();
const revalidator = useRevalidator();
return useMemo(
() => ({
push(url) {
navigate(url);
},
refresh() {
void revalidator.revalidate();
},
}),
[navigate, revalidator],
);
},
```
Sources: [packages/core/src/framework/react-router.tsx:12-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L12-L27)
The framework's `Link` implementation maps the generic `href` property to React Router's `to` prop and converts boolean `prefetch` flags into `'intent'` or `'none'` string values.
```tsx
Link({ href, prefetch, ...props }) {
return (
{props.children}
);
},
```
Sources: [packages/core/src/framework/react-router.tsx:28-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L28-L34)
> [!NOTE]
> React Router's `useRevalidator` returns a revalidation state object where `revalidate()` is an asynchronous function; the adapter explicitly voids the returned promise to satisfy lint rules within synchronous callback contexts.
>
> Sources: [packages/core/src/framework/react-router.tsx:21-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L21-L23)
### Provider Wrappers and UI Package Integration
The `ReactRouterProvider` component accepts children alongside optional custom `Link` and `Image` overrides, supplying them to the underlying `FrameworkProvider` by falling back to the default framework implementation when custom components are omitted.
```tsx
export function ReactRouterProvider({
children,
Link: CustomLink,
Image: CustomImage,
}: {
children: ReactNode;
Link?: Framework['Link'];
Image?: Framework['Image'];
}) {
return (
{children}
);
}
```
Sources: [packages/core/src/framework/react-router.tsx:37-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L37-L55)
Both Radix UI and Base UI provide specialized `RootProvider` components that bridge React Router into their respective design system providers. Found in `packages/radix-ui/src/provider/react-router.tsx` and `packages/base-ui/src/provider/react-router.tsx`, these providers accept `RootProviderProps` containing an optional `components` object with `Link` and `Image` properties, forwarding them into `ReactRouterProvider` while spreading remaining props into `BaseProvider`.
```tsx
export interface RootProviderProps extends ComponentProps {
/**
* Custom framework components to override React Router defaults
*/
components?: {
Link?: Framework['Link'];
Image?: Framework['Image'];
};
}
export function RootProvider({ components, ...props }: RootProviderProps) {
return (
{props.children}
);
```
Sources: [packages/radix-ui/src/provider/react-router.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx#L7-L22), [packages/base-ui/src/provider/react-router.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx#L7-L22)
| Prop | Type | Purpose |
| :--- | :--- | :--- |
| `components` | `{ Link?: Framework['Link']; Image?: Framework['Image']; }` | Custom framework components to override React Router defaults |
| `children` | `ReactNode` | React subtree rendered inside the base design system provider |
Sources: [packages/radix-ui/src/provider/react-router.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx#L7-L15), [packages/base-ui/src/provider/react-router.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx#L7-L15)
> [!WARNING]
> UI package root providers for React Router require the `'use client'` directive at the module boundary to ensure React context hooks operate correctly in client-side routing environments.
>
> Sources: [packages/radix-ui/src/provider/react-router.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx#L1-L1), [packages/base-ui/src/provider/react-router.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx#L1-L1)
## TanStack Start Provider Layer
### TanStack Router Hooks and State Ref Caching
The TanStack Start framework integration bridges TanStack Router primitives into Fumadocs via core definitions in `fumadocs-core`. The framework object configures a custom `Link` component mapping `href` to `to` and setting prefetch behavior to `'intent'` when enabled.
```tsx
const framework: Framework = {
Link({ href, prefetch = true, ...props }) {
return (
{props.children}
);
},
```
Sources: [packages/core/src/framework/tanstack.tsx:5-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L5-L12)
The `usePathname` hook leverages `useRouterState` to select both loading status and location pathname. To prevent layout flickering during route transitions, pathname updates use a persistent `useRef` combined with `useMemo` to return the cached active pathname while loading state is true.
```tsx
usePathname() {
const { isLoading, pathname } = useRouterState({
select: (state) => ({
isLoading: state.isLoading,
pathname: state.location.pathname,
}),
});
const activePathname = useRef(pathname);
return useMemo(() => {
if (isLoading) {
return activePathname.current;
}
activePathname.current = pathname;
return pathname;
}, [isLoading, pathname]);
},
```
Sources: [packages/core/src/framework/tanstack.tsx:13-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L13-L30)
> [!NOTE]
> During route transitions when `isLoading` is active, `usePathname` returns the cached reference value rather than the incoming intermediate pathname to maintain stable navigation highlighting.
>
> Sources: [packages/core/src/framework/tanstack.tsx:21-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L21-L29)
Router actions are wrapped inside a memoized `useRouter` hook that invokes TanStack Router's `useRouter`. The `push` method delegates to `router.navigate({ href: url })` while `refresh` calls `router.invalidate()`.
```tsx
useRouter() {
const router = useRouter();
return useMemo(
() => ({
push(url) {
void router.navigate({
href: url,
});
},
refresh() {
void router.invalidate();
},
}),
[router],
);
},
```
Sources: [packages/core/src/framework/tanstack.tsx:31-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L31-L47)
Parameter extraction is handled by `useParams({ strict: false })`, and the entire definition is wrapped by `TanstackProvider` to supply context descendants with framework bindings.
```tsx
useParams() {
return useParams({ strict: false });
},
};
/**
* Fumadocs adapter for Tanstack Router/Start
*/
export function TanstackProvider({
children,
Link: CustomLink,
Image: CustomImage,
}: {
children: ReactNode;
Link?: Framework['Link'];
Image?: Framework['Image'];
}) {
return (
{children}
);
}
```
Sources: [packages/core/src/framework/tanstack.tsx:48-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L48-L74)
### UI Package Root Providers
Both Base UI and Radix UI expose client-side `RootProvider` components that incorporate `TanstackProvider` from `fumadocs-core`. These providers accept optional component overrides for `Link` and `Image` within a `components` prop.
```tsx
export interface RootProviderProps extends ComponentProps {
/**
* Custom framework components to override Tanstack Router defaults
*/
components?: {
Link?: Framework['Link'];
Image?: Framework['Image'];
};
}
export function RootProvider({ components, ...props }: RootProviderProps) {
return (
{props.children}
);
```
Sources: [packages/base-ui/src/provider/tanstack.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx#L7-L22), [packages/radix-ui/src/provider/tanstack.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx#L7-L22)
| Prop | Type | Purpose |
| :--- | :--- | :--- |
| `components` | `{ Link?: Framework['Link']; Image?: Framework['Image']; }` | Custom framework components to override TanStack Router defaults |
| `children` | `ReactNode` | React subtree rendered inside the design system provider |
Sources: [packages/base-ui/src/provider/tanstack.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx#L7-L15), [packages/radix-ui/src/provider/tanstack.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx#L7-L15)
> [!WARNING]
> Both package root provider files require the `'use client'` directive at the top of the module to operate correctly within React client component trees.
>
> Sources: [packages/base-ui/src/provider/tanstack.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx#L1-L1), [packages/radix-ui/src/provider/tanstack.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx#L1-L1)
## Waku Minimal Router Adapter
### Waku Router Context Bindings and Framework Definitions
The Waku minimal router adapter connects Waku routing primitives into Fumadocs through core definitions in `fumadocs-core`. The framework object implements `usePathname` by calling Waku's `useRouter().path`, while `useParams` returns an empty object memoized with `useMemo` accompanied by a console warning.
```tsx
const framework: Framework = {
usePathname() {
return useRouter().path;
},
useParams() {
console.warn('[Fumadocs] useParams() is not supported on Waku');
return useMemo(() => ({}), []);
},
```
Sources: [packages/core/src/framework/waku.tsx:7-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L7-L14)
> [!WARNING]
> The `useParams` hook on Waku emits a console warning (`[Fumadocs] useParams() is not supported on Waku`) and returns an empty object because route parameters are accessed directly via page props rather than context hooks.
>
> Sources: [packages/core/src/framework/waku.tsx:11-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L11-L14)
Navigation actions are wrapped inside a memoized `useRouter` hook that caches the router instance using a `useRef`. The returned object provides `push(url)` delegating to `routerRef.current.push(url)` and `refresh()` calling `routerRef.current.reload()`.
```tsx
useRouter() {
const router = useRouter();
const routerRef = useRef(router);
routerRef.current = router;
return useMemo(
() => ({
push(url: string) {
return routerRef.current.push(url);
},
refresh() {
return routerRef.current.reload();
},
}),
[],
);
},
```
Sources: [packages/core/src/framework/waku.tsx:15-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L15-L31)
The framework `Link` component maps Fumadocs link properties to Waku's `Link` element, translating `href` to `to` and setting `unstable_prefetchOnEnter` to the `prefetch` boolean value defaulting to `true`.
```tsx
Link({ href, prefetch = true, ...props }) {
return (
{props.children}
);
},
};
```
Sources: [packages/core/src/framework/waku.tsx:32-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L32-L39)
The `WakuProvider` component wraps `FrameworkProvider`, accepting optional custom `Link` and `Image` overrides and falling back to the framework defaults.
```tsx
export function WakuProvider({
children,
Link: CustomLink,
Image: CustomImage,
}: {
children: ReactNode;
Link?: Framework['Link'];
Image?: Framework['Image'];
}) {
return (
{children}
);
}
```
Sources: [packages/core/src/framework/waku.tsx:41-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L41-L59)
### UI Provider Wrappers and Preview Integration
Both Base UI and Radix UI expose client-side `RootProvider` components specifically adapted for Waku. These components wrap children with `WakuProvider` and `BaseProvider`, accepting an optional `components` object to override `Link` and `Image`.
```tsx
export interface RootProviderProps extends ComponentProps {
/**
* Custom framework components to override Waku defaults
*/
components?: {
Link?: Framework['Link'];
Image?: Framework['Image'];
};
}
export function RootProvider({ components, ...props }: RootProviderProps) {
return (
{props.children}
);
```
Sources: [packages/base-ui/src/provider/waku.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx#L7-L22), [packages/radix-ui/src/provider/waku.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/waku.tsx#L7-L22)
| Prop | Type | Purpose |
| :--- | :--- | :--- |
| `components` | `{ Link?: Framework['Link']; Image?: Framework['Image']; }` | Custom framework components to override Waku defaults |
| `children` | `ReactNode` | React subtree rendered inside the design system provider |
Sources: [packages/base-ui/src/provider/waku.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx#L7-L15), [packages/radix-ui/src/provider/waku.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/waku.tsx#L7-L15)
The preview application leverages `fumadocs-ui/provider/waku` within its client provider component and configures dynamic routing inside `[...slugs].tsx`. The markdown compiler processes documents with remark plugins including `remarkGfm`, `remarkMath`, `remarkMdxMermaid`, `remarkHeading`, `remarkNpm`, and `remarkCodeTab`, alongside rehype plugins for `rehypeKatex`, `rehypeCode`, and `rehypeToc`.
```tsx
const compiler = createMarkdownCompiler({
remarkPlugins: [
remarkGfm,
remarkMath,
remarkMdxMermaid,
plugin(remarkHeading, { generateToc: false }),
plugin(remarkNpm, { persist: { id: 'package-manager' } }),
remarkCodeTab,
],
remarkRehypeOptions: {
passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'],
},
rehypePlugins: [
rehypeKatex,
plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }),
plugin(rehypeToc, { exportToc: { as: 'data' } }),
],
});
```
Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46)
> [!NOTE]
> The preview application uses dynamic configuration (`getConfig` returning `render: 'dynamic'`) and dynamically selects between `docs` and `flux` layout presets based on runtime configuration settings.
>
> Sources: [packages/preview/src/pages/[...slugs].tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L76-L96), [packages/preview/src/pages/[...slugs].tsx:225-229](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L225-L229)
## Dynamic Links and Active Navigation
### Dynamic Link Href Resolution
The `DynamicLink` component extends standard navigation links by substituting route parameters into templated path strings at runtime. By retrieving active route parameters through the `useParams` hook, `DynamicLink` computes updated URLs via `useMemo` before rendering the underlying `Link` element.
```tsx
export const DynamicLink = forwardRef(
({ href, ...props }, ref) => {
const params = useParams();
const url = useMemo(() => (href ? updateHref(href, params) : href), [params, href]);
return ;
},
);
```
Sources: [packages/core/src/dynamic-link.tsx:15-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L15-L23)
The underlying `updateHref` function parses parameter placeholders using regular expressions. If a matching key exists within the parameter dictionary, it substitutes the value—joining array segments with slashes if necessary—and preserves trailing slashes from the template pattern.
```tsx
export function updateHref(href: string, params: Record) {
return href.replace(/\[(.*)]\/?/, (match, key) => {
const hasEndingSlash = match[match.length - 1] === '/';
const value = key in params ? params[key] : undefined;
if (!value) return '';
const replacement = typeof value === 'string' ? value : value.join('/');
return hasEndingSlash ? `${replacement}/` : replacement;
});
}
```
Sources: [packages/core/src/dynamic-link.tsx:27-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L27-L36)
> [!WARNING]
> If a route parameter placeholder lacks a matching key in the `params` record, `updateHref` evaluates `value` as undefined and returns an empty string for that segment.
>
> Sources: [packages/core/src/dynamic-link.tsx:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L30-L31)
### Active Navigation and Layout Tabs
Layout structures determine active states for navigation links and folder tabs by evaluating the current pathname against registered URLs and page tree nodes. The `isLinkItemActive` function inspects link configuration objects, immediately returning `false` for custom item types or entries configured with `active: 'none'`.
```tsx
export function updateHref(href: string, params: Record) {
return href.replace(/\[(.*)]\/?/, (match, key) => {
const hasEndingSlash = match[match.length - 1] === '/';
const value = key in params ? params[key] : undefined;
if (!value) return '';
const replacement = typeof value === 'string' ? value : value.join('/');
return hasEndingSlash ? `${replacement}/` : replacement;
});
}
```
Sources: [packages/core/src/dynamic-link.tsx:27-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L27-L36)
Layout tabs generated from page tree structures evaluate active states by searching folder hierarchies for matching child page URLs or checking explicit URL sets and normalized path comparisons.
```tsx
export function isLayoutTabActive(tab: LayoutTab, pathname: string) {
if (tab.$folder) {
return (
PageTree.findPath(
tab.$folder.children,
(node) => node.type === 'page' && isActive(node.url, pathname),
) !== null
);
}
if (tab.urls) {
return tab.urls.has(normalize(pathname));
}
return isActive(tab.url, pathname, true);
}
```
Sources: [packages/radix-ui/src/layouts/shared/index.tsx:146-161](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L146-L161)
| Property | Type | Default | Purpose |
| :--- | :--- | :--- | :--- |
| `active` | `'url' \| 'nested-url' \| 'none'` | `'url'` | Defines active state matching criteria for navigation items |
| `url` | `string` | — | Target destination URL for navigation and link resolution |
| `external` | `boolean` | `false` | Indicates whether the link points to an external resource |
| `on` | `'menu' \| 'nav' \| 'all'` | `'all'` | Restricts where link items are rendered within the layout |
Sources: [packages/radix-ui/src/layouts/shared/index.tsx:163-181](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L163-L181)
## Related
- [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture)
---
## Technical docs: Internationalization Support
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/internationalization-support
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/base-ui/src/contexts/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx)
- [packages/language/src/zh-tw.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-tw.ts)
- [packages/radix-ui/src/contexts/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx)
- [packages/base-ui/src/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx)
- [packages/language/src/zh-cn.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-cn.ts)
- [packages/radix-ui/src/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/i18n.tsx)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/base-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx)
- [packages/core/src/source/page-tree/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts)
- [packages/base-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/index.tsx)
- [packages/core/src/source/llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/llms.ts)
- [packages/radix-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx)
- [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx)
- [packages/core/src/i18n/middleware.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts)
- [packages/base-ui/src/layouts/shared/slots/language-select.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx)
- [packages/base-ui/src/layouts/flux/page/slots/footer.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx)
- [packages/radix-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx)
- [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts)
- [packages/base-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts)
- [packages/radix-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts)
- [packages/api-docs/src/i18n.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/i18n.ts)
- [packages/radix-ui/src/layouts/shared/slots/language-select.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx)
- [packages/core/src/source/page-tree/transformer-fallback.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts)
- [packages/openapi/src/i18n.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts)
- [packages/preview/src/components/provider.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/provider.tsx)
- [packages/epub/src/toc-builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/src/toc-builder.ts)
- [packages/preview/src/layouts/config.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/layouts/config.tsx)
- [packages/asyncapi/src/i18n.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/i18n.ts)
- [packages/base-ui/src/layouts/home/not-found.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/home/not-found.tsx)
- [packages/radix-ui/src/layouts/home/not-found.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/not-found.tsx)
## Overview
Fumadocs provides comprehensive internationalization support for multi-language documentation projects, coordinating server-side locale negotiation, request proxy middleware, and client React context providers. It bridges server-rendered storage collections with reactive UI components, enabling seamless language switching, localized navigation trees, and extensible translation dictionaries across base and Radix UI layouts.
Sources: [packages/core/src/i18n/middleware.ts:56-110](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L56-L110), [packages/base-ui/src/contexts/i18n.tsx:33-72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L33-L72), [packages/radix-ui/src/contexts/i18n.tsx:49-89](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L49-L89), [packages/base-ui/src/i18n.tsx:52-71](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx#L52-L71), [packages/core/src/source/loader.ts:303-346](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L303-L346)
## Routing Middleware and Negotiation
### Middleware Options and URL Formatting
The `createI18nMiddleware` function generates a Next.js proxy middleware to handle internationalization routing, language detection, and header negotiation based on `MiddlewareOptions` and core `I18nConfig`.
```typescript
interface MiddlewareOptions extends I18nConfig {
format?: URLFormatter | ((locale: string, pathname: string) => string);
cookieName?: string;
}
export interface URLFormatter {
get: (url: NextURL) => string | undefined;
add: (url: NextURL, locale: string) => URL;
remove: (url: NextURL) => URL;
}
```
Sources: [packages/core/src/i18n/middleware.ts:7-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L7-L36)
| Option / Method | Type | Default | Purpose |
| :--- | :--- | :--- | :--- |
| `languages` | `string[]` | *Required* | Supported language codes for the project |
| `defaultLanguage` | `string` | *Required* | Fallback language used when negotiation fails or matches defaults |
| `format` | `URLFormatter \| Function` | `DefaultFormatter` | Formatter object or custom function to add, remove, or retrieve locale prefixes |
| `cookieName` | `string` | `'FD_LOCALE'` | Cookie key storing the active locale when `hideLocale` is set to `'always'` |
| `hideLocale` | `'never' \| 'always' \| 'default-locale'` | `'never'` | Strategy for hiding locale segments in the request pathname |
| `URLFormatter.get` | `(url: NextURL) => string \| undefined` | *DefaultFormatter* | Extracts the locale segment from the request URL pathname |
| `URLFormatter.add` | `(url: NextURL, locale: string) => URL` | *DefaultFormatter* | Inserts the locale prefix and project base path into the URL |
| `URLFormatter.remove` | `(url: NextURL) => URL` | *DefaultFormatter* | Strips the explicit locale segment from the URL pathname |
Sources: [packages/core/src/i18n/middleware.ts:38-75](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L38-L75)
### Request Routing and Negotiation Flow
When a request enters the proxy middleware, the handler extracts the current path locale using `formatter.get(url)`. If the extracted segment is not present in the configured `languages` array, it is treated as undefined.
```typescript
export const DefaultFormatter: URLFormatter = {
get(url) {
const segs = url.pathname.split('/');
if (segs.length > 1 && segs[1]) return segs[1];
},
add(url, locale) {
const next = new URL(url);
next.pathname = `${url.basePath}/${locale}/${url.pathname}`.replaceAll(/\/+/g, '/');
return next;
},
remove(url) {
const next = new URL(url);
const pathname = url.pathname.split('/').slice(2).join('/');
next.pathname = `${url.basePath}/${pathname}`.replaceAll(/\/+/g, '/');
return next;
},
};
```
Sources: [packages/core/src/i18n/middleware.ts:38-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L38-L54)
Depending on the configured `hideLocale` strategy, requests without a valid path locale trigger different routing behaviors:
- If `hideLocale` is `'default-locale'`, the middleware rewrites the request to the URL formatted with `defaultLanguage`.
- If `hideLocale` is `'always'`, it retrieves the locale from the request cookie specified by `cookieName`, falling back to language negotiation via `@formatjs/intl-localematcher` and `getNegotiator`, then rewrites to the formatted URL.
- Otherwise, it issues an HTTP redirect to the preferred negotiated locale URL.
```typescript
if (!pathLocale) {
if (hideLocale === 'default-locale') {
return NextResponse.rewrite(formatter.add(url, defaultLanguage));
}
const finalLanguages = getNegotiator(request).languages(languages);
const preferred = matchLocale(finalLanguages, languages, defaultLanguage);
if (hideLocale === 'always') {
const locale = request.cookies.get(cookieName)?.value ?? preferred;
return NextResponse.rewrite(formatter.add(url, locale));
}
return NextResponse.redirect(formatter.add(url, preferred));
}
```
Sources: [packages/core/src/i18n/middleware.ts:82-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L82-L96)
> [!WARNING]
> When `hideLocale` is set to `'always'` or `'default-locale'` (when matching the default language), explicit locale prefixes in the URL are stripped via `formatter.remove(url)` and a redirect response is returned while simultaneously persisting the active locale code into the `cookieName` cookie.
Sources: [packages/core/src/i18n/middleware.ts:98-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L98-L106)
## Client Context and Localization Hooks
### Translation APIs and Configuration Helpers
Client-side internationalization relies on React context providers and navigation hooks implemented identically across both `packages/base-ui` and `packages/radix-ui`. The `LocaleContext` supplies active locale state, available language items, and an `onChange` updater function accessed through the `useI18n` hook.
```typescript
interface LocaleItem {
name: string;
locale: string;
}
interface LocaleContextType {
locale?: string;
onChange?: (v: string) => void;
locales?: LocaleItem[];
}
const LocaleContext = createContext({});
export function useI18n(): LocaleContextType {
return use(LocaleContext);
}
```
Sources: [packages/base-ui/src/contexts/i18n.tsx:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L6-L21), [packages/radix-ui/src/contexts/i18n.tsx:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L6-L21)
The `I18nProvider` component wraps application trees with both `LocaleContext` and `@fuma-translate/react`'s `TranslationProvider`. When `onLocaleChange` is omitted, the provider's built-in locale switcher mutates the current pathname by replacing or prepending the target language segment before calling `router.push`.
```typescript
export function I18nProvider({
locales = [],
locale,
onLocaleChange,
children,
translations = Empty,
}: I18nProviderProps) {
const router = useRouter();
const pathname = usePathname();
const onChange = (value: string) => {
if (onLocaleChange) {
return onLocaleChange(value);
}
const segments = pathname.split('/').filter((v) => v.length > 0);
if (segments.length === 0 || segments[0] !== locale) {
segments.unshift(value);
} else {
segments[0] = value;
}
router.push(`/${segments.join('/')}`);
};
```
Sources: [packages/base-ui/src/contexts/i18n.tsx:33-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L33-L55), [packages/radix-ui/src/contexts/i18n.tsx:49-72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L49-L72)
> [!NOTE]
> `I18nProvider` maintains an `onChangeRef` synchronized with the latest `onChange` callback on every render, ensuring stable memoized context references passed to descendant components.
Sources: [packages/base-ui/src/contexts/i18n.tsx:56-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L56-L69), [packages/radix-ui/src/contexts/i18n.tsx:73-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L73-L86)
Helper functions in `packages/base-ui/src/i18n.tsx` and `packages/radix-ui/src/i18n.tsx` bridge core translation dictionaries with UI provider properties. The `uiTranslations` extension injects localized UI keys, while `i18nProvider` resolves language fallbacks and maps supported language codes to display names.
| Function / Helper | Signature | Purpose |
| :--- | :--- | :--- |
| `uiTranslations` | `() => TranslationExtension` | Returns compiled UI translation keys from package assets |
| `i18nProvider` | `(translations, lang?) => I18nProviderProps` | Generates provider properties including locale, translations, and mapped `locales` array |
| `defineI18nUI` | `(config, localeTranslations) => I18nUIConfig` | Extends an `I18nConfig` object with a custom `provider` factory method |
Sources: [packages/base-ui/src/i18n.tsx:12-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx#L12-L46), [packages/radix-ui/src/i18n.tsx:12-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/i18n.tsx#L12-L46)
> [!WARNING]
> When resolving language display names in `i18nProvider`, the implementation defaults to `'English'` if `t.get(code).displayName` is undefined.
Sources: [packages/base-ui/src/i18n.tsx:35-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx#L35-L39), [packages/radix-ui/src/i18n.tsx:35-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/i18n.tsx#L35-L39)
## Language Selection Interface Components
### Language Switcher and Popover Presentation
The `LanguageSelect` component provides an interactive dropdown interface using primitive popover components. It retrieves the active language context via `useI18n()` and throws an error if `context.locales` is uninitialized. The trigger element renders with configurable button variants and applies an accessibility label through `@fuma-translate/react`.
```tsx
export function LanguageSelect({
className,
variant = 'ghost',
children,
...rest
}: LanguageSelectProps): React.ReactElement {
const context = useI18n();
const t = useTranslations({ note: 'language switcher' });
if (!context.locales) throw new Error('Missing ``');
const chooseLanguage = t('Choose a language');
return (
cn(buttonVariants({ variant }), 'gap-1.5 p-1.5', s.open && 'bg-fd-accent', className)
}
{...rest}
>
{children}
{chooseLanguage}
```
Sources: [packages/base-ui/src/layouts/shared/slots/language-select.tsx:14-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx#L14-L38)
```tsx
export function LanguageSelect({
className,
variant = 'ghost',
children,
...rest
}: LanguageSelectProps): React.ReactElement {
const context = useI18n();
const t = useTranslations({ note: 'language switcher' });
if (!context.locales) throw new Error('Missing ``');
const chooseLanguage = t('Choose a language');
return (
{children}
{chooseLanguage}
```
Sources: [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:14-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L14-L40)
> [!WARNING]
> Both package implementations require a parent ``; omitting the provider causes `LanguageSelect` to throw an error immediately during render when `context.locales` is missing.
Sources: [packages/base-ui/src/layouts/shared/slots/language-select.tsx:22-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx#L22-L22), [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:22-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L22-L22)
### Locale Selection and Text Display
Inside the popover content, available locales are mapped into interactive buttons. Clicking an item triggers `context.onChange?.(item.locale)` to update the active language. The currently active locale receives distinct styling (`bg-fd-primary/10 text-fd-primary`), while unselected options display muted foreground colors with hover states.
```tsx
{context.locales.map((item) => (
))}
```
Sources: [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:39-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L39-L58)
The companion `LanguageSelectText` component extracts the display name of the currently active locale from the i18n context and renders it inside a span element.
```tsx
export type LanguageSelectTextProps = ComponentProps<'span'>;
export function LanguageSelectText(props: LanguageSelectTextProps) {
const { locales, locale } = useI18n();
const text = locales?.find((item) => item.locale === locale)?.name;
return {text};
}
```
Sources: [packages/base-ui/src/layouts/shared/slots/language-select.tsx:61-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx#L61-L68)
```tsx
export type LanguageSelectTextProps = ComponentProps<'span'>;
export function LanguageSelectText(props: LanguageSelectTextProps) {
const { locales, locale } = useI18n();
const text = locales?.find((item) => item.locale === locale)?.name;
return {text};
}
```
Sources: [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:63-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L63-L70)
## Translation Presets and Extension Schemas
### Structured Dictionary Bundles and Extension Extensions
Fumadocs structures internationalization dictionaries by combining base UI translations with extension tokens from specialized domain packages. Packages like `@fumadocs/api-docs`, `fumadocs-openapi`, and `@fumadocs/asyncapi` export dedicated translation extension functions that load compiled JSON translation keys and return a `TranslationExtension` object matching `keyof Translations`. For instance, `apiDocsTranslations()` reads from `@/.translations/keys.json` to yield typed translation keys for schema UIs and playgrounds.
```typescript
import translationKeys from '@/.translations/keys.json';
import type { TranslationExtension } from 'fumadocs-core/i18n';
import type { Translations } from '@/.translations';
export type { Translations };
export function apiDocsTranslations(): TranslationExtension {
return { keys: translationKeys as never };
}
```
Sources: [packages/api-docs/src/i18n.ts:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/i18n.ts#L1-L8)
Domain-specific packages such as `openapiTranslations()` and `asyncapiTranslations()` compose their own translation keys with shared schema UI keys by invoking `apiDocsTranslations()` internally and spreading both key arrays into a unified extension object.
```typescript
import translationKeys from '@/.translations/keys.json';
import type { TranslationExtension } from 'fumadocs-core/i18n';
import type { Translations } from '@/.translations';
import {
type Translations as SharedTranslations,
apiDocsTranslations,
} from '@fumadocs/api-docs/i18n';
export type { Translations };
export function openapiTranslations(): TranslationExtension<
keyof Translations | keyof SharedTranslations
> {
const shared = apiDocsTranslations();
return { keys: [...shared.keys, ...translationKeys] as never };
}
```
Sources: [packages/openapi/src/i18n.ts:1-16](https://github.com/blade47/fumadox/blob/HEAD/packages/openapi/src/i18n.ts#L1-L16), [packages/asyncapi/src/i18n.ts:1-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/i18n.ts#L1-L15)
> [!NOTE]
> The `openapiTranslations()` function merges shared schema translation keys from `@fumadocs/api-docs` with OpenAPI-specific keys, ensuring schema UI components and playground controls resolve their labels correctly in multilingual builds.
> Sources: [packages/openapi/src/i18n.ts:11-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts#L11-L16)
### Multilingual Bundling and Legacy Configuration
Multilingual dictionary bundling is illustrated by comprehensive locale definitions such as Traditional Chinese (`zh-tw.ts`) and Simplified Chinese (`zh-cn.ts`). These language files aggregate type definitions across all dependent packages and supply localized strings for user interfaces, API playgrounds, OpenAPI operations, and AsyncAPI channels.
```typescript
import type { TranslationPreset } from 'fumadocs-core/i18n';
import type { Translations as UITranslations } from 'fumadocs-ui/i18n';
import type { Translations as OpenAPITranslations } from 'fumadocs-openapi/i18n';
import type { Translations as AsyncAPITranslations } from '@fumadocs/asyncapi/i18n';
import type { Translations as StoryTranslations } from '@fumadocs/story/i18n';
import type { Translations as APIDocsTranslations } from '@fumadocs/api-docs/i18n';
type Translations = UITranslations &
OpenAPITranslations &
AsyncAPITranslations &
StoryTranslations &
APIDocsTranslations;
```
Sources: [packages/language/src/zh-tw.ts:1-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-tw.ts#L1-L12), [packages/language/src/zh-cn.ts:1-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-cn.ts#L1-L12)
For backward compatibility with legacy setups, `defineI18nOpenAPI` wraps an existing `I18nUIConfig` instance, overriding its `provider` method to inject partial translation dictionaries for specific locales dynamically during runtime localization lookup.
```typescript
export function defineI18nOpenAPI(
config: I18nUIConfig,
translations: Partial, Partial>>,
): I18nUIConfig {
return {
...config,
provider(locale = config.defaultLanguage) {
const out = config.provider(locale);
const data = translations[locale as Languages];
if (data) {
out.translations = { ...out.translations, ...data };
}
return out;
},
};
}
```
Sources: [packages/openapi/src/i18n.ts:19-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts#L19-L33)
> [!WARNING]
> The `defineI18nOpenAPI` helper is marked as deprecated; developers are advised to use `i18n.translations()` combined with `openapiTranslations()` instead of wrapping the i18n UI configuration object.
> Sources: [packages/openapi/src/i18n.ts:18-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts#L18-L18)
## Localized Tree Navigation and Pagination
### Tree Context Resolution and Active Page Traversal
The `TreeContextProvider` component initializes tree navigation by wrapping raw page trees and resolving active hierarchies. It tracks the current location via `usePathname()` and computes the active breadcrumb path by invoking `searchPath(tree.children, pathname)`, falling back to `tree.fallback?.children` if necessary.
```typescript
export function TreeContextProvider({
tree: rawTree,
children,
}: {
tree: PageTree.Root;
children: ReactNode;
}) {
const nextIdRef = useRef(0);
const pathname = usePathname();
const tree = useMemo(() => rawTree, [rawTree.$id]);
const path = useMemo(() => {
return (
searchPath(tree.children, pathname) ??
(tree.fallback ? searchPath(tree.fallback.children, pathname) : null) ??
[]
);
}, [tree, pathname]);
const root = path.findLast((item) => item.type === 'folder' && item.root) ?? tree;
root.$id ??= String(nextIdRef.current++);
return (
({ root, full: tree }) as TreeContextType, [root, tree])}>
{children}
);
}
```
Sources: [packages/base-ui/src/contexts/tree.tsx:17-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx#L17-L47), [packages/radix-ui/src/contexts/tree.tsx:17-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L17-L47)
> [!NOTE]
> Object-typed tree props passed from Server Components can be re-constructed across renders, breaking hook dependencies. `TreeContextProvider` mitigates this by memoizing on `rawTree.$id` and assigning a fallback identifier using `nextIdRef` if `$id` is uninitialized.
> Sources: [packages/base-ui/src/contexts/tree.tsx:27-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx#L27-L40), [packages/radix-ui/src/contexts/tree.tsx:27-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L27-L40)
### Footer Pagination Linking Across Page Trees
The `useFooterItems()` hook flattens the active tree root into a linear sequence of non-external page nodes, caching the result in a `WeakMap` indexed by `PageTree.Root` or `PageTree.Folder`. Folder index nodes are traversed first before processing child entries.
```typescript
const footerCache = new WeakMap();
export function useFooterItems(): PageTree.Item[] {
const { root } = useTreeContext();
const cached = footerCache.get(root);
if (cached) return cached;
const list: PageTree.Item[] = [];
function onNode(node: PageTree.Node) {
if (node.type === 'folder') {
if (node.index) onNode(node.index);
for (const child of node.children) onNode(child);
} else if (node.type === 'page' && !node.external) {
list.push(node);
}
}
for (const child of root.children) onNode(child);
footerCache.set(root, list);
return list;
}
```
Sources: [packages/base-ui/src/utils/use-footer-items.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts#L5-L27), [packages/radix-ui/src/utils/use-footer-items.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L5-L27)
The `Footer` component consumes this flattened array, locating the active index via `isActive(item.url, pathname)` to supply previous and next page references for pagination links.
```typescript
export function Footer({ items, children, className, ...props }: FooterProps) {
const footerList = useFooterItems();
const pathname = usePathname();
const { previous, next } = useMemo(() => {
if (items) return items;
const idx = footerList.findIndex((item) => isActive(item.url, pathname));
if (idx === -1) return {};
return {
previous: footerList[idx - 1],
next: footerList[idx + 1],
};
}, [footerList, items, pathname]);
return (
<>
{previous && }
{next && }
{children}
>
);
}
```
Sources: [packages/base-ui/src/layouts/flux/page/slots/footer.tsx:25-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx#L25-L56)
## Related
- [Page Tree Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation)
- [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture)
---
## Technical docs: MDX Loader Pipeline
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts)
- [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts)
- [packages/mdx/src/bun/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts)
- [packages/mdx/src/rolldown/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts)
- [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts)
- [packages/mdx/src/loaders/mdx/build-mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts)
- [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts)
- [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts)
- [packages/mdx-remote/src/compile.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts)
- [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts)
- [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
- [packages/mdx/src/node/_loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts)
- [packages/mdx/src/webpack/mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts)
- [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts)
- [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx)
- [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts)
- [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts)
- [packages/mdx/src/loaders/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts)
- [packages/mdx/src/node/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/loader.ts)
- [packages/mdx/src/config/preset.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts)
- [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx)
- [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts)
- [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json)
- [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts)
- [packages/core/src/content/mdx/preset-runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts)
- [packages/core/src/mdx-plugins/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts)
## Overview
The MDX loader pipeline handles content transformation and bundling within [Bundler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins), [Content Compiler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins), and [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) integrations. It processes documentation source files through unified processors, applying remark and rehype transformations to generate type-safe modules and structured outputs.
Sources: [packages/mdx/src/loaders/mdx/index.ts:25-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L108), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L122)
## MDX Loader Factory and Entrypoints
### Loader Factory and Query Validation
The `createMdxLoader` factory function receives a `ConfigLoader` and returns a standard `Loader` object that tests files against `mdxLoaderGlob`. During the `load` execution, query parameters are validated via `querySchema`, which parses loose objects with default options: `only` (`frontmatter` or `all`), `collection`, and `workspace`. If a workspace identifier is provided, the core instance is retrieved from `core.getWorkspaces()`.
```typescript
const querySchema = z.looseObject({
only: z.literal(['frontmatter', 'all']).default('all'),
collection: z.string().optional(),
workspace: z.string().optional(),
});
```
Sources: [packages/mdx/src/loaders/mdx/index.ts:11-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L11-L15)
> [!NOTE]
> When `only` is set to `frontmatter`, the loader skips MDX compilation entirely and returns a serialized export of the parsed frontmatter data directly.
Sources: [packages/mdx/src/loaders/mdx/index.ts:81-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L81-L86)
Build caching can be enabled under production environments when `experimentalBuildCache` is set in global configuration. The loader checks disk cache entries using an MD5 hash of the file path and compares content hashes to avoid redundant compilations.
Sources: [packages/mdx/src/loaders/mdx/index.ts:39-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L39-L60)
Sources: [packages/mdx/src/loaders/mdx/index.ts:25-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L60)
### Node Entrypoints and Execution Sequence
Node.js module loading integration is provided via `initialize` and `load` hooks in `packages/mdx/src/node/_loader.ts`, as well as a deprecated legacy loader export in `packages/mdx/src/node/loader.ts`. The modern module loader initializes a core instance with the `node-loader` environment and builds standalone configuration loaders before wrapping MDX and meta loaders for Node.
Sources: [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29), [packages/mdx/src/node/loader.ts:8-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/loader.ts#L8-L27)
```mermaid
sequenceDiagram
participant _loader.ts
participant index.ts (mdx)
participant build-mdx.ts
_loader.ts->>index.ts (mdx): 1. initialize()
index.ts (mdx)->>index.ts (mdx): 2. createMdxLoader()
index.ts (mdx)->>build-mdx.ts: 3. buildMDX()
build-mdx.ts->>build-mdx.ts: 4. getProcessor()
```
Sources: [packages/mdx/src/loaders/mdx/index.ts:25-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L28), [packages/mdx/src/node/_loader.ts:11-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L25), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L81)
The pipeline execution sequence flows through specific functions during document loading:
1. `initialize` — Sets up the core configuration and hooks in `packages/mdx/src/node/_loader.ts`.
Sources: [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29)
2. `createMdxLoader` — Instantiates the loader object and parses query parameters and frontmatter in `packages/mdx/src/loaders/mdx/index.ts`.
Sources: [packages/mdx/src/loaders/mdx/index.ts:25-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L32)
3. `buildMDX` — Coordinates VFile preparation, custom transformations, and compiler invocation in `packages/mdx/src/loaders/mdx/build-mdx.ts`.
Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121)
4. `getProcessor` — Retrieves or creates a cached Unified processor instance configured with remark and postprocess plugins in `packages/mdx/src/loaders/mdx/build-mdx.ts`.
Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:81-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L81-L108)
Sources: [packages/mdx/src/loaders/mdx/index.ts:25-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L32), [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121)
## MDX Compilation with Unified Processors
### Call-Chain Execution Walkthrough and Sequence
The execution trace for building and compiling MDX content flows through four primary stages, invoking specific functions in sequence: `loader` → `createMdxLoader` → `buildMDX` → `getProcessor`.
1. `loader` — The Webpack or bundler adapter receives raw file content and calls the asynchronous loader callback function.
Sources: [packages/mdx/src/webpack/mdx.ts:9-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts#L9-L28)
2. `createMdxLoader` — Parses query parameters, reads frontmatter, checks build caches, and calls `buildMDX` with the adjusted source string and compiler context.
Sources: [packages/mdx/src/loaders/mdx/index.ts:28-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L28-L97)
3. `buildMDX` — Initializes a `VFile` instance with the source string, file path, and embedded custom properties like `_getProcessor`, applies collection-level transforms via `transformVFile`, and invokes the processor.
Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121)
4. `getProcessor` — Retrieves or instantiates a cached Unified processor using `@mdx-js/mdx` configured with `remarkInclude`, user remark plugins, and `remarkPostprocess`.
Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:81-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L81-L108)
```mermaid
sequenceDiagram
participant mdx.ts (webpack)
participant index.ts (mdx)
participant build-mdx.ts
mdx.ts (webpack)->>index.ts (mdx): loader()
index.ts (mdx)->>build-mdx.ts: buildMDX()
build-mdx.ts->>build-mdx.ts: getProcessor()
```
Sources: [packages/mdx/src/webpack/mdx.ts:9-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts#L9-L28), [packages/mdx/src/loaders/mdx/index.ts:88-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L88-L97), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121)
### Compiler Options and Data Types
| Property | Type | Purpose |
| :--- | :--- | :--- |
| `filePath` | `string` | Specifies the absolute or relative file path for the source document being compiled. |
| `source` | `string` | Raw markdown or MDX content string, offset by frontmatter newline counts. |
| `environment` | `'bundler' \| 'runtime'` | Defines the target execution environment for MDX configuration loading. |
| `isDevelopment` | `boolean` | Flags whether development mode is active, toggling debug features in `@mdx-js/mdx`. |
| `_compiler` | `CompilerOptions` | Optional compiler reference supplying an `addDependency` method for file watchers. |
Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:14-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L14-L29)
> [!WARNING]
> When compiling documents, `buildMDX` prepends newline characters corresponding to the exact length of the stripped frontmatter block. This ensures that line numbers reported in parser or compilation errors match the original source file line numbers precisely.
Sources: [packages/mdx/src/loaders/mdx/index.ts:88-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L88-L92)
## Preset Plugins and Processor Configuration
### Preset Application and Options Architecture
The configuration pipeline provides two main preset options: `fumadocs` and `minimal`. The `applyMdxPreset` function accepts `MDXPresetOptions` and returns an asynchronous function resolving to `@mdx-js/mdx` `ProcessorOptions`. When set to `minimal`, options are returned directly without plugin injections. The `mdxPreset` function in the core package similarly builds processor options with a default `outputFormat` of `'function-body'` for server or runtime evaluation.
| Option Key | Type | Default Value | Purpose |
| :--- | :--- | :--- | :--- |
| `preset` | `'fumadocs' \| 'minimal'` | `'fumadocs'` | Selects the processor preset strategy. |
| `valueToExport` | `string[]` | `[]` | Specifies property names to export from `vfile.data`. |
| `remarkStructureOptions` | `Plugins.StructureOptions \| false` | `{ exportAs: 'structuredData' }` | Configures headings and structure extraction. |
| `remarkHeadingOptions` | `Plugins.RemarkHeadingOptions` | `{ generateToc: false }` | Configures heading parsing without TOC generation. |
| `remarkImageOptions` | `Plugins.RemarkImageOptions \| false` | Dynamic (`useImport` true for bundlers) | Configures image processing behaviors. |
| `remarkCodeTabOptions` | `Plugins.RemarkCodeTabOptions \| false` | `undefined` | Enables or configures code tab remark processing. |
| `remarkNpmOptions` | `Plugins.RemarkNpmOptions \| false` | `undefined` | Enables or configures package manager code block transformations. |
| `rehypeCodeOptions` | `Plugins.RehypeCodeOptions \| false` | `undefined` | Configures [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) and code block enhancements. |
Sources: [packages/mdx/src/config/preset.ts:8-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L8-L46), [packages/core/src/content/mdx/preset-runtime.ts:5-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L5-L18)
> [!NOTE]
> In bundler environments, `remarkImage` defaults `useImport` to `true`, ensuring image sources are correctly imported as module assets. In runtime environments, bundler-specific outputs shift to function bodies.
Sources: [packages/mdx/src/config/preset.ts:82-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L82-L82), [packages/mdx/src/config/preset.ts:127-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L127-L127)
### Remark and Rehype Plugin Pipeline
The remark plugin pipeline integrates `remarkGfm`, `remarkHeading`, `remarkImage`, `remarkCodeTab`, `remarkNpm`, and `remarkStructure`. It also processes custom `valueToExport` arrays by reading matching keys from `file.data` and pushing them into `file.data['mdx-export']`. The rehype pipeline integrates `rehypeCode` and `rehypeToc`. Both pipelines support custom Pluggable arrays or modifier functions via `pluginOption` or `resolvePlugins`.
```typescript
export * from './remark-gfm';
export * from './rehype-code';
export * from './remark-image';
export * from './remark-structure';
export * from './remark-heading';
export * from './remark-admonition';
export * from './remark-directive-admonition';
export * from './rehype-toc';
export * from './remark-code-tab';
export * from './remark-steps';
export * from './remark-npm';
export * from './codeblock-utils';
export { remarkMdxFiles, type RemarkMdxFilesOptions } from './remark-mdx-files';
export * from './remark-mdx-mermaid';
export * from './remark-feedback-block';
export type { LLMsOptions } from './remark-llms';
```
Sources: [packages/core/src/mdx-plugins/index.ts:1-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts#L1-L16)
> [!WARNING]
> Setting individual remark or rehype option flags explicitly to `false` (such as `remarkImageOptions: false` or `rehypeCodeOptions: false`) completely disables the corresponding plugin from being appended to the unified pipeline array.
Sources: [packages/mdx/src/config/preset.ts:78-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L78-L88), [packages/mdx/src/config/preset.ts:116-123](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L116-L123)
## Meta and Configuration Loaders
### Metadata File Loader Parsing and Transformation
Metadata loaders intercept JSON and YAML source files matching collection patterns, applying Zod schema validation over query parameters to extract `collection` and `workspace` identifiers. The `parse` function handles file extensions by invoking `JSON.parse` for JSON files and `js-yaml`'s `load` for YAML files, wrapping failures with detailed error context.
```typescript
function parse(filePath: string, source: string) {
try {
if (filePath.endsWith('.json')) return JSON.parse(source);
if (filePath.endsWith('.yaml')) return load(source);
} catch (e) {
throw new Error(`invalid data in ${filePath}`, { cause: e });
}
throw new Error('Unknown file type ' + filePath);
}
```
Sources: [packages/mdx/src/loaders/meta.ts:25-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L25-L34)
> [!NOTE]
> When the `collection` query parameter is omitted or fails validation, the metadata loader falls back to bundler built-in plugins by returning `null`, allowing default file resolution to take over.
Sources: [packages/mdx/src/loaders/meta.ts:37-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L37-L38)
### Adapter Transformation and Output Generation
The loader produces output modules based on the resolved file type and configuration options. For JSON files, the `moduleType` can be configured as either `'json'` or `'js'`, whereas YAML files always transpile to JavaScript default exports.
| Resolve Option Key | Type | Default Value | Purpose |
| :--- | :--- | :--- | :--- |
| `json` | `'json' \| 'js'` | `'js'` | Specifies module output format for JSON meta files. |
| `yaml` | `'js'` | `'js'` | Specifies module output format for YAML meta files. |
Sources: [packages/mdx/src/loaders/meta.ts:18-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L18-L23)
```typescript
if (input.filePath.endsWith('.json')) {
return {
moduleType: resolveJson,
code:
resolveJson === 'json'
? JSON.stringify(data)
: `export default ${JSON.stringify(data)}`,
};
} else {
return {
moduleType: 'js',
code: `export default ${JSON.stringify(data)}`,
};
}
```
Sources: [packages/mdx/src/loaders/meta.ts:80-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L80-L93)
> [!WARNING]
> If a metadata collection item is defined in the source config, raw parsed data passes through `core.transformMeta` before export generation, altering the final structure returned to consumers.
Sources: [packages/mdx/src/loaders/meta.ts:61-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L61-L69)
## Core Plugin Pipeline Lifecycle
### Initialization and Execution Call Chain
The core plugin pipeline lifecycle manages core instance initialization, workspace discovery, and plugin hook execution. The process begins with `createMDX`, which invokes `createNextCore` and subsequently `createCore` to instantiate the core context and resolve plugins via `getPlugins`.
1. `createMDX` — Initializes the core instance by wrapping configuration options.
Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31)
2. `createNextCore` — Generates a core instance with specific environment defaults and the index plugin.
Sources: [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206)
3. `createCore` — Instantiates the core object, setting up internal caches, workspaces, and transformation methods.
Sources: [packages/mdx/src/core.ts:148-152](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L148-L152)
4. `getPlugins` — Flattens and aggregates plugin option arrays asynchronously into a unified array of plugins.
Sources: [packages/mdx/src/core.ts:136-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L136-L146)
```mermaid
sequenceDiagram
participant index.ts as packages/mdx/src/next/index.ts
participant core.ts as packages/mdx/src/core.ts
index.ts->>index.ts: createMDX()
index.ts->>index.ts: createNextCore()
index.ts->>core.ts: createCore()
core.ts->>core.ts: getPlugins()
```
Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31), [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206), [packages/mdx/src/core.ts:136-152](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L136-L152)
> [!WARNING]
> During core initialization (`core.init`), caches and workspaces are cleared, and config plugins are executed sequentially, allowing each plugin to mutate the loaded configuration before workspace resolution occurs.
Sources: [packages/mdx/src/core.ts:176-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L176-L185)
### Plugin Hook Dispatch and Transformation Methods
The core instance exposes explicit methods to invoke lifecycle hooks across registered plugins. When emitting files or transforming content, `emit`, `transformMeta`, `transformFrontmatter`, and `transformVFile` iterate through the plugins sequentially.
```typescript
async emit(emitOptions: EmitOptions = {}): Promise {
const { filterPlugin, filterWorkspace, write = false } = emitOptions;
const start = performance.now();
const ctx = this.getPluginContext();
const added = new Set();
const out: EmitOutput = {
entries: [],
workspaces: {},
};
for (const li of await Promise.all(
plugins.map((plugin) => {
if ((filterPlugin && !filterPlugin(plugin)) || !plugin.emit) return;
return plugin.emit.call(ctx);
}),
)) {
if (!li) continue;
for (const item of li) {
if (added.has(item.path)) continue;
out.entries.push(item);
added.add(item.path);
}
}
```
Sources: [packages/mdx/src/core.ts:244-266](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L244-L266)
| Hook Method | Context Passed | Iteration Behavior | Purpose |
| :--- | :--- | :--- | :--- |
| `config` | PluginContext | Sequential override | Modifies or replaces loaded configuration. |
| `emit` | PluginContext | Parallel execution via `Promise.all` | Generates virtual or persistent output entries. |
| `configureServer` | ServerContext | Sequential execution | Sets up development server watchers or middleware. |
| `meta.transform` | TransformOptions & PluginContext | Sequential pipe | Transforms metadata collection items after validation. |
| `doc.frontmatter` | TransformOptions & PluginContext | Sequential pipe | Transforms document frontmatter after schema validation. |
| `doc.vfile` | TransformOptions & PluginContext | Sequential pipe | Modifies the virtual file container for documents. |
Sources: [packages/mdx/src/core.ts:182-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L182-L185), [packages/mdx/src/core.ts:237-239](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L237-L239), [packages/mdx/src/core.ts:254-258](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L254-L258), [packages/mdx/src/core.ts:302-304](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L302-L304), [packages/mdx/src/core.ts:318-320](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L318-L320), [packages/mdx/src/core.ts:333-335](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L333-L335)
> [!CAUTION]
> Workspace instantiation supports a maximum depth of 1; child workspaces recursively invoke `createCore` with prefixed output directories, and failing to respect this depth limitation results in unhandled configuration loops.
Sources: [packages/mdx/src/core.ts:187-203](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L187-L203)
## Related
- [Bundler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins)
- [Content Compiler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins)
---
## Technical docs: Bundler Plugins
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/mdx/src/loaders/adapter.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts)
- [packages/mdx/src/rolldown/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts)
- [packages/mdx/src/bun/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts)
- [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts)
- [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx)
- [packages/mdx/src/loaders/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts)
- [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
- [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts)
- [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts)
- [packages/mdx/src/node/_loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts)
- [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts)
- [packages/mdx/src/webpack/mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts)
- [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts)
- [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts)
- [packages/mdx/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/tsdown.config.ts)
- [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json)
- [packages/core/src/mdx-plugins/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts)
- [packages/story/src/webpack/story.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/core/src/content/mdx/preset-bundler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts)
- [packages/mdx/src/node/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/loader.ts)
- [packages/story/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts)
- [packages/doc-gen/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/tsdown.config.ts)
- [packages/mdx/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bin.ts)
- [packages/api-docs/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/tsdown.config.ts)
- [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts)
- [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts)
- [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts)
- [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts)
- [packages/asyncapi/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/tsdown.config.ts)
## Overview
Fumadocs provides a set of bundler plugins and low-level adapters that integrate content compilation pipelines into modern build tools and JavaScript runtimes [packages/mdx/src/loaders/adapter.ts:1-223](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts), [packages/mdx/src/core.ts:1-340](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts). These integrations handle document parsing, frontmatter validation, configuration reloading, and virtual entry point generation across Next.js, Vite, Rolldown, Webpack, Node.js, and Bun [packages/mdx/src/next/index.ts:1-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts), [packages/mdx/src/vite/index.ts:1-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts), [packages/mdx/src/rolldown/index.ts:1-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts), [packages/mdx/src/bun/index.ts:1-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts). By abstracting environment-specific module loading and transformation hooks behind a unified core, the packages maintain consistent document behavior during development and production builds [packages/mdx/src/loaders/adapter.ts:35-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts), [packages/mdx/src/core.ts:148-340](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts).
Sources: [packages/mdx/src/loaders/adapter.ts:1-223](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts), [packages/mdx/src/rolldown/index.ts:1-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts), [packages/mdx/src/bun/index.ts:1-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts), [packages/mdx/src/vite/index.ts:1-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts), [packages/mdx/src/next/index.ts:1-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts), [packages/mdx/src/core.ts:1-340](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts)
## Next.js Integration and Core Lifecycle
### Initialization and Execution Flow
The Next.js integration initializes through `createMDX`, which sets up core compilation options and checks the `_FUMADOCS_MDX` environment variable to prevent duplicate initialization passes. When invoked, `createMDX` executes `createNextCore` using options normalized by `applyDefaults`. The call-chain sequence `createMDX` → `init` → `devServer` → `initOrReload` proceeds by instantiating the core via `createMDX`, handing control to `init` to evaluate development flags, invoking `devServer` when `isDev` is true to watch configuration files and collections, and finally triggering `initOrReload` to load the configuration and emit compiled outputs.
```mermaid
sequenceDiagram
participant Index as packages/mdx/src/next/index.ts
Index->>Index: createMDX()
Index->>Index: init()
Index->>Index: devServer()
Index->>Index: initOrReload()
```
Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
1. `createMDX`: Accepts `CreateMDXOptions`, establishes default environment variables, and delegates core creation.
Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
2. `init`: Manages asynchronous bootstrap and checks the `dev` boolean flag to determine whether to spin up file system watchers.
Sources: [packages/mdx/src/next/index.ts:124-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
3. `devServer`: Instantiates a `chokidar` `FSWatcher` instance ignoring the output directory, tracks configuration files and collection directories, and handles hot-reloading on configuration changes.
Sources: [packages/mdx/src/next/index.ts:132-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
4. `initOrReload`: Loads configuration files via `loadConfig(core, true)` and invokes `core.emit({ write: true })`.
Sources: [packages/mdx/src/next/index.ts:125-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
> [!WARNING]
> If `process.env._FUMADOCS_MDX` is already set to `'1'`, subsequent calls to `init` are bypassed during module evaluation to prevent concurrent watcher duplication across Next.js worker threads.
Sources: [packages/mdx/src/next/index.ts:34-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
### Configuration Options and Default Values
The integration relies on `CreateMDXOptions` to configure source paths, output targets, and index generation plugins. These options are processed by `applyDefaults` to guarantee defined parameters.
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `configPath` | `string` | `_Defaults.configPath` | Path to source configuration file. |
| `outDir` | `string` | `_Defaults.outDir` | Directory for output files. |
| `index` | `IndexFilePluginOptions \| false` | `{}` | Index file plugin options or `false` to disable. |
Sources: [packages/mdx/src/next/index.ts:12-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts), [packages/mdx/src/next/index.ts:192-198](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
> [!NOTE]
> `createNextCore` constructs the underlying core instance with environment set to `'next'` and registers the index plugin if enabled.
Sources: [packages/mdx/src/next/index.ts:200-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
## MDX Compiler Preset Configuration
### Preset Options and Remark/Rehype Registration
The `mdxPreset` function asynchronous builder resolves and registers remark and rehype plugins into standard MDX processor options. It takes `MDXBundlerPresetOptions` which omits standard remark and rehype options in favor of resolver structures and specific plugin toggles.
```typescript
export type MDXBundlerPresetOptions = Omit<
NonNullable,
'rehypePlugins' | 'remarkPlugins'
> & {
rehypePlugins?: ResolvePlugins;
remarkPlugins?: ResolvePlugins;
/** @private for `remark-include` */
_include?: Pluggable;
remarkStructureOptions?: Plugins.StructureOptions | false;
remarkHeadingOptions?: Plugins.RemarkHeadingOptions | false;
remarkImageOptions?: Plugins.RemarkImageOptions | false;
remarkCodeTabOptions?: Plugins.RemarkCodeTabOptions | false;
remarkNpmOptions?: Plugins.RemarkNpmOptions | false;
rehypeCodeOptions?: Plugins.RehypeCodeOptions | false;
};
```
Sources: [packages/core/src/content/mdx/preset-bundler.ts:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L6-L21)
```typescript
export async function mdxPreset(options: MDXBundlerPresetOptions = {}): Promise {
const {
rehypeCodeOptions,
remarkImageOptions,
remarkHeadingOptions,
remarkStructureOptions,
remarkCodeTabOptions,
remarkNpmOptions,
_include,
...mdxOptions
} = options;
```
Sources: [packages/core/src/content/mdx/preset-bundler.ts:26-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L26-L36)
> [!NOTE]
> Each remark and rehype plugin can be explicitly disabled by passing `false` to its corresponding option key, or customized by passing an object containing plugin-specific parameters.
Sources: [packages/core/src/content/mdx/preset-bundler.ts:15-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L15-L20)
### Plugin Integration Pipeline
The preset registration pipeline resolves plugins asynchronously through `resolvePlugins`, combining standard defaults with custom user configurations. The pipeline processes remark plugins starting with GitHub Flavored Markdown and conditional expansions.
```typescript
const remarkPlugins = await resolvePlugins(
(v) => [
import('remark-gfm').then((mod) => mod.default),
remarkHeadingOptions !== false &&
import('@/mdx-plugins/remark-heading').then((mod) => [
mod.remarkHeading,
{
generateToc: false,
...remarkHeadingOptions,
},
]),
_include ?? false,
remarkImageOptions !== false &&
import('@/mdx-plugins/remark-image').then((mod) => [
mod.remarkImage,
{
...remarkImageOptions,
useImport: remarkImageOptions?.useImport ?? true,
},
]),
remarkCodeTabOptions !== false &&
import('@/mdx-plugins/remark-code-tab').then((mod) => [
mod.remarkCodeTab,
remarkCodeTabOptions,
]),
remarkNpmOptions !== false &&
import('@/mdx-plugins/remark-npm').then((mod) => [mod.remarkNpm, remarkNpmOptions]),
...v,
remarkStructureOptions !== false &&
import('@/mdx-plugins/remark-structure').then((mod) => [
mod.remarkStructure,
{
exportAs: 'structuredData',
...remarkStructureOptions,
} satisfies Plugins.StructureOptions,
]),
],
mdxOptions.remarkPlugins,
);
```
Sources: [packages/core/src/content/mdx/preset-bundler.ts:38-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L38-L76)
```typescript
const rehypePlugins = await resolvePlugins(
(v) => [
rehypeCodeOptions !== false &&
import('@/mdx-plugins/rehype-code').then((mod) => [mod.rehypeCode, rehypeCodeOptions]),
...v,
import('@/mdx-plugins/rehype-toc').then((mod) => mod.rehypeToc),
],
mdxOptions.rehypePlugins,
);
```
Sources: [packages/core/src/content/mdx/preset-bundler.ts:78-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L78-L86)
> [!WARNING]
> Disabling `remarkHeadingOptions`, `remarkImageOptions`, `remarkCodeTabOptions`, `remarkNpmOptions`, `remarkStructureOptions`, or `rehypeCodeOptions` by setting them to `false` prevents their dynamic imports from executing during the preset build.
Sources: [packages/core/src/content/mdx/preset-bundler.ts:41-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L41-L73), [packages/core/src/content/mdx/preset-bundler.ts:80-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L80-L81)
### Preset Configuration Options Reference
| Option Key | Type | Default Behavior / Mapping | Description |
| :--- | :--- | :--- | :--- |
| `remarkPlugins` | `ResolvePlugins` | Combined via `resolvePlugins` | Custom remark plugins appended to the preset. |
| `rehypePlugins` | `ResolvePlugins` | Combined via `resolvePlugins` | Custom rehype plugins appended to the preset. |
| `_include` | `Pluggable` | `undefined` | Private plugin hook for `remark-include`. |
| `remarkStructureOptions` | `Plugins.StructureOptions \| false` | `{ exportAs: 'structuredData' }` | Options for the structure extraction remark plugin. |
| `remarkHeadingOptions` | `Plugins.RemarkHeadingOptions \| false` | `{ generateToc: false }` | Options for heading extraction and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) generation. |
| `remarkImageOptions` | `Plugins.RemarkImageOptions \| false` | `{ useImport: true }` | Options for remark image optimization and imports. |
| `remarkCodeTabOptions` | `Plugins.RemarkCodeTabOptions \| false` | `undefined` | Options for code tab grouping transformations. |
| `remarkNpmOptions` | `Plugins.RemarkNpmOptions \| false` | `undefined` | Options for package manager command translation. |
| `rehypeCodeOptions` | `Plugins.RehypeCodeOptions \| false` | `undefined` | Options for [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) and code block processing. |
Sources: [packages/core/src/content/mdx/preset-bundler.ts:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L6-L21), [packages/core/src/content/mdx/preset-bundler.ts:41-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L41-L73)
## Index File Codegen Coordination
### Execution Pipeline and Sequence Architecture
The coordination of index file generation begins at the core layer where configuration options are evaluated. The explicit call chain starts with `createMDX`, which delegates through `createNextCore`, initializes the `indexFile` plugin, and executes `generateConfigs` to assemble server options and type definitions.
```typescript
export function createMDX(createOptions: CreateMDXOptions = {}) {
const core = createNextCore(applyDefaults(createOptions));
```
Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31)
```typescript
function createNextCore(options: Required): Core {
return createCore({
environment: 'next',
outDir: options.outDir,
configPath: options.configPath,
plugins: [options.index && indexFile(options.index)],
});
```
Sources: [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206)
```typescript
export default function indexFile(options: IndexFilePluginOptions = {}): Plugin {
const { target = 'default', addJsExtension, browser = true, dynamic = true } = options;
let dynamicCollections: CollectionItem[];
function isDynamic(collection: CollectionItem) {
return (
(collection.type === 'docs' && collection.docs.dynamic) ||
(collection.type === 'doc' && collection.dynamic)
);
}
function generateConfigs(core: Core): {
serverOptions: ServerOptions;
tc: string;
} {
const serverOptions: ServerOptions = {};
const typeConfigs: string[] = ['import("fumadocs-mdx/runtime/types").InternalTypeConfig'];
const ctx = core.getPluginContext();
for (const plugin of core.getPlugins()) {
const indexFilePlugin = plugin['index-file'];
if (!indexFilePlugin) continue;
indexFilePlugin.serverOptions?.call(ctx, serverOptions);
const config = indexFilePlugin.generateTypeConfig?.call(ctx);
if (config) typeConfigs.push(config);
}
return {
serverOptions,
tc: typeConfigs.join(' & '),
};
}
```
Sources: [packages/mdx/src/plugins/index-file.ts:51-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L51-L83)
```mermaid
sequenceDiagram
participant IndexNext as packages/mdx/src/next/index.ts
participant IndexPlugin as packages/mdx/src/plugins/index-file.ts
IndexNext->>IndexNext: createMDX()
IndexNext->>IndexNext: createNextCore()
IndexNext->>IndexPlugin: indexFile()
IndexPlugin->>IndexPlugin: generateConfigs()
```
Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31), [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206), [packages/mdx/src/plugins/index-file.ts:51-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L51-L83)
> [!NOTE]
> The function `generateConfigs` iterates over registered core plugins to extract custom `serverOptions` and append any module type configurations (`generateTypeConfig`) into a combined intersection type string.
Sources: [packages/mdx/src/plugins/index-file.ts:62-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L62-L83)
### Plugin Options and Configuration Reference
The plugin behavior is governed by `IndexFilePluginOptions`, which controls compilation targets, extension resolution, and output file entry generation.
```typescript
export interface IndexFilePluginOptions {
target?: 'default' | 'vite';
/**
* add `.js` extensions to imports, needed for ESM without bundler resolution
*/
addJsExtension?: boolean;
/**
* Generate entry point for browser
* @defaultValue true
*/
browser?: boolean;
/**
* Generate entry point for dynamic compilation
* @defaultValue true
*/
dynamic?: boolean;
}
```
Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32)
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `target` | `'default' \| 'vite'` | `'default'` | Target bundler environment for codegen paths and glob resolution. |
| `addJsExtension` | `boolean` | `undefined` | Appends `.js` extensions to imports for ESM without bundler resolution. |
| `browser` | `boolean` | `true` | Generates a browser entry point module (`browser.ts`). |
| `dynamic` | `boolean` | `true` | Generates an entry point for dynamic content compilation (`dynamic.ts`). |
Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32)
## Webpack Loader Interception
### Standalone MDX and Meta Loaders
The package exposes standalone Webpack loaders for processing MDX documents and collection metadata files outside of the Next.js plugin wrapper. Both loaders utilize a lazy-initialized singleton instance via `toWebpack` to bind core loader logic, while declaring dependencies on compiled configuration paths via Webpack's `this.addDependency()`.
```typescript
const loader: LoaderDefinitionFunction = function loader(source) {
const callback = this.async();
const options = this.getOptions();
this.cacheable(true);
this.addDependency(options.absoluteCompiledConfigPath);
if (!instance) {
instance = toWebpack(
createMdxLoader(
createStandaloneConfigLoader({
core: getCore(options),
buildConfig: false,
mode: options.isDev ? 'dev' : 'production',
}),
),
);
}
void instance.call(this, source, callback);
};
```
Sources: [packages/mdx/src/webpack/mdx.ts:9-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts#L9-L28)
```typescript
const loader: LoaderDefinitionFunction = function (source) {
const callback = this.async();
const options = this.getOptions();
this.cacheable(true);
this.addDependency(options.absoluteCompiledConfigPath);
if (!instance) {
instance = toWebpack(
createMetaLoader(
createStandaloneConfigLoader({
core: getCore(options),
buildConfig: false,
mode: options.isDev ? 'dev' : 'production',
}),
{
json: 'json',
yaml: 'js',
},
),
);
}
void instance.call(this, source, callback);
};
```
Sources: [packages/mdx/src/webpack/meta.ts:9-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts#L9-L32)
> [!NOTE]
> The meta loader configures `createMetaLoader` with mapping values `{ json: 'json', yaml: 'js' }`, passing an options object to `createStandaloneConfigLoader` where `buildConfig` is disabled and `mode` is derived from `options.isDev`.
Sources: [packages/mdx/src/webpack/meta.ts:17-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts#L17-L27)
### Story File Transformation Loader
The story loader handles component documentation files by leveraging `ts-morph` projects and file transformation utilities. It accepts options via `StoryLoaderOptions` and manages asynchronous execution pools through `projectPromise`.
```typescript
export interface StoryLoaderOptions {
/**
* Path to `tsconfig.json`.
*
* @default "tsconfig.json"
*/
tsconfigPath?: string;
}
let projectPromise: Promise | undefined;
const loader: LoaderDefinitionFunction = function (source) {
const callback = this.async();
const options = this.getOptions();
this.cacheable(true);
const run = async () => {
if (!projectPromise) {
const resolvedTsconfig = options.tsconfigPath ?? path.join(this.rootContext, 'tsconfig.json');
projectPromise = createControlsProject(resolvedTsconfig);
}
try {
const transformed = transformStoryFile(
'@fumadocs/story/next/client',
source,
this.resourcePath,
await projectPromise!,
);
callback(undefined, transformed ?? source);
} catch (error) {
if (!(error instanceof Error)) throw error;
callback(error);
}
};
void run();
};
```
Sources: [packages/story/src/webpack/story.ts:7-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L7-L44)
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `tsconfigPath` | `string` | `"tsconfig.json"` | Path to the `tsconfig.json` configuration file used for `ts-morph` project initialization. |
Sources: [packages/story/src/webpack/story.ts:7-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L7-L14), [packages/story/src/webpack/story.ts:25-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L25-L25)
> [!WARNING]
> If `projectPromise` has not been initialized when a story file is processed, the loader resolves `tsconfigPath` relative to `this.rootContext` before creating the controls project.
Sources: [packages/story/src/webpack/story.ts:23-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L23-L27)
## Vite and Rolldown Adapters
### Vite Plugin Architecture and Server Lifecycle
The Vite plugin wrapper orchestrates core compilation lifecycle hooks, configuration building, and development server file watching. It exposes `PluginOptions` to control index generation, configuration paths, module resolution updates, and output directories.
```typescript
export interface PluginOptions {
/**
* Generate index files for accessing content.
*
* @defaultValue true
*/
index?: boolean | IndexFilePluginOptions;
/**
* @defaultValue source.config.ts
*/
configPath?: string;
/**
* Update Vite config to fix module resolution of Fumadocs
*
* @defaultValue true
*/
updateViteConfig?: boolean;
/**
* Output directory of generated files
*
* @defaultValue '.source'
*/
outDir?: string;
}
```
Sources: [packages/mdx/src/vite/index.ts:12-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L12-L38)
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `index` | `boolean \| IndexFilePluginOptions` | `true` | Generates index files for accessing content or configures index file options. |
| `configPath` | `string` | `'source.config.ts'` | Path to the content source configuration file. |
| `updateViteConfig` | `boolean` | `true` | Updates Vite config to fix module resolution of Fumadocs. |
| `outDir` | `string` | `'.source'` | Output directory of generated files. |
Sources: [packages/mdx/src/vite/index.ts:12-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L12-L38)
During the `config` hook, the plugin initializes core functionality via `createViteCore` and runs `core.init()`. It registers `pre`-ordered transform hooks for MDX and meta loaders while establishing file watchers on the configuration path.
> [!CAUTION]
> When Vite RSC processes client references, it passes compiled MDX client modules with IDs matching `virtual:vite-rsc`. The plugin explicitly intercepts and ignores these IDs to prevent JavaScript content formatting from breaking the MDX compiler.
Sources: [packages/mdx/src/vite/index.ts:83-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L83-L86)
```typescript
return [
{
name: 'fumadocs-mdx',
async config(config) {
root = config.root ?? process.cwd();
options = applyDefaults(root, pluginOptions);
core = createViteCore(options);
await core.init({
config: buildConfig(
forcedConfig
? await forcedConfig
: (await runnerImport>(options.configPath)).module,
root,
),
});
const configLoader = createIntegratedConfigLoader(core);
const mdxLoader = toVite(createMdxLoader(configLoader));
const metaLoader = toVite(
createMetaLoader(configLoader, {
// vite has built-in plugin for JSON files
json: 'json',
}),
);
mdxPlugin.transform = {
filter: mdxLoader.filter,
order: 'pre',
handler(code, id) {
// Vite RSC will pass the compiled MDX file's client module with ID `virtual:vite-rsc/client-references/group/facade:xxx.mdx`.
// The format of `value` becomes JavaScript, which will break the MDX compiler.
// We have to ignore them.
if (id.includes('virtual:vite-rsc')) return null;
if (!forcedConfig) this.addWatchFile(options.configPath);
return mdxLoader.transform.call(this, code, id);
},
};
metaPlugin.transform = {
filter: metaLoader.filter,
order: 'pre',
handler(code, id) {
if (!forcedConfig) this.addWatchFile(options.configPath);
return metaLoader.transform.call(this, code, id);
},
};
if ('_fumadocs_skipViteConfig' in config && config._fumadocs_skipViteConfig) return;
if (!options.updateViteConfig) return;
const { getConfig } = await import('@fumadocs/vite');
return getConfig({ root });
},
```
Sources: [packages/mdx/src/vite/index.ts:54-105](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L54-L105)
### Rolldown Plugin Configuration and File Loading
The Rolldown plugin wrapper configures core compilation with a `rolldown` environment parameter. It constructs integrated configuration and loaders, returning a set of Rolldown plugins that handle raw file loading and transformation.
```typescript
export interface PluginOptions {
configPath?: string;
outDir?: string;
}
export default async function mdx(
config: Record | Promise>,
options?: PluginOptions,
): Promise {
const core = createCore({
configPath: options?.configPath ?? _Defaults.configPath,
outDir: options?.outDir ?? _Defaults.outDir,
environment: 'rolldown',
});
await core.init({
config: buildConfig(await config, process.cwd()),
});
const configLoader = createIntegratedConfigLoader(core);
const mdxLoader = toVite(createMdxLoader(configLoader));
const metaLoader = toVite(
createMetaLoader(configLoader, {
// rolldown has built-in plugin for JSON files
json: 'json',
}),
);
```
Sources: [packages/mdx/src/rolldown/index.ts:11-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L11-L37)
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `configPath` | `string` | `_Defaults.configPath` | Path to the content source configuration file. |
| `outDir` | `string` | `_Defaults.outDir` | Output directory of generated files. |
Sources: [packages/mdx/src/rolldown/index.ts:11-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L11-L14), [packages/mdx/src/rolldown/index.ts:21-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L21-L22)
> [!NOTE]
> Because Rolldown cannot read the correct file path when query parameters exist on module IDs, a dedicated load handler strips query strings using `id.lastIndexOf('?')` before reading the file contents from disk via `fs.readFile`.
Sources: [packages/mdx/src/rolldown/index.ts:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L41-L50)
```typescript
return [
{
name: 'fumadocs-mdx',
load: {
filter: { id: [metaLoaderGlob, mdxLoaderGlob] },
// Rolldown couldn't read the correct file path when query params exist.
async handler(id) {
const idx = id.lastIndexOf('?');
if (idx === -1) return null;
return fs.readFile(id.slice(0, idx), 'utf-8');
},
},
},
{
name: 'fumadocs-mdx:mdx',
transform: {
filter: mdxLoader.filter,
handler: mdxLoader.transform,
},
},
{
name: 'fumadocs-mdx:meta',
transform: {
filter: metaLoader.filter,
handler: metaLoader.transform,
},
},
];
```
Sources: [packages/mdx/src/rolldown/index.ts:38-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L38-L66)
### Story File Transformation Plugin
The story plugin provides a Vite-compatible transformation pipeline for component stories, leveraging `ts-morph` projects and filtering file IDs against regular expressions.
```typescript
export interface StoryPluginOptions {
/**
* Path to `tsconfig.json`.
*
* @default "tsconfig.json"
*/
tsconfigPath?: string;
/**
* Filter story files to transform by id (regex)
*
* @default `/\.story\.(js|jsx|ts|tsx)$/`
*/
filter?: RegExp;
}
```
Sources: [packages/story/src/vite/index.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts#L7-L21)
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `tsconfigPath` | `string` | `"tsconfig.json"` | Path to the `tsconfig.json` configuration file. |
| `filter` | `RegExp` | `/\.story\.(js\|jsx\|ts\|tsx)$/` | Filter story files to transform by ID regex. |
Sources: [packages/story/src/vite/index.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts#L7-L21)
```typescript
export default function story(pluginOptions: StoryPluginOptions = {}): Plugin {
const { filter = /\.story\.(js|jsx|ts|tsx)$/ } = pluginOptions;
let tsconfigPath: string;
let projectPromise: Promise | undefined;
return {
name: 'fumadocs:story',
enforce: 'pre',
configResolved(resolved) {
tsconfigPath = pluginOptions.tsconfigPath ?? path.join(resolved.root, 'tsconfig.json');
},
transform: {
filter: { id: filter },
async handler(code, id) {
projectPromise ??= createControlsProject(tsconfigPath);
return transformStoryFile('@fumadocs/story/vite/client', code, id, await projectPromise);
},
},
};
```
Sources: [packages/story/src/vite/index.ts:23-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts#L23-L42)
## Node and Bun Runtime Loaders
### Bun Plugin Module Interception
The Bun plugin integration configures core settings and exposes module loading hooks tailored for the Bun runtime environment. It implements the `BunPlugin` interface through `createMdxPlugin`, accepting options that extend partial core configurations alongside custom plugin toggles.
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `environment` | `string` | `'bun'` | Runtime execution environment identifier. |
| `outDir` | `string` | `_Defaults.outDir` | Output directory path for generated files. |
| `configPath` | `string` | `_Defaults.configPath` | Path to the content source configuration file. |
| `disableMetaFile` | `boolean` | `false` | Disables the automatic meta file transformation step. |
Sources: [packages/mdx/src/bun/index.ts:10-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L10-L23)
During the `setup` lifecycle hook, the plugin initializes core functionality by transforming the configuration path into a file URL and invoking `core.init()`. It establishes integrated configuration loading and assigns MDX and meta loaders using the Bun adapter utility.
```typescript
return {
name: 'bun-plugin-fumadocs-mdx',
async setup(build) {
const importPath = pathToFileURL(configPath).href;
const core = createCore({
environment,
outDir,
configPath,
});
await core.init({
config: buildConfig(await import(importPath), process.cwd()),
});
const configLoader = createIntegratedConfigLoader(core);
toBun(createMdxLoader(configLoader))(build);
if (!disableMetaFile) toBun(createMetaLoader(configLoader))(build);
},
};
}
```
Sources: [packages/mdx/src/bun/index.ts:25-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L25-L44)
> [!NOTE]
> The meta loader step can be entirely bypassed by passing `disableMetaFile: true` in the plugin options, preventing unnecessary processing of metadata files when only core MDX compilation is required.
Sources: [packages/mdx/src/bun/index.ts:14-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L14-L22), [packages/mdx/src/bun/index.ts:41-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L41-L41)
### Native Node.js Module Loaders
Native Node.js environments utilize custom module loading hooks conforming to Node's module customization hooks specification. The modern initialization implementation defines an `initialize` hook that sets up standalone configuration loaders for production mode.
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `environment` | `string` | `'node-loader'` | Execution environment assigned during core creation. |
| `configPath` | `string` | `_Defaults.configPath` | Path to the content source configuration file. |
| `outDir` | `string` | `_Defaults.outDir` | Output directory path for generated content. |
| `disableMetaFile` | `boolean` | `undefined` | Conditionally skips pushing the meta loader into the loader cache. |
Sources: [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29)
```typescript
export const initialize: InitializeHook = (options) => {
const core = createCore({
environment: 'node-loader',
...options,
configPath: options.configPath ?? _Defaults.configPath,
outDir: options.outDir ?? _Defaults.outDir,
});
const configLoader = createStandaloneConfigLoader({
core,
buildConfig: true,
mode: 'production',
});
cachedLoaders = [toNode(createMdxLoader(configLoader))];
if (!options.disableMetaFile) {
cachedLoaders.push(toNode(createMetaLoader(configLoader)));
}
};
```
Sources: [packages/mdx/src/node/_loader.ts:11-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L30)
The accompanying `load` hook iterates sequentially through cached Node module loaders using a recursive runner function, falling back to the standard `nextLoad` function when all custom hooks have executed.
```typescript
export const load: LoadHook = async (url, context, nextLoad) => {
if (!cachedLoaders) throw new Error('not initialized');
const hooks = cachedLoaders;
function run(
i: number,
url: string,
context: LoadHookContext,
): LoadFnOutput | Promise {
if (i >= hooks.length) {
return nextLoad(url, context);
}
return hooks[i](url, context, (url, ctx) => run(i + 1, url, { ...context, ...ctx }));
}
return run(0, url, context);
};
```
Sources: [packages/mdx/src/node/_loader.ts:31-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L31-L48)
> [!WARNING]
> Attempting to invoke the `load` hook before the module loader has been properly initialized via `initialize` triggers an immediate runtime error stating `not initialized`.
Sources: [packages/mdx/src/node/_loader.ts:31-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L31-L32)
## Related
- [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline)
---
## Technical docs: Content Compiler Plugins
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx)
- [packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts)
- [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts)
- [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts)
- [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts)
- [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts)
- [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts)
- [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts)
- [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts)
- [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts)
- [packages/asyncapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts)
- [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts)
- [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts)
- [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts)
- [packages/core/src/source/storage/content.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts)
- [packages/openapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts)
- [packages/python/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts)
- [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts)
- [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts)
- [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts)
- [packages/shadcn/src/manual-installation.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts)
- [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts)
- [packages/shared/compile-package-translations.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/compile-package-translations.ts)
- [packages/mdx-remote/src/compile.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts)
- [packages/story/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts)
- [packages/core/src/source/plugins/slugs.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts)
- [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts)
- [packages/content-collections/src/resolve-plugins.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/resolve-plugins.ts)
## Overview
Fumadocs compiler plugins extend the core build pipeline[packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L176-L185) to transform documentation source collections, inject metadata, and emit virtual assets for bundlers. By intercepting lifecycle hooks across unified processors and bundler configurations, these plugins coordinate everything from static index generation and frontmatter validation to version control timestamp extraction and schema serialization.
Sources: [packages/mdx/src/core.ts:176-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L176-L185)
## Compiler Plugin Architecture
### Plugin Interfaces and Execution Lifecycle Hooks
Fumadocs MDX compiler plugins implement structured contracts defined across core plugin modules[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L40-L93). The `IndexFilePlugin` interface allows plugins like last-modified to inject custom type configurations and server options directly into the compilation context[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L46-L65). Plugins hook into document parsing via `vfile` handlers, intercept collection config initialization, and configure watcher behaviors on development servers.
Sources: [packages/mdx/src/plugins/index-file.ts:34-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/last-modified.ts:40-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L40-L93)
| Plugin Hook | Target Context / Argument | Purpose in Compiler Pipeline |
| :--- | :--- | :--- |
| `config` | `PluginContext` | Initializes collection filters, dynamic collection lists, and version control functions. |
| `configureServer` | Vite Dev Server | Sets up file watchers, invalidates filesystem caches, and triggers targeted re-emits on file additions or deletions[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L90-L120), [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L27-L67). |
| `emit` | `PluginContext` | Asynchronously generates virtual file entries, schema files, or index outputs for bundler resolution[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98). |
| `generateTypeConfig` | `PluginContext` | Returns TypeScript type definition strings for internal type config merging. |
| `serverOptions` | `ServerOptions` | Mutates runtime server configurations, such as registering passthrough properties like `lastModified`[packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L60-L65). |
| `doc.vfile` | Unified `VFile` | Inspects and transforms document virtual files during compilation, injecting metadata or frontmatter exports[packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L78-L91). |
Sources: [packages/mdx/src/plugins/index-file.ts:34-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/json-schema.ts:27-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L27-L98), [packages/mdx/src/plugins/last-modified.ts:40-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L40-L93)
> [!IMPORTANT]
> During server configuration watchers, plugins inspect dynamic collections via `isDynamic` to decide whether change events trigger full re-emits or skip file generation depending on the active `target` (`default` or `vite`)[[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L55-L120).
Sources: [packages/mdx/src/plugins/index-file.ts:55-120](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L55-L120)
### Emit Entry Contracts and Virtual Output Generation
Plugins coordinate asset generation through the `EmitEntry` contract, returning a target file path and stringified content[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98). The `index-file` plugin builds server, dynamic, and browser entry points by evaluating collection structures and invoking code generators[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155). Simultaneously, the `jsonSchema` plugin iterates over collections to serialize Zod schemas into JSON schema representations[packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98).
Sources: [packages/mdx/src/plugins/index-file.ts:121-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/plugins/json-schema.ts:68-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98)]
## Virtual Index File Code Generation
### Plugin Options and Configuration Generation
The `indexFile` plugin accepts options defined by `IndexFilePluginOptions`, supporting properties such as `target` (`'default'` or `'vite'`), `addJsExtension` (appending `.js` extensions to imports for ESM without bundler resolution), `browser` (generating browser entry points, defaulting to `true`), and `dynamic` (generating dynamic compilation entry points, defaulting to `true`).
```typescript
export interface IndexFilePluginOptions {
target?: 'default' | 'vite';
addJsExtension?: boolean;
browser?: boolean;
dynamic?: boolean;
}
```
Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32)
During setup, `generateConfigs` iterates through registered core plugins, invoking optional `serverOptions` hooks and accumulating TypeScript type definitions into an intersection string (`tc`) anchored by `import("fumadocs-mdx/runtime/types").InternalTypeConfig`.
```typescript
function generateConfigs(core: Core): {
serverOptions: ServerOptions;
tc: string;
} {
const serverOptions: ServerOptions = {};
const typeConfigs: string[] = ['import("fumadocs-mdx/runtime/types").InternalTypeConfig'];
const ctx = core.getPluginContext();
for (const plugin of core.getPlugins()) {
const indexFilePlugin = plugin['index-file'];
if (!indexFilePlugin) continue;
indexFilePlugin.serverOptions?.call(ctx, serverOptions);
const config = indexFilePlugin.generateTypeConfig?.call(ctx);
if (config) typeConfigs.push(config);
}
return {
serverOptions,
tc: typeConfigs.join(' & '),
};
}
```
Sources: [packages/mdx/src/plugins/index-file.ts:62-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L62-L83)
### Call-Chain Execution Walkthrough
The virtual index generation pipeline executes sequentially across modular compiler layers to emit output targets.
1. `mdx`: Initializes the Vite plugin wrapper, resolves workspace roots, and provisions the Vite core configuration[packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L40-L68).
2. `createViteCore`: Instantiates the core builder environment with `environment: 'vite'` and registers the `indexFile` plugin configured with the `'vite'` target[packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L144-L159).
3. `indexFile`: Evaluates active documentation and meta collections during its `emit` lifecycle hook, orchestrating file generation tasks[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155).
4. `toEmitEntry`: Wraps content generators by instantiating code generator instances via `createCodegen` and yielding serialized `EmitEntry` objects containing file paths and stringified outputs[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L125-L146).
Sources: [packages/mdx/src/plugins/index-file.ts:121-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/vite/index.ts:40-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L40-L68), [packages/mdx/src/vite/index.ts:144-159](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L144-L159)
```mermaid
sequenceDiagram
participant mdx as mdx (vite/index.ts)
participant createViteCore as createViteCore (vite/index.ts)
participant indexFile as indexFile (plugins/index-file.ts)
participant toEmitEntry as toEmitEntry (plugins/index-file.ts)
mdx->>createViteCore: createViteCore(options)
createViteCore->>indexFile: indexFile({...})
indexFile->>toEmitEntry: toEmitEntry(path, content)
toEmitEntry-->>indexFile: EmitEntry { path, content }
```
Sources: [packages/mdx/src/plugins/index-file.ts:121-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/vite/index.ts:40-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L40-L68), [packages/mdx/src/vite/index.ts:144-159](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L144-L159)
> [!WARNING]
> Dynamic collections are evaluated at runtime by checking `isDynamic`, which returns true if a collection type equals `'docs'` with `collection.docs.dynamic` set, or if type equals `'doc'` with `collection.dynamic` enabled. Changes to these collections bypass standard Vite glob caching and force full file re-emissions.
Sources: [packages/mdx/src/plugins/index-file.ts:55-120](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L55-L120)
### Dynamic Compilation and Runtime Execution
The runtime dynamic module manages lazy entries through `dynamic`, accepting config exports, core options, and server configurations to provision collection loaders[packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L58).
```typescript
export async function dynamic(
configExports: Config,
coreOptions: CoreOptions,
serverOptions?: ServerOptions,
) {
const core = createCore(coreOptions);
await core.init({
config: buildConfig(configExports as Record, process.cwd()),
});
const create = server(serverOptions);
// ...
```
Sources: [packages/mdx/src/runtime/dynamic.ts:47-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L58)
The `convertLazyEntries` helper maps incoming lazy entries by reading file contents from `info.fullPath`, stripping frontmatter via the `frontmatter` utility, building MDX AST outputs through `buildMDX`, and hydrating compiled modules using `executeMdx` with an asynchronous function constructor[packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L67-L95).
```typescript
async function compile({ info, data }: LazyEntry) {
let content = await fs.readFile(info.fullPath, 'utf-8');
content = frontmatter(content).content;
const compiled = await buildMDX(core, collection, {
filePath: info.fullPath,
source: content,
frontmatter: data as Record,
isDevelopment: false,
environment: 'runtime',
});
return (await executeMdx(String(compiled.value), {
baseUrl: pathToFileURL(info.fullPath),
})) as CompiledMDXProperties;
}
```
Sources: [packages/mdx/src/runtime/dynamic.ts:71-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L71-L86)
## Git Last Modified Timestamps
### Plugin Configuration and Version Control Resolution
The last-modified plugin injects a `lastModified` property into document page exports by resolving timestamps through version control systems or custom handler functions. The `LastModifiedPluginOptions` interface accepts a `versionControl` option, which can be explicitly set to `'git'` or provided as a custom `VersionControlFn` callback accepting a file path and returning a promise resolving to a `Date`, `null`, or `undefined`. An optional `filter` predicate limits timestamp injection to specified collections by name.
```typescript
export interface LastModifiedPluginOptions {
versionControl?: 'git' | VersionControlFn;
filter?: (collection: string) => boolean;
}
```
Sources: [packages/mdx/src/plugins/last-modified.ts:9-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L9-L27)
During the plugin initialization and configuration lifecycle, the current working directory (`cwd`) is resolved from workspace configuration or the process current directory. When `versionControl` is configured as `'git'`, the internal function `fn` binds to `getGitTimestamp`, passing both the target file path and the resolved working directory.
```typescript
config() {
const { workspace } = this.core.getOptions();
const cwd = workspace ? path.resolve(workspace.dir) : process.cwd();
switch (versionControl) {
case 'git':
fn = (v) => getGitTimestamp(v, cwd);
break;
default:
fn = versionControl;
}
},
```
Sources: [packages/mdx/src/plugins/last-modified.ts:66-77](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L66-L77)
> [!NOTE]
> When executing git-based timestamp resolution within containerized CI or deployment environments such as Vercel, shallow clones will omit commit history. Users must configure the `VERCEL_DEEP_CLONE` environment variable to `true` to ensure full commit logs are available for extraction.
Sources: [packages/mdx/src/plugins/last-modified.ts:12-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L12-L16)
### Child Process Execution and Caching
To prevent redundant filesystem and process execution overhead across repeated document compilation passes, `getGitTimestamp` maintains a module-scoped cache mapping file paths to promises of `Date | null`. When a file lookup occurs, the cache is checked first before spawning a child process.
```typescript
const cache = new Map>();
```
Sources: [packages/mdx/src/plugins/last-modified.ts:6-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L6-L6)
When a cache miss occurs, the function executes the `git` command via `tinyexec` (`x`), requesting the single latest commit (`-1`) with pretty formatting (`--ai`) for the path relative to the working directory. If the process exits with a non-zero exit code, or if the resulting date string parses to an invalid time, `null` is returned and cached accordingly.
```typescript
async function getGitTimestamp(file: string, cwd: string): Promise {
const cached = cache.get(file);
if (cached) return cached;
const timePromise = (async () => {
const out = await x('git', ['log', '-1', '--pretty="%ai"', path.relative(cwd, file)], {
nodeOptions: {
cwd,
},
});
if (out.exitCode !== 0) return null;
const date = new Date(out.stdout);
return isNaN(date.getTime()) ? null : date;
})();
cache.set(file, timePromise);
return timePromise;
}
```
Sources: [packages/mdx/src/plugins/last-modified.ts:95-113](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L95-L113)
During virtual file processing (`vfile`), the plugin evaluates the collection filter, retrieves the resolved timestamp for `this.filePath`, and populates `file.data['mdx-export']` with an export object defining `name: 'lastModified'` and the corresponding `value` date. Concurrently, index file generation hooks push `lastModified` into server option passthroughs and emit TypeScript type definitions extending `DocData` with an optional `lastModified?: Date` property for all matching collections.
```typescript
doc: {
async vfile(file) {
if (!filter(this.collection.name)) return;
const timestamp = await fn(this.filePath);
if (timestamp) {
file.data['mdx-export'] ??= [];
file.data['mdx-export'].push({
name: 'lastModified',
value: timestamp,
});
}
},
},
```
Sources: [packages/mdx/src/plugins/last-modified.ts:78-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L78-L91)
## JSON Schema Generation
### Schema Definition and Path Resolution
The `jsonSchema` plugin generates local JSON schema definitions for collection frontmatter and meta structures, relying exclusively on Zod for schema parsing. The plugin accepts a single options object defined by `JSONSchemaOptions`, containing the `insert` boolean flag which controls whether a `$schema` property is injected into newly created JSON files.
Sources: [packages/mdx/src/plugins/json-schema.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L7-L21)
Schema paths are resolved uniformly using the internal `getSchemaPath` function, which maps a given schema identifier string into a standard relative output path under the `json-schema/` directory.
Sources: [packages/mdx/src/plugins/json-schema.ts:22-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L22-L24)
| Option Key | Type | Default | Purpose |
| :--- | :--- | :--- | :--- |
| `insert` | `boolean` | `false` | Inserts the `$schema` field pointing to the generated schema file when new JSON or meta files are created |
Sources: [packages/mdx/src/plugins/json-schema.ts:7-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L7-L14)
```typescript
function getSchemaPath(name: string) {
return `json-schema/${name}.json`;
}
```
Sources: [packages/mdx/src/plugins/json-schema.ts:22-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L22-L24)
### Server Watcher and File Injection
When the development server is configured and `insert` is enabled, the plugin registers a file watcher listener for the `'add'` event. Upon detecting a newly added file, the watcher iterates through all registered collections to identify whether the file belongs to a standalone `meta` collection or the meta schema of a `docs` collection.
Sources: [packages/mdx/src/plugins/json-schema.ts:27-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L27-L44)
> [!WARNING]
> If a newly created JSON file already contains an existing `$schema` property, the watcher aborts execution and skips file modification entirely to prevent overwriting user-defined schema references.
Sources: [packages/mdx/src/plugins/json-schema.ts:55-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L55-L55)
If a match is found and parsing succeeds without errors, the watcher computes a relative path from the target file's directory to the absolute JSON schema file location. It then injects the `$schema` property at the root of the parsed JSON object and writes the formatted result back to the filesystem.
Sources: [packages/mdx/src/plugins/json-schema.ts:45-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L45-L66)
```typescript
if ('$schema' in obj) return;
const schemaPath = path.join(
outDir,
getSchemaPath(parent ? `${parent.name}.meta` : match.name),
);
const updated = {
$schema: path.relative(path.dirname(file), schemaPath),
...obj,
};
await fs.writeFile(file, JSON.stringify(updated, null, 2));
```
Sources: [packages/mdx/src/plugins/json-schema.ts:55-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L55-L65)
### Emit Hook and Schema Serialization
The `emit()` lifecycle hook iterates across all core collections to harvest Zod schemas defined on documentation items and metadata files, serializing them into emitter entry objects.
Sources: [packages/mdx/src/plugins/json-schema.ts:68-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98)
```typescript
for (const collection of this.core.getCollections()) {
if (collection.type === 'docs') {
if (collection.meta.schema instanceof z.ZodType) {
onSchema(`${collection.name}.meta`, collection.meta.schema);
}
if (collection.docs.schema instanceof z.ZodType) {
onSchema(`${collection.name}.docs`, collection.docs.schema);
}
} else if (collection.schema instanceof z.ZodType) {
onSchema(collection.name, collection.schema);
}
}
```
Sources: [packages/mdx/src/plugins/json-schema.ts:83-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L83-L95)
The internal `onSchema` helper invokes `z.toJSONSchema` with configured options forcing input mode (`io: 'input'`) and setting unrepresentable types to `'any'`, then stores the resulting stringified JSON schemas inside the emitted file collection.
Sources: [packages/mdx/src/plugins/json-schema.ts:71-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L71-L81)
```typescript
function onSchema(name: string, schema: z.ZodSchema) {
files.push({
path: getSchemaPath(name),
content: JSON.stringify(
z.toJSONSchema(schema, {
io: 'input',
unrepresentable: 'any',
}),
),
});
}
```
Sources: [packages/mdx/src/plugins/json-schema.ts:71-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L71-L81)
## Filesystem Caching and Codegen Utilities
Compiler plugins manage incremental updates and file invalidation using dedicated caching utilities and version control timestamp maps. For example, the `index-file` plugin maintains a filesystem cache instance (`indexFileCache`) to track file modifications and invalidate entries when filesystem watchers trigger change events.
Sources: [packages/mdx/src/plugins/index-file.ts:6-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L6-L6), [packages/mdx/src/plugins/index-file.ts:49-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L49-L49), [packages/mdx/src/plugins/index-file.ts:93-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L93-L94)
Similarly, the git last-modified plugin uses a module-level `Map` to cache asynchronous timestamp promises for each file path, preventing redundant process spawns during document compilation.
Sources: [packages/mdx/src/plugins/last-modified.ts:6-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L6-L6), [packages/mdx/src/plugins/last-modified.ts:95-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L95-L96), [packages/mdx/src/plugins/last-modified.ts:111-112](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L111-L112)
```typescript
server.watcher.on('all', async (event, file) => {
indexFileCache.delete(file);
```
Sources: [packages/mdx/src/plugins/index-file.ts:93-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L93-L94)
Code generation and path normalization helpers abstract away target-specific output differences and import specifier formatting. The `indexFile` plugin constructs an emitter context using a configurable code generator that accepts target options, output directories, and extension preferences for ESM environments.
Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32), [packages/mdx/src/plugins/index-file.ts:129-134](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L129-L134)
> [!NOTE]
> When generating server index files, the compiler formats configuration import paths using `codegen.formatImportPath` to ensure correct resolution across different bundler targets and workspace layouts.
Sources: [packages/mdx/src/plugins/index-file.ts:162-163](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L162-L163)
## Related
- [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline)
---
## Technical docs: MDX Runtime Compilation
URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-runtime-compilation
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/mdx-remote/src/render.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts)
- [packages/mdx-remote/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/index.ts)
- [packages/local-md/src/eval-estree-expression/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/eval-estree-expression/index.ts)
- [packages/mdx-remote/src/client/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/client/index.ts)
- [packages/mdx-remote/src/compile.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts)
- [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts)
- [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx)
- [packages/core/src/content/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/md.ts)
- [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts)
- [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts)
- [packages/local-md/src/md/renderer.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/renderer.ts)
- [packages/mdx/src/webpack/mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts)
- [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts)
- [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts)
- [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts)
- [packages/local-md/src/js/executor-native.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts)
- [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts)
- [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx)
- [packages/radix-ui/src/mdx.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/mdx.tsx)
- [packages/mdx/src/loaders/mdx/build-mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts)
- [packages/local-md/src/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/client.ts)
- [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts)
- [packages/core/src/content/mdx/preset-runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts)
- [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts)
- [packages/preview/src/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/markdown.tsx)
- [packages/base-ui/src/mdx.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/mdx.tsx)
- [packages/core/src/mdx-plugins/remark-mdx-files.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts)
- [packages/base-ui/src/mdx.server.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/mdx.server.tsx)
- [packages/core/src/mdx-plugins/remark-llms.runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.runtime.ts)
- [packages/radix-ui/src/mdx.server.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/mdx.server.tsx)
## Overview
MDX Runtime Compilation facilitates the parsing, frontmatter extraction, compilation, and evaluation of MDX documents on demand across server and browser runtimes. It leverages the MDX processor, Unified transformation pipelines, and custom runtime execution functions to convert raw string inputs into executable React components, structured table-of-contents data, and metadata exports. By coordinating dynamic doc collections, standard schema validation, and custom component binding, the system enables flexible documentation rendering across diverse UI frameworks and bundlers.
Sources: [packages/mdx-remote/src/compile.ts:60-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L60-L121), [packages/mdx-remote/src/render.ts:17-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L33), [packages/mdx/src/runtime/dynamic.ts:47-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L122), [packages/mdx/src/runtime/browser.tsx:58-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L58-L76), [packages/mdx/src/runtime/server.ts:72-241](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L72-L241)
## Remote Compilation Architecture
### Compiler Factory and Processor Initialization
The `createCompiler` function initializes and caches a unified MDX processor instance configured via `createProcessor`. It accepts either a minimal configuration or a full preset configuration through `CompilerOptions`. If format options are omitted or set to `'detect'`, the processor defaults to MDX format.
```typescript
export function createCompiler(mdxOptions?: CompilerOptions) {
let instance: ReturnType | undefined;
function getProcessor() {
if (instance) return instance;
let format = mdxOptions?.format;
if (!format || format === 'detect') format = 'mdx';
return (instance = createProcessor({
...(mdxOptions?.preset === 'minimal' ? mdxOptions : getCompileOptions(mdxOptions)),
format,
}));
}
```
Sources: [packages/mdx-remote/src/compile.ts:60-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L60-L73)
The compilation pipeline processes raw source strings by first extracting frontmatter via `parseFrontmatter`. It then feeds the content body into the cached processor along with the file path and extracted frontmatter data.
```typescript
async compile>(
options: CompileMDXOptions,
): Promise> {
const { scope = {}, skipRender } = options;
const { frontmatter, content } = parseFrontmatter(options.source);
const file = await this.compileFile({
value: content,
path: options.filePath,
data: {
frontmatter,
},
});
const compiled = String(file);
```
Sources: [packages/mdx-remote/src/compile.ts:89-102](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L60-L102)
> [!WARNING]
> Setting `skipRender` to `true` on `CompileMDXOptions` will bypass the execution phase, leaving `exports` as `null` and throwing an error if the resulting `body` function is invoked.
Sources: [packages/mdx-remote/src/compile.ts:44-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L44-L48), [packages/mdx-remote/src/compile.ts:109-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L109-L115)
### Execution Scope and Function Hydration
Once the MDX text is compiled into function body string output, `executeMdx` constructs a dynamic asynchronous function via `AsyncFunction`. It merges scope options, JSX runtimes, and base URLs into an `opts` object, exposing remaining scope properties as arguments to the generated function.
```typescript
export async function executeMdx(compiled: string, options: Options = {}) {
const { opts: scopeOpts, ...scope } = options.scope ?? {};
const fullScope = {
opts: {
...(scopeOpts as object),
...(options.jsxRuntime ?? jsxRuntimeDefault),
baseUrl: options.baseUrl,
},
...scope,
};
const hydrateFn = new AsyncFunction(...Object.keys(fullScope), compiled);
return (await hydrateFn.apply(hydrateFn, Object.values(fullScope))) as {
default: MdxContent;
toc?: TOCItemType[];
};
}
```
Sources: [packages/mdx-remote/src/render.ts:17-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L33)
| Option Key | Default / Source | Purpose |
| :--- | :--- | :--- |
| `scope` | `{}` | Custom variables and context injected into the MDX execution scope. |
| `baseUrl` | `pathToFileURL(filePath)` | Resolves relative file paths for remote compilation contexts. |
| `jsxRuntime` | `react/jsx-runtime` (or dev runtime) | Supplies JSX element creation functions during component hydration. |
Sources: [packages/mdx-remote/src/render.ts:8-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L8-L12), [packages/mdx-remote/src/compile.ts:76-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L76-L81)
> [!NOTE]
> The synchronous counterpart `executeMdxSync` uses a standard synchronous `Function` constructor instead of `AsyncFunction`, evaluating compiled outputs immediately when asynchronous evaluation is not required.
Sources: [packages/mdx-remote/src/render.ts:35-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L35-L52)
## Client-Side Evaluation and Component Injection
### Asynchronous and Synchronous Hydration Functions
Client runtimes execute compiled MDX bundle strings by constructing dynamic functions via `executeMdx` and `executeMdxSync`. The `executeMdx` function uses an asynchronous function constructor derived from `executeMdx0` or `executeMdx`, while `executeMdxSync` utilizes a standard `Function` constructor to evaluate bundles synchronously.
```typescript
const AsyncFunction: new (...args: string[]) => (...args: unknown[]) => Promise =
Object.getPrototypeOf(executeMdx).constructor;
export async function executeMdx(compiled: string, options: Options = {}) {
const { opts: scopeOpts, ...scope } = options.scope ?? {};
const fullScope = {
opts: {
...(scopeOpts as object),
...(options.jsxRuntime ?? jsxRuntimeDefault),
baseUrl: options.baseUrl,
},
...scope,
};
const hydrateFn = new AsyncFunction(...Object.keys(fullScope), compiled);
return (await hydrateFn.apply(hydrateFn, Object.values(fullScope))) as {
default: MdxContent;
toc?: TOCItemType[];
};
}
```
Sources: [packages/mdx-remote/src/render.ts:14-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L33)
| Hydration Function | Constructor Type | Return Signature |
| :--- | :--- | :--- |
| `executeMdx` | `AsyncFunction` | `Promise<{ default: MdxContent; toc?: TOCItemType[] }>` |
| `executeMdxSync` | `Function` | `{ default: MdxContent; toc?: TOCItemType[] }` |
Sources: [packages/mdx-remote/src/render.ts:14-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L14-L15), [packages/mdx-remote/src/render.ts:28-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L28-L32), [packages/mdx-remote/src/render.ts:46-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L46-L51)
> [!NOTE]
> The legacy `executeMdx` implementation in `packages/mdx-remote/src/index.ts` automatically selects between `react/jsx-runtime` and `react/jsx-dev-runtime` based on `process.env.NODE_ENV === 'production'`.
Sources: [packages/mdx-remote/src/index.ts:10-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/index.ts#L10-L17)
### Scope Merging and Component Bindings
Both `executeMdx` and `executeMdxSync` accept an `Options` object containing scope variables, base URLs, and custom JSX runtimes. The options merge property values into an `opts` object, exposing remaining scope properties as arguments to the generated hydration function.
```typescript
export async function executeMdx(compiled: string, options: Options = {}) {
const { opts: scopeOpts, ...scope } = options.scope ?? {};
const fullScope = {
opts: {
...(scopeOpts as object),
...(options.jsxRuntime ?? jsxRuntimeDefault),
baseUrl: options.baseUrl,
},
...scope,
};
```
Sources: [packages/mdx-remote/src/render.ts:17-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L26)
> [!WARNING]
> Failing to supply a valid `jsxRuntime` option defaults execution to `jsxRuntimeDefault` (`react/jsx-runtime`), which may cause runtime errors if development-only JSX annotations are required by the compiled bundle.
Sources: [packages/mdx-remote/src/render.ts:4-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L4-L4), [packages/mdx-remote/src/render.ts:22-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L22-L22), [packages/mdx-remote/src/render.ts:40-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L40-L40)
The resulting `MdxContent` component accepts optional `components` bindings matching `MDXComponents` alongside table-of-contents data structured as `TOCItemType[]`.
```typescript
import type { MDXComponents } from 'mdx/types';
import type { TOCItemType } from 'fumadocs-core/toc';
import type { FC } from 'react';
import jsxRuntimeDefault from 'react/jsx-runtime';
export type MdxContent = FC<{ components?: MDXComponents }>;
```
Sources: [packages/mdx-remote/src/render.ts:1-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L1-L6), [packages/mdx-remote/src/render.ts:29-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L29-L32)
## Dynamic Doc Collection Runtime
### On-Demand Collection Initialization and Execution
The runtime compilation engine initializes dynamic documentation collections using `dynamic` and `server` modules. The `dynamic` function initializes core configurations via `createCore` and builds configuration exports from the working directory using `buildConfig`.
```typescript
export async function dynamic(
configExports: Config,
coreOptions: CoreOptions,
serverOptions?: ServerOptions,
) {
const core = createCore(coreOptions);
await core.init({
config: buildConfig(configExports as Record, process.cwd()),
});
```
Sources: [packages/mdx/src/runtime/dynamic.ts:47-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L55)
> [!NOTE]
> The `getDocCollection` utility validates collection existence, retrieving either standard documentation arrays or single documentation entries based on the collection type definition.
Sources: [packages/mdx/src/runtime/dynamic.ts:59-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L59-L65)
Lazy entry compilation reads raw file content via `node:fs/promises`, strips frontmatter metadata using the `frontmatter` utility, and compiles MDX through `buildMDX` in runtime environment mode. The compiled output string is then evaluated using an asynchronous function constructor initialized by `executeMdx`.
```typescript
async function compile({ info, data }: LazyEntry) {
let content = await fs.readFile(info.fullPath, 'utf-8');
content = frontmatter(content).content;
const compiled = await buildMDX(core, collection, {
filePath: info.fullPath,
source: content,
frontmatter: data as Record,
isDevelopment: false,
environment: 'runtime',
});
return (await executeMdx(String(compiled.value), {
baseUrl: pathToFileURL(info.fullPath),
})) as CompiledMDXProperties;
}
```
Sources: [packages/mdx/src/runtime/dynamic.ts:71-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L71-L86)
| Execute Option | Type | Purpose |
| :--- | :--- | :--- |
| `scope` | `Record` | Injected variables and options scope for MDX execution |
| `baseUrl` | `string \| URL` | File URL reference for relative asset resolution |
| `jsxRuntime` | `unknown` | Custom JSX runtime fallback overriding default imports |
Sources: [packages/mdx/src/runtime/dynamic.ts:22-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L22-L26), [packages/mdx/src/runtime/dynamic.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L33-L39)
### Server Document Mapping and Lazy Collections
The `server` module provides utility factories including `fileInfo`, `mapDocData`, and `createDocMethods` to construct document metadata and method bindings for file entries. Passthrough properties defined in server options are explicitly mapped into document data records alongside body contents, table-of-contents trees, and structured data extracts.
```typescript
export function server(options: ServerOptions = {}) {
const { doc: { passthroughs: docPassthroughs = [] } = {} } = options;
function fileInfo(file: string, base: string): FileInfo {
if (file.startsWith('./')) {
file = file.slice(2);
}
return {
path: file,
fullPath: path.join(base, file),
};
}
function mapDocData(entry: CompiledMDXProperties): DocData {
const data: DocData = {
body: entry.default,
toc: entry.toc,
structuredData: entry.structuredData,
_exports: entry as unknown as Record,
};
for (const key of docPassthroughs) {
// @ts-expect-error -- handle passthrough properties
data[key] = entry[key];
}
return data;
}
```
Sources: [packages/mdx/src/runtime/server.ts:72-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L72-L100)
> [!WARNING]
> Calling `getText('processed')` or `getMDAST()` on document methods throws an error unless `includeProcessedMarkdown` or `includeMDAST` are enabled in the collection configuration.
Sources: [packages/mdx/src/runtime/server.ts:296-310](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L296-L310)
Collections support both eager and lazy loading variants through `doc`, `docLazy`, `docs`, `docsLazy`, and `meta` methods. Lazy execution caches compilation promises per entry, preventing redundant file reads and MDX build steps during subsequent document retrievals.
```typescript
for (const entry of entries) {
head[entry.info.path] = () => entry.data;
let cachedResult: Promise | undefined;
body[entry.info.path] = () => (cachedResult ??= compile(entry));
}
return { head, body };
}
```
Sources: [packages/mdx/src/runtime/dynamic.ts:88-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L88-L95), [packages/mdx/src/runtime/server.ts:126-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L126-L155)
The `toFumadocsSource` function aggregates page and metadata items into a unified virtual file structure for downstream source consumers, applying optional base directory paths to all registered virtual file entries.
```typescript
export function toFumadocsSource<
Page extends DocMethods & PageData,
Meta extends MetaMethods & MetaData,
>(
pages: Page[],
metas: Meta[],
options?: ToFumadocsSourceOptions,
): Source<{
pageData: Page;
metaData: Meta;
}> {
const baseDir = options?.baseDir;
const files: VirtualFile<{
pageData: Page;
metaData: Meta;
}>[] = [];
for (const entry of pages) {
files.push({
type: 'page',
path: baseDir ? path.join(baseDir, entry.info.path) : entry.info.path,
absolutePath: entry.info.fullPath,
data: entry,
});
}
for (const entry of metas) {
files.push({
type: 'meta',
path: baseDir ? path.join(baseDir, entry.info.path) : entry.info.path,
absolutePath: entry.info.fullPath,
data: entry,
});
}
return {
files,
};
}
```
Sources: [packages/mdx/src/runtime/server.ts:243-281](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L243-L281)
## Browser Execution and Client Loaders
### Client Loader Creation and Cache Sharing
The browser runtime exports the `browser` factory and `createClientLoader` utility to manage compiled MDX file entries and render components within React client environments. To prevent duplicate chunks generated by code-splitting frameworks such as Tanstack Start from fracturing state, `createClientLoader` accepts an optional `id` configuration option to share document preloads across multiple instances through a global `loaderStore` map.
```tsx
const loaderStore = new Map<
string,
{
preloaded: Map;
}
>();
export function createClientLoader<
Doc = CompiledMDXProperties,
Props extends object | undefined = undefined,
>(
globEntries: Record Promise>,
options: ClientLoaderOptions,
): ClientLoader {
const { id = '', component: useRenderer } = options;
const renderers: Record> = {};
const loaders = new Map Promise>();
const store = loaderStore.get(id) ?? {
preloaded: new Map(),
};
loaderStore.set(id, store);
```
Sources: [packages/mdx/src/runtime/browser.tsx:78-99](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L78-L99)
> [!NOTE]
> File path keys registered in glob entries are normalized by stripping leading `./` prefixes to ensure consistent cache lookups regardless of glob path syntax.
Sources: [packages/mdx/src/runtime/browser.tsx:100-102](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L100-L102)
### Standard Schema Integration and Renderer Methods
The `doc` method on the browser collection entry infers frontmatter output types via `@standard-schema/spec` while wrapping raw glob entries and forwarding options to `createClientLoader`.
```tsx
export function browser() {
return {
doc(
_name: Name,
glob: Record Promise>,
) {
const out: DocCollectionEntry = {
raw: glob as DocCollectionEntry['raw'],
createClientLoader({ id = _name as string, ...options }) {
return createClientLoader(this.raw, { id, ...options });
},
};
return out as Config[Name] extends DocCollection | DocsCollection
? DocCollectionEntry, TC>
: never;
},
```
Sources: [packages/mdx/src/runtime/browser.tsx:58-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L58-L74)
Client loaders return an interface containing three core methods for retrieving and rendering documentation entries: `preload`, `getComponent`, and `useContent`.
| Method | Parameters | Return Type | Description |
| :--- | :--- | :--- | :--- |
| `preload` | `path: string` | `Promise` | Asynchronously fetches and caches raw document content into the store |
| `getComponent` | `path: string` | `FC` | Returns a React functional component that renders the document using React's `use()` hook |
| `useContent` | `path: string, props?: Props` | `ReactNode` | Directly renders the document component populated with the provided properties |
Sources: [packages/mdx/src/runtime/browser.tsx:28-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L28-L40), [packages/mdx/src/runtime/browser.tsx:125-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L125-L138)
> [!WARNING]
> Requesting a path that does not exist in the available glob entries throws an error directly from `getLoader` during resolution.
Sources: [packages/mdx/src/runtime/browser.tsx:104-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L104-L109)
## Runtime Plugin Presets and Execution
### MDX Preset Configuration and Default Plugins
The `mdxPreset` function asynchronous helper builds and configures `ProcessorOptions` for unified and MDX pipelines by resolving default remark and rehype plugins alongside custom overrides. By default, the output format is set to `function-body`, and standard plugins can be disabled by passing `false` to their respective option flags in `MDXRuntimePresetOptions`.
| Preset Option | Default State | Associated Module / Plugin | Configuration Object |
| :--- | :--- | :--- | :--- |
| `remarkHeadingOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-heading` | `{ generateToc: false, ...remarkHeadingOptions }` |
| `remarkImageOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-image` | `remarkImageOptions` |
| `remarkCodeTabOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-code-tab` | `remarkCodeTabOptions` |
| `remarkNpmOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-npm` | `remarkNpmOptions` |
| `remarkStructureOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-structure` | `{ exportAs: 'structuredData', ...remarkStructureOptions }` |
| `rehypeCodeOptions` | Enabled (unless `false`) | `@/mdx-plugins/rehype-code` | `rehypeCodeOptions` |
| `remarkPlugins` / `rehypePlugins` | Resolves `v` | `remark-gfm` (remark), `@/mdx-plugins/rehype-toc` (rehype) | User-defined or resolved via `resolvePlugins` |
```typescript
export async function mdxPreset(options: MDXRuntimePresetOptions = {}): Promise {
const {
rehypeCodeOptions,
remarkImageOptions,
remarkHeadingOptions,
remarkStructureOptions,
remarkCodeTabOptions,
remarkNpmOptions,
outputFormat = 'function-body',
...mdxOptions
} = options;
const remarkPlugins = await resolvePlugins(
(v) => [
import('remark-gfm').then((mod) => mod.default),
remarkHeadingOptions !== false &&
import('@/mdx-plugins/remark-heading').then((mod) => [
mod.remarkHeading,
{
generateToc: false,
...remarkHeadingOptions,
},
]),
remarkImageOptions !== false &&
import('@/mdx-plugins/remark-image').then((mod) => [mod.remarkImage, remarkImageOptions]),
remarkCodeTabOptions !== false &&
import('@/mdx-plugins/remark-code-tab').then((mod) => [
mod.remarkCodeTab,
remarkCodeTabOptions,
]),
remarkNpmOptions !== false &&
import('@/mdx-plugins/remark-npm').then((mod) => [mod.remarkNpm, remarkNpmOptions]),
...v,
remarkStructureOptions !== false &&
import('@/mdx-plugins/remark-structure').then((mod) => [
mod.remarkStructure,
{
exportAs: 'structuredData',
...remarkStructureOptions,
} satisfies Plugins.StructureOptions,
]),
],
mdxOptions.remarkPlugins,
);
const rehypePlugins = await resolvePlugins(
(v) => [
rehypeCodeOptions !== false &&
import('@/mdx-plugins/rehype-code').then((mod) => [mod.rehypeCode, rehypeCodeOptions]),
...v,
import('@/mdx-plugins/rehype-toc').then((mod) => mod.rehypeToc),
],
mdxOptions.rehypePlugins,
);
return {
...mdxOptions,
outputFormat,
remarkPlugins,
rehypePlugins,
};
}
```
Sources: [packages/core/src/content/mdx/preset-runtime.ts:23-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L23-L84)
> [!NOTE]
> The remark heading plugin explicitly forces `generateToc: false` by default within the preset runtime, separating table-of-contents generation into the rehype TOC pipeline.
Sources: [packages/core/src/content/mdx/preset-runtime.ts:38-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L38-L45)
### File Tree Transformation and Auto-Files Parsing
The `remarkMdxFiles` transformer parses code blocks with the `files` language identifier or `auto-files` JSX flow elements into MDX component structures (``, ``, and ``). The `parseFileTree` helper splits code lines, tracks indentation depth using standard Unix or Windows line endings, and builds hierarchical folder-file relationships. When encountering `` elements, the transformer extracts `dir`, `pattern`, and `defaultOpenAll` attributes, utilizing `tinyglobby` to scan directories relative to the virtual file's parent directory or CWD.
```typescript
function parseFileTree(code: string) {
const lines = code.split(/\r?\n/);
const stack = new Map();
for (const line of lines) {
let depth = 0;
let name = line;
let match: RegExpMatchArray | null;
while ((match = /(?:├──|│|└──)\s*/.exec(name))) {
name = name.slice(match[0].length);
depth++;
}
if (!name) continue;
const node: Node = name.endsWith('/')
? { type: 'folder', name, children: [], depth }
: { type: 'file', name, depth };
let parent: Node | undefined;
for (let i = depth - 1; i >= 0 && !parent; i--) {
parent = stack.get(i);
}
stack.set(depth, node);
if (!parent) continue;
if (parent.type === 'file') {
Object.assign(parent, {
type: 'folder',
children: [],
});
}
(parent as FolderNode).children.push(node);
}
return stack.get(0);
}
function defaultToMDX(node: Node, options: ToMdxOptions, depth = 0): MdxJsxFlowElement {
if (depth === 0) {
return {
type: 'mdxJsxFlowElement',
name: 'Files',
attributes: [],
children: [defaultToMDX(node, options, depth + 1)],
};
}
const attributes: MdxJsxAttribute[] = [
{ type: 'mdxJsxAttribute', name: 'name', value: node.name },
];
if (node.type === 'file') {
return {
type: 'mdxJsxFlowElement',
attributes,
children: [],
name: 'File',
};
}
if (options.defaultOpenAll) {
attributes.push({
type: 'mdxJsxAttribute',
name: 'defaultOpen',
value: null,
});
}
return {
type: 'mdxJsxFlowElement',
attributes,
name: 'Folder',
children: node.children.map((item) => defaultToMDX(item, options, depth + 1)),
};
}
/**
*
```
Sources: [packages/core/src/mdx-plugins/remark-mdx-files.ts:40-162](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts#L40-L162)
> [!WARNING]
> Omitting the `pattern` attribute on an `` element triggers an immediate failure on the virtual file (`file.fail`) at the node's exact AST position.
Sources: [packages/core/src/mdx-plugins/remark-mdx-files.ts:146-156](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts#L146-L156)
### Placeholder Rendering and Serialization
The `renderPlaceholder` runtime function evaluates delimited control strings matching the control regex `/\0(.+?)\0/gs`, parsing inner JSON payloads into `PlaceholderData` objects containing `name`, `attributes`, and `children`. If nested child blocks contain text, `renderPlaceholder` executes recursively. If a matching renderer exists in the `renderers` dictionary, the placeholder output is replaced with the renderer's return value; otherwise, it falls back to the raw child text or the original match block upon a JSON parsing error.
```typescript
const regex = /\0(.+?)\0/gs;
export async function renderPlaceholder(
text: string,
renderers: Record Awaitable>,
): Promise {
let out = '';
let idx = 0;
for (const match of text.matchAll(regex)) {
out += text.slice(idx, match.index);
const inner = match[1];
try {
const data = JSON.parse(inner) as PlaceholderData;
const renderer = data.name && renderers[data.name];
if (data.children.trim()) {
data.children = await renderPlaceholder(data.children, renderers);
}
if (renderer) {
out += await renderer(data);
} else {
out += data.children;
}
} catch {
out += match[0];
}
idx = match.index + match[0].length;
}
out += text.slice(idx);
return out;
```
Sources: [packages/core/src/mdx-plugins/remark-llms.runtime.ts:10-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.runtime.ts#L10-L42)
## Preview and Dynamic Rendering Integration
### Markdown Compiler Setup and Plugin Pipelines
The markdown compiler pipeline is configured via `createMarkdownCompiler`, which accepts `remarkPlugins`, `rehypePlugins`, and `remarkRehypeOptions`. In preview environments, the processor integrates `remarkGfm`, `remarkMath`, `remarkMdxMermaid`, `remarkHeading`, `remarkNpm`, and `remarkCodeTab`, alongside `rehypeKatex`, `rehypeCode`, and `rehypeToc` with `{ exportToc: { as: 'data' } }`.
```tsx
const compiler = createMarkdownCompiler({
remarkPlugins: [
remarkGfm,
remarkMath,
remarkMdxMermaid,
plugin(remarkHeading, { generateToc: false }),
plugin(remarkNpm, { persist: { id: 'package-manager' } }),
remarkCodeTab,
],
remarkRehypeOptions: {
passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'],
},
rehypePlugins: [
rehypeKatex,
plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }),
plugin(rehypeToc, { exportToc: { as: 'data' } }),
],
});
```
Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46)
| Compiler Option | Configured Plugins / Options | Purpose |
| :--- | :--- | :--- |
| `remarkPlugins` | `remarkGfm`, `remarkMath`, `remarkMdxMermaid`, `remarkHeading`, `remarkNpm`, `remarkCodeTab` | Extends markdown parsing with tables, math, mermaid diagrams, headings, package managers, and code tabs. |
| `remarkRehypeOptions` | `passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement']` | Preserves JSX flow and text elements during AST conversion. |
| `rehypePlugins` | `rehypeKatex`, `rehypeCode`, `rehypeToc` | Applies KaTeX math formatting, code [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting), and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) extraction. |
Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46)
> [!CAUTION]
> The markdown compilation renderer throws an explicit error when encountering disallowed evaluation nodes, disallowing program evaluation and limiting identifier lookup strictly to override component bindings.
Sources: [packages/preview/src/lib/md.ts:45-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts#L45-L55)
### Component Injection and Rendering Handlers
The `DocPage` routing component loads layout and page structures based on configuration presets (`docs` or `flux`), resolving page slugs through source loaders. When rendering content inside `MdContent`, `ServerImage` intercepts non-absolute image sources and rewrites them into query parameters containing `page`, `project`, and `src`.
```tsx
function useMdxComponents(page: SourcePage) {
function ServerImage({ src, ...rest }: ComponentProps<'img'>) {
// resolve non-absolute src
if (src && !URL.canParse(src)) {
const params = new URLSearchParams();
params.set('page', page.absolutePath!);
params.set('project', page.data.project.dir);
params.set('src', src);
src = `/img?${params}`;
}
return