> Each page under `/docs/next` has a version for every framework at `/docs/`, where `` is one of `next`, `react-router`, `tanstack-start`, `waku`, `astro`. # Fumadocs (Framework Mode): Introduction URL: /docs Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/index.mdx The documentation framework for React # Set up Fumadocs Instructions for AI agents to set up Fumadocs on Next.js. The setup changes between versions, so run the commands below and read the linked docs instead of writing the setup from memory. Add `.md` to the URL of a docs page to read it as Markdown. Use Next.js unless the user asks for another framework, or their app uses another one. In that case, follow the instructions of that framework instead: - Next.js: https://fumadocs.dev/docs/next.md - React Router: https://fumadocs.dev/docs/react-router.md - TanStack Start: https://fumadocs.dev/docs/tanstack-start.md - Waku: https://fumadocs.dev/docs/waku.md - Astro: https://fumadocs.dev/docs/astro.md ## New Site Create a new docs site in a new folder, or as a workspace package of a monorepo: ```bash npx create-fumadocs-app@latest my-docs --template +next+fuma-docs-mdx --install --yes ``` For a static site, use the `+next+fuma-docs-mdx+static` template. - `my-docs` is the folder to create. - `--yes` skips the prompts, and the options you don't pass use their defaults. The options are listed in https://fumadocs.dev/docs/cli/create-fumadocs-app.md ## Existing App To add docs to an existing app, run the CLI in the folder of the app: ```bash npx @fumadocs/cli@latest init ``` - The CLI detects the framework, and adds the docs pages with their own layout beside the existing routes. - `--i18n` sets up internationalization. - The CLI asks before it overwrites a file. Without a terminal, it keeps the file and prints its name. Pass `--yes` only when every file it writes can be overwritten. To set up by hand, or to merge a file that the CLI kept, follow https://fumadocs.dev/docs/next/manual-installation.md ## After the Setup Both commands print the next steps. Start the dev server and open the docs, at `/docs` unless the output names another path. For the tasks that follow, read the docs page of the task first: - Writing pages: https://fumadocs.dev/docs/next/markdown.md - Organizing pages and folders: https://fumadocs.dev/docs/next/page-conventions.md - Customizing the UI: https://fumadocs.dev/docs/next/guides/customize-ui.md - Changing the theme and colors: https://fumadocs.dev/docs/ui/theme.md - Other tasks: https://fumadocs.dev/llms.txt lists every docs page. Fumadocs (Foo-ma docs) is a **documentation framework**, designed to be fast, flexible, and composes seamlessly into your React framework. It consists of multiple layers: Handles most of the logic, including document search, content source adapters, and Markdown extensions. The default theme of Fumadocs offers a beautiful look for documentation sites and interactive components. The source of your content, can be a CMS or local data layers like [Fumadocs MDX](/docs/mdx) (the official content source). A command line tool to install UI components and automate things, useful for customizing layouts. Read our in-depth [What is Fumadocs](/docs/next/what-is-fumadocs) introduction. ## Choosing a Framework [#choosing-a-framework] The guides are written for each framework. Choose the one your app uses, or Next.js for a new project: Powerful and mature, the default for new projects. For React Router apps. Its SPA mode hosts the site statically on a CDN. For TanStack Start apps. Its SPA mode hosts the site statically on a CDN. Fast and simple, a React framework on Vite with server components. For Astro sites, with content collections and MDX rendered as React islands. [Fumapress](https://press.fumadocs.dev) is a site generator that manages more features on top of Fumadocs. - Automatic routing, `llms.txt`, MCP and more basic features. - Based on Vite ([Waku](https://waku.gg)). It enforces a React framework of its own, and offers a better DX in return. # Fumadocs (Framework Mode): Scalar Example URL: /docs/asyncapi Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/asyncapi/index.mdx View the Scalar Galaxy example AsyncAPI schema. - [Subscribe to Planet Events ](/docs/asyncapi/planets/subscribeToPlanetEvents): Subscribe to real-time events for a specific planet - [Subscribe to User Events ](/docs/asyncapi/users/subscribeToUserEvents): Subscribe to events for a specific user (requires authentication) - [Subscribe to System Events ](/docs/asyncapi/system/subscribeToSystemEvents): Subscribe to system-wide notifications and alerts - [Subscribe to Celestial Body Events ](/docs/asyncapi/celestial-bodies/subscribeToCelestialBodyEvents): Subscribe to events for all celestial bodies in the galaxy # Fumadocs CLI (the CLI tool for automating Fumadocs apps): create-fumadocs-app URL: /docs/cli/create-fumadocs-app Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/cli/create-fumadocs-app.mdx The CLI to create new Fumadocs apps ## Usage [#usage] ```npm npx create-fumadocs-app@latest my-docs ``` It asks for the template and features to configure, you can also pass them as options. ### Options [#options] | Option | Description | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `--template ` | The template to use, see [Templates](#templates). | | `--src` | (Next.js only) Use the `src/` directory. | | `--linter ` | Configure a linter: `eslint` (Next.js only), `oxlint` or `biome`. | | `--search ` | Search solution: `orama` (default, local search), `orama-cloud`, `algolia`, `meilisearch`, `typesense` or `mixedbread` (needs a server). | | `--og-image ` | OG image: `next-og` (Next.js only) or `takumi`, others use Takumi. | | `--ai-chat ` | AI chat: `openrouter`, `llmgateway` or `inkeep`, not available on static, SPA and Astro templates. | | `--install` | Install dependencies automatically. | | `--no-git` | Skip Git repository initialization. | | `--pm ` | Package manager: `npm`, `pnpm`, `yarn` or `bun`, detected from how the CLI is invoked. | | `-y, --yes` | Skip prompts, use defaults for options not specified. | ### Templates [#templates] | Value | Description | | ---------------------------- | -------------------------- | | `+next+fuma-docs-mdx` | Next.js (default) | | `+next+fuma-docs-mdx+static` | Next.js with static export | | `waku` | Waku | | `react-router` | React Router | | `react-router-spa` | React Router in SPA mode | | `tanstack-start` | TanStack Start | | `tanstack-start-spa` | TanStack Start in SPA mode | | `astro` | Astro | ### Non-interactive [#non-interactive] Pass `--yes` to skip prompts, useful for scripts, CI and AI agents: ```npm npx create-fumadocs-app@latest my-docs --template +next+fuma-docs-mdx --install --yes ``` Options you didn't specify use their defaults: no linter, local search, no AI chat. It fails when the target directory already exists and is not empty. The templates have no i18n option. To add i18n to the new project, follow the Internationalization guide of its framework: [Next.js](/docs/next/internationalization), [React Router](/docs/react-router/internationalization), [TanStack Start](/docs/tanstack-start/internationalization), [Waku](/docs/waku/internationalization) or [Astro](/docs/astro/internationalization). ## Programmatic API [#programmatic-api] Despite the classical CLI usage, you can also use it in scripts like: ```npm npm install create-fumadocs-app ``` ```ts import { create } from 'create-fumadocs-app'; await create({ outputDir: 'my-app', template: '+next+fuma-docs-mdx', packageManager: 'pnpm', }); ``` # Fumadocs CLI (the CLI tool for automating Fumadocs apps): User Guide URL: /docs/cli Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/cli/index.mdx The CLI tool that automates setups and installs components. ## Installation [#installation] Initialize a config for CLI: ```package-install npx @fumadocs/cli ``` You can change the output paths of components in the config. ### Init [#init] Set up Fumadocs on an existing app. It supports Next.js, React Router, TanStack Start, Waku and Astro. ```package-install npx @fumadocs/cli init ``` To avoid conflicts with your app, the docs pages are added in a dedicated route group (e.g. `app/(docs)` on Next.js) with their own provider and layout, route handlers like the search API follow the [examples](https://github.com/fuma-nama/fumadocs/tree/dev/examples). Only a few edits are made to existing files: - Fumadocs MDX plugin in your framework config. - Fumadocs UI styles in your global CSS. - `suppressHydrationWarning` on the `` element of your root layout, for the theme switch. - `.source` in `.gitignore`. Pass `--i18n` to set up [internationalization](/docs/next/internationalization): the docs routes get a locale segment (optional for the default locale where the router supports it), a `lib/i18n.ts` config and, on Next.js, a proxy scoped to the docs routes. Other features follow the i18n config of your project. It asks before overwriting a file, pass `--yes` to skip prompts and `--no-install` to only write dependencies to `package.json`. ### Features [#features] Configure a feature on your project, it installs the needed components & routes, and wires them into your app. ```package-install npx @fumadocs/cli feature ai --provider openrouter ``` | Feature | Description | | ---------- | ------------------------------------------------------------------------------------------ | | `docs` | Set up Fumadocs, same as `init`. | | `ai` | [Ask AI](/docs/next/integrations/llms#ask-ai) dialog, `--provider`. | | `llms` | [LLM routes](/docs/next/integrations/llms): `llms.txt`, `llms-full.txt` and per-page Markdown. | | `mcp` | [MCP server](/docs/next/integrations/llms#mcp-server) to search and read the docs. | | `webmcp` | [WebMCP](/docs/next/integrations/llms#webmcp) tools for AI agents in the browser, experimental. | | `og` | Open Graph image generation with Takumi or next/og (Next.js only), `--engine`. | | `search` | 3rd party [search solution](/docs/next/search), `--provider`. | | `feedback` | [Feedback](/docs/next/integrations/feedback) component on docs pages. | | `epub` | Route to [export EPUB](/docs/next/guides/export-epub). | | `lint` | Configure ESLint (Next.js only), Biome or Oxlint, `--linter`. | Features adapt to your setup: - Fumadocs MDX with the [Macro API](/docs/mdx/macro) or a `source.config.ts`, other content sources can't use `llms`, `mcp` and `epub`. - The `baseUrl` of your docs, `src/` directory, `next.config.ts`, i18n, static export and SPA modes. - React Router with file-based routes: the routes to register are printed instead. - Astro with `@fumadocs/astro` collections: `ai` is not available, `mcp` and `epub` need an adapter. The paths of routes are placed under the constants of `lib/shared.ts`. See help for the available options: ```package-install npx @fumadocs/cli feature -h ``` ### Components [#components] Select and install components. ```package-install npx @fumadocs/cli add ``` You can pass component names directly. ```package-install npx @fumadocs/cli add banner files ``` #### How the magic works? [#how-the-magic-works] The CLI fetches the latest version of component from the Fumadocs registry (`https://fumadocs.dev/registry`). When you install a component, it is guaranteed to be up-to-date. In addition, it also transforms import paths. Make sure to use the latest version of CLI > This is highly inspired by Shadcn UI. ### Customize [#customize] A simple way to customize Fumadocs layouts. ```package-install npx @fumadocs/cli customize ``` It installs the layout into `layouts` and points the imports of your route files at it. ### Shadcn UI [#shadcn-ui] On projects with a `components.json`, the CLI follows the aliases of Shadcn UI and: - installs the `shadcn` preset, so Fumadocs UI adopts your theme colors. - reuses the `button`, `popover` and `collapsible` in your `ui` directory, they share the API of Shadcn UI. - imports `cn` from your `utils` alias. Fumadocs' copies are only installed when you don't have them yet. ### Tree [#tree] Generate files tree for Fumadocs UI `Files` component, using the `tree` command from your terminal. ```package-install npx @fumadocs/cli tree ./my-dir ./output.tsx ``` You can output MDX files too: ```package-install npx @fumadocs/cli tree ./my-dir ./output.mdx ``` See help for further details: ```package-install npx @fumadocs/cli tree -h ``` #### Example Output [#example-output] ```tsx title="output.tsx" import { File, Folder, Files } from 'fumadocs-ui/components/files'; export default ( ); ``` # Fumadocs CLI (the CLI tool for automating Fumadocs apps): Preview URL: /docs/cli/preview Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/cli/preview.mdx A light tool to view Markdown files. ## Introduction [#introduction] `fumadocs-preview` allows you to view Markdown files with Fumadocs, it is useful for reading skills files & notes. Run the command under your project directory. ```npm npx fumadocs-preview dir/to/content ``` ### Configurations [#configurations] For other configurations, you can install it locally: ```npm npm install fumadocs-preview -D ``` Then init the config file: ```npm npx fumadocs-preview init ``` # Fumadocs (Framework Mode): Store Example URL: /docs/graphql Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/graphql/index.mdx View the example store GraphQL schema. A store schema documented with [Fumadocs GraphQL](/docs/next/integrations/graphql), its playground sends requests to a mock endpoint. - [Customer](/docs/graphql/queries/customer) has named examples to pick from. - [Order Updated](/docs/graphql/subscriptions/orderUpdated) streams live events in the playground. - [Customer query](/docs/graphql/queries/customer): Look up a customer by its ID. - [Orders query](/docs/graphql/queries/orders): List all orders. - [Search query](/docs/graphql/queries/search): Search for customers and orders. - [Node query](/docs/graphql/queries/node): Fetch any node by ID. - [Create Order mutation](/docs/graphql/mutations/createOrder): Create a new order. - [Legacy Create Order mutation](/docs/graphql/mutations/legacyCreateOrder) - [Order Updated subscription](/docs/graphql/subscriptions/orderUpdated): Subscribe to status changes of an order. # Fumadocs Core (the core library of Fumadocs): Breadcrumb URL: /docs/headless/components/breadcrumb Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/components/breadcrumb.mdx The navigation component at the top of the screen A hook for implementing Breadcrumb in your documentation. It returns breadcrumb items for a page based on the given page tree. > If present, the index page of a folder will be used as the item. ## Usage [#usage] It exports a `useBreadcrumb` hook: ```ts twoslash declare const tree: any; // ---cut--- import { useBreadcrumb } from 'fumadocs-core/breadcrumb'; // or the hook provided by your React framework import { usePathname } from 'fumadocs-core/framework'; const pathname = usePathname(); const items = useBreadcrumb(pathname, tree); // ^? ``` ### Example [#example] A styled example. `usePathname()` and `Link` of Fumadocs work on every framework with its [framework provider](/docs/headless#installation). ```tsx 'use client'; import { usePathname } from 'fumadocs-core/framework'; import { useBreadcrumb } from 'fumadocs-core/breadcrumb'; import type { PageTree } from 'fumadocs-core/page-tree'; import { Fragment } from 'react'; import { ChevronRight } from 'lucide-react'; import Link from 'fumadocs-core/link'; export function Breadcrumb({ tree }: { tree: PageTree.Root }) { const pathname = usePathname(); const items = useBreadcrumb(pathname, tree); if (items.length === 0) return null; return (
{items.map((item, i) => ( {i !== 0 && } {item.url ? ( {item.name} ) : ( {item.name} )} ))}
); } ``` You can use it by passing the page tree via `tree` prop in a server component. ### Breadcrumb Item [#breadcrumb-item] ### BreadcrumbItem | Prop | Type | Description | | ------ | --------------------- | ----------- | | `name` | `React.ReactNode` | | | `url?` | `string \| undefined` | | # Fumadocs Core (the core library of Fumadocs): Components URL: /docs/headless/components Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/components/index.mdx Blocks for your docs - [Breadcrumb](/docs/headless/components/breadcrumb): The navigation component at the top of the screen - [Link](/docs/headless/components/link): A Link component that handles external links - [TOC](/docs/headless/components/toc): Table of Contents # Fumadocs Core (the core library of Fumadocs): Link URL: /docs/headless/components/link Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/components/link.mdx A Link component that handles external links A component that wraps the Link component of your React framework (e.g. `next/link`) and automatically handles external links in the document.~ When an external URL is detected, it uses `` instead of the Link Component. The `rel` property is automatically generated. ## Usage [#usage] Usage is the same as using ``. ```mdx import Link from 'fumadocs-core/link'; Click Me ``` ### External [#external] You can force a URL to be external by passing an `external` prop. ### Dynamic hrefs [#dynamic-hrefs] You can enable dynamic hrefs by importing `dynamic-link`. ```mdx import { DynamicLink } from 'fumadocs-core/dynamic-link'; Click Me ``` # Fumadocs Core (the core library of Fumadocs): TOC URL: /docs/headless/components/toc Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/components/toc.mdx Table of Contents A Table of Contents with active anchor observer and auto scroll. ## Usage [#usage] ```tsx import * as Base from 'fumadocs-core/toc'; return ( ); ``` ### Anchor Provider [#anchor-provider] Watches for the active anchor using the Intersection Observer API. ### AnchorProviderProps | Prop | Type | Description | | ----------- | ---------------------- | ---------------------------------------------------- | | `toc` | `TOC.TOCItemType[]` | | | `single?` | `boolean \| undefined` | Only accept one active item at most Default: `false` | | `children?` | `React.ReactNode` | | ### Scroll Provider [#scroll-provider] Scrolls the scroll container to the active anchor. ### ScrollProviderProps | Prop | Type | Description | | -------------- | -------------------------------------- | --------------------------------------------- | | `containerRef` | `React.RefObject` | Scroll into the view of container when active | | `children?` | `React.ReactNode` | | ### TOC Item [#toc-item] An anchor item for jumping to the target anchor. | Data Attribute | Values | Description | | -------------- | ------------- | -------------------- | | `data-active` | `true, false` | Is the anchor active | ## Example [#example] ```tsx import { AnchorProvider, ScrollProvider, TOCItem, type TOCItemType } from 'fumadocs-core/toc'; import { type ReactNode, useRef } from 'react'; export function Page({ items, children }: { items: TOCItemType[]; children: ReactNode }) { const viewRef = useRef(null); return (
{items.map((item) => ( {item.title} ))}
{children}
); } ``` # Fumadocs Core (the core library of Fumadocs): Content Collections URL: /docs/headless/content-collections Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/content-collections/index.mdx Use Content Collections for Fumadocs [Content Collections](https://www.content-collections.dev) is a library that transforms your content into type-safe data collections. ## Setup [#setup] Follow their [official guide](https://content-collections.dev/docs) to setup Content Collections for your React framework. Make sure you have MDX configured: ```npm npm i @content-collections/mdx ``` To integrate with Fumadocs, add the following to your `content-collections.ts`. ```ts title="content-collections.ts" import { defineCollection, defineConfig } from '@content-collections/core'; import { transformMDX } from '@fumadocs/content-collections/configuration'; import { metaSchema, pageSchema } from 'fumadocs-core/source/schema'; const docs = defineCollection({ name: 'docs', directory: 'content/docs', include: '**/*.mdx', schema: pageSchema, transform: transformMDX, }); const metas = defineCollection({ name: 'meta', directory: 'content/docs', include: '**/meta.json', parser: 'json', schema: metaSchema, }); export default defineConfig({ collections: [docs, metas], }); ``` And pass it to `loader()`. ```ts title="lib/source.ts" import { allDocs, allMetas } from 'content-collections'; import { loader } from 'fumadocs-core/source'; import { createMDXSource } from '@fumadocs/content-collections'; export const source = loader({ baseUrl: '/docs', source: createMDXSource(allDocs, allMetas), }); ``` Done! You can access the pages and generated page tree from Source API. ```ts import { getPage } from '@/lib/source'; const page = getPage(slugs); // MDX output page?.data.body; // Table of contents page?.data.toc; // Structured Data, for Search API page?.data.structuredData; ``` ### MDX Options [#mdx-options] You can customize MDX options in the `transformMDX` function. ```ts import { defineCollection } from '@content-collections/core'; import { transformMDX } from '@fumadocs/content-collections/configuration'; const docs = defineCollection({ transform: (document, context) => transformMDX(document, context, { // options here }), }); ``` ### Import Components [#import-components] To use components from other packages like Fumadocs UI, pass them to your `` component. ```tsx import { MDXContent } from '@content-collections/mdx/react'; import { getMDXComponents } from '@/components/mdx'; return ; ``` You can also import them in MDX Files, but it is not recommended. Content Collections uses `mdx-bundler` to bundle MDX files. To support importing a package from node modules, Fumadocs added a default value to the `cwd` option of MDX Bundler. It works good, but we still **do not** recommend importing components in MDX files. Reasons: - It requires esbuild to bundle these components, while it should be done by the framework's bundler (e.g. Vite or Turbopack) - You can refactor the import path of components without changing your MDX files. - With Remote Sources, it doesn't make sense to add an import in MDX files. # Fumadocs Core (the core library of Fumadocs): Introduction URL: /docs/headless Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/index.mdx Getting started with core library ## What is this? [#what-is-this] Fumadocs Core offers server-side functions and headless components to build docs on React.js frameworks like Next.js, React Router, TanStack Start, Waku and Astro. - [Search](/docs/headless/search) - Breadcrumb, Sidebar, TOC Components - Remark/Rehype Plugins - [MCP tools](/docs/headless/utils/mcp) for AI agents to search and read docs - [Additional utilities](/docs/headless/utils) It can be used without Fumadocs UI, in other words, it's headless. For beginners and normal usages, use [Fumadocs UI](/docs/ui). ## Installation [#installation] Install the core package. Individual integrations may require additional dependencies, listed in their guides. ```package-install fumadocs-core ``` For some components, a framework provider is needed: ```tsx tab="Next.js" import type { ReactNode } from 'react'; import { NextProvider } from 'fumadocs-core/framework/next'; export function RootLayout({ children }: { children: ReactNode }) { // or if you're using Fumadocs UI, use `` return {children}; } ``` ```tsx tab="React Router" import type { ReactNode } from 'react'; import { ReactRouterProvider } from 'fumadocs-core/framework/react-router'; export function Root({ children }: { children: ReactNode }) { return {children}; } ``` ```tsx tab="TanStack Start" import type { ReactNode } from 'react'; import { TanstackProvider } from 'fumadocs-core/framework/tanstack'; export function Root({ children }: { children: ReactNode }) { return {children}; } ``` ```tsx tab="Waku" import type { ReactNode } from 'react'; import { WakuProvider } from 'fumadocs-core/framework/waku'; export function Root({ children }: { children: ReactNode }) { return {children}; } ``` ```tsx tab="Astro" import { navigate } from 'astro:transitions/client'; import type { ReactNode } from 'react'; import { AstroProvider } from 'fumadocs-core/framework/astro'; // Rendered inside a React island, pass pathname and params from the Astro page. export function Root({ pathname, params, children, }: { pathname: string; params: Record; children: ReactNode; }) { return ( {children} ); } ``` Explore the APIs and components: # Fumadocs Core (the core library of Fumadocs): Configuration URL: /docs/headless/internationalization/config Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/internationalization/config.mdx Shared i18n configuration For framework integration guide, see [Internationalization](/docs/next/internationalization). ## Define Config [#define-config] Fumadocs core provides necessary middleware and utilities for i18n support. You can define a config to share between utilities. ```ts title="lib/i18n.ts" import { defineI18n } from 'fumadocs-core/i18n'; export const i18n = defineI18n({ defaultLanguage: 'en', languages: ['en', 'cn'], }); ``` ### Hide Locale Prefix [#hide-locale-prefix] To hide the locale prefix (e.g. `/en/page` -> `/page`), use the `hideLocale` option. ```ts import { defineI18n } from 'fumadocs-core/i18n'; export const i18n = defineI18n({ defaultLanguage: 'en', languages: ['en', 'cn'], hideLocale: 'default-locale', }); ``` | Mode | Description | | ---------------- | -------------------------------------------------- | | `always` | Always hide the prefix, detect locale from cookies | | `default-locale` | Only hide the default locale | | `never` | Never hide the prefix (default) | On `always` mode, locale is stored as a cookie (set by the middleware), which isn't optimal for static sites. This may cause undesired cache problems, and need to pay extra attention on SEO to ensure search engines can index your pages correctly. ### Fallback Language [#fallback-language] The fallback language to use when translations are missing for a file, default to your `defaultLanguage`. It accepts one of the languages in your `languages` array. ```ts import { defineI18n } from 'fumadocs-core/i18n'; export const i18n = defineI18n({ languages: ['en', 'cn'], defaultLanguage: 'en', // Chinese variant is used if a file is missing in English fallbackLanguage: 'cn', }); ``` To disable the fallback behaviour, set it to `null`: ```ts import { defineI18n } from 'fumadocs-core/i18n'; export const i18n = defineI18n({ languages: ['en', 'cn'], defaultLanguage: 'en', fallbackLanguage: null, }); ``` When disabled, no fallback will be used (including `meta.json`). You can still create a shared file for every locale with `$`: # Fumadocs Core (the core library of Fumadocs): Middleware URL: /docs/headless/internationalization/middleware Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/internationalization/middleware.mdx Next.js proxy for implementing i18n routing ## Setup [#setup] Redirects users to appropriate locale, it can be customized from `i18n.ts` config file. It's a Next.js proxy. See [Internationalization](/docs/next/internationalization) for the setup on React Router, TanStack Start, Waku and Astro. ```ts title="proxy.ts" import { createI18nMiddleware } from 'fumadocs-core/i18n/middleware'; import { i18n } from '@/lib/i18n'; export default createI18nMiddleware(i18n); export const config = { // Matcher ignoring `/_next/` and `/api/` // You may need to adjust it to ignore static assets in `/public` folder matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], }; ``` > When `hideLocale` is enabled, it uses `NextResponse.rewrite` to hide locale prefixes. # Fumadocs Core (the core library of Fumadocs): Headings URL: /docs/headless/mdx/headings Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/headings.mdx Process headings from your document ## Remark Heading [#remark-heading] A remark plugin that applies IDs to headings. Fumadocs MDX enables it by default. Pass options with `remarkHeadingOptions`. ### Custom IDs [#custom-heading-id] You can customize the heading ID with `[#slug]`. ```md # heading [#slug] ``` To disable it: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkHeadingOptions: { customId: false, }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { remarkHeadingOptions: { customId: false, }, }, }); ``` ### Extract TOC [#extract-toc] By default, it also extracts the headings (table of contents) of a document to the file data as `toc`, an array of `TOCItemType`. Fumadocs MDX turns it off with `generateToc: false` and exports the table of contents with [Rehype TOC](#rehype-toc) instead. ### TOCItemType | Prop | Type | Description | | -------- | --------------------- | ------------------------------ | | `title` | `React.ReactNode` | | | `url` | `string` | | | `depth` | `number` | | | `_step?` | `number \| undefined` | [remark-steps] the step number | ### Headings with Expressions [#headings-with-expressions] In Fumadocs MDX, the ID of a heading is generated from its rendered text when the heading has an expression, or is inside [``](/docs/next/markdown#show): ```mdx ## Deploy on {props.framework} ``` With `framework: 'astro'`, the ID is `deploy-on-astro`. Duplicate IDs get a suffix like `-1`, and headings that aren't rendered don't count as duplicates. This needs the `rehypeHeading` plugin, which Fumadocs MDX adds after your rehype plugins. Without it, Remark Heading generates the ID from the source text, like `deploy-on-propsframework`. ### Custom Slugs [#custom-slugs] A custom `slug` function generates IDs from the source text, also for headings with expressions. To use the rendered text with your own slugger, export `createHeadingIds()` from a module: ```ts title="lib/heading.ts" import { createHeadingIds as create } from 'fumadocs-core/mdx-plugins/remark-heading.runtime'; export const createHeadingIds: typeof create = (ids) => // called for each page, so a slugger can count duplicates create(ids, () => (text) => text.toLowerCase().replaceAll(' ', '_')); ``` Then set `slugImportSource` to the module. Compiled pages import it, like the JSX runtime of `jsxImportSource` in MDX, so use a package name or an import alias: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkHeadingOptions: { slug: (_root, _heading, text) => text.toLowerCase().replaceAll(' ', '_'), slugImportSource: '@/lib/heading', }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { remarkHeadingOptions: { slug: (_heading, text) => text.toLowerCase().replaceAll(' ', '_'), slugImportSource: '@/lib/heading', }, }, }); ``` The `slug` function is still used for the headings before the first heading with an expression, so keep the two consistent. ## Rehype TOC [#rehype-toc] A rehype plugin that exports the table of contents. Unlike Remark Heading, it keeps JSX nodes in heading titles. Fumadocs MDX enables it by default. On Sätteri, pass options with `rehypeTocOptions`. ### Output [#output] For a Markdown document: ```md ## Hello `code` ``` The plugin exports it as `toc`: ```jsx export const toc = [ { title: ( <> Hello code ), depth: 2, url: '#hello-code', }, ]; ``` In Fumadocs MDX, `page.data.toc` only lists the headings that are rendered with the page props. A custom content source can do the same with [runtime outputs](/docs/headless/source-api/source#runtime-outputs). # Fumadocs Core (the core library of Fumadocs): MDX Plugins URL: /docs/headless/mdx Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/index.mdx Useful remark & rehype plugins for your docs. - [Headings](/docs/headless/mdx/headings): Process headings from your document - [Package Install](/docs/headless/mdx/install): Generate code blocks for installing packages - [Rehype Code](/docs/headless/mdx/rehype-code): Code syntax highlighter - [Remark Admonition](/docs/headless/mdx/remark-admonition): Use Admonition in Fumadocs - [Remark Image](/docs/headless/mdx/remark-image): Adding size attributes to images. - [Remark Include](/docs/headless/mdx/remark-include): Reuse content from other files. - [Remark LLMs](/docs/headless/mdx/remark-llms): Export the Markdown of your documents for LLMs. - [Remark Files](/docs/headless/mdx/remark-mdx-files): Generate files from codeblocks. - [Remark NPM](/docs/headless/mdx/remark-npm): Generate code blocks for package managers - [Remark Show](/docs/headless/mdx/remark-show): Show content on a condition. - [Remark Steps](/docs/headless/mdx/remark-steps): Generate steps from headings - [Remark TS to JS](/docs/headless/mdx/remark-ts2js): A remark plugin to transform TypeScript codeblocks into two tabs of codeblock with its JavaScript variant. - [Stringification](/docs/headless/mdx/stringification): How Fumadocs turns your documents into Markdown. - [Remark Structure](/docs/headless/mdx/structure): Extract search records from your documents. # Fumadocs Core (the core library of Fumadocs): Package Install URL: /docs/headless/mdx/install Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/install.mdx Generate code blocks for installing packages Use [Remark NPM](/docs/headless/mdx/remark-npm) instead. It is a drop-in replacement, enabled by default in Fumadocs MDX. ## Usage [#usage] ```package-install fumadocs-docgen ``` `remarkInstall` is a remark plugin with no Sätteri version. Add it, and disable Remark NPM which handles `package-install` code blocks first: ```ts title="source.config.ts" import { remarkInstall } from 'fumadocs-docgen'; import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkNpmOptions: false, remarkPlugins: [remarkInstall], }, }); ``` Define the required components. ```tsx title="components/mdx.tsx" import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import defaultComponents from 'fumadocs-ui/mdx'; import type { MDXComponents } from 'mdx/types'; export function getMDXComponents(components?: MDXComponents) { return { ...defaultComponents, // [!code ++:2] Tab, Tabs, ...components, } satisfies MDXComponents; } ``` Create code blocks with `package-install` as language. ````mdx ```package-install my-package ``` ```package-install npm i my-package -D ``` ```` ### Output [#output] ```mdx ... ... ... ... ``` ## Options [#options] ### Persistent [#persistent] When using with Fumadocs UI, you can enable persistence with the `persist` option. ```ts title="source.config.ts" import { remarkInstall } from 'fumadocs-docgen'; import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkNpmOptions: false, remarkPlugins: [[remarkInstall, { persist: { id: 'some-id' } }]], }, }); ``` This will instead generate: ```mdx ... ``` # Fumadocs Core (the core library of Fumadocs): Rehype Code URL: /docs/headless/mdx/rehype-code Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/rehype-code.mdx Code syntax highlighter A wrapper of [`@shikijs/rehype`](https://shiki.style/packages/rehype), the syntax highlighter used by Fumadocs. It converts raw `
` codeblocks into highlighted codeblocks:

````md tab="Input"
```ts
console.log('Hello World');
```
````

```html tab="Output"
  
    
      console...
    
  
``` ## Usage [#usage] Rehype Code is a rehype plugin. Fumadocs MDX enables it by default. Pass options with `rehypeCodeOptions`: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { rehypeCodeOptions: { themes: { light: 'github-light', dark: 'github-dark', }, }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { rehypeCodeOptions: { themes: { light: 'github-light', dark: 'github-dark', }, }, }, }); ``` ### Highlighter [#highlighter] The plugin uses Shiki. `rehypeCodeFromHighlighter` takes another [highlighter](/docs/headless/utils/shiki) like Highlights instead, with the options other than Shiki's. Pass a function to create the highlighter with the transformers of the plugin. Disable the default plugin and add it: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import { rehypeCodeFromHighlighter } from 'fumadocs-core/mdx-plugins/rehype-code.core'; import { highlighter } from './lib/highlighter'; export default defineConfig({ mdxOptions: { rehypeCodeOptions: false, rehypePlugins: [ () => rehypeCodeFromHighlighter(({ transformers }) => highlighter.override({ shikiTransformers: transformers }), ), ], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; import { rehypeCodeFromHighlighter } from '@fumadocs/satteri/rehype-code'; import { highlighter } from './lib/highlighter'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { rehypeCodeOptions: false, hastPlugins: [ rehypeCodeFromHighlighter(({ transformers }) => highlighter.override({ shikiTransformers: transformers }), ), ], }, }); ``` ### Meta [#meta] It parses the `title` meta string, and adds it to the `pre` element as an attribute. ````mdx tab="Input" ```js title="Title" console.log('Hello'); ``` ```` ```jsx tab="Output"
...
``` You may filter the meta string before processing it with the `filterMetaString` option. ### Inline Code [#inline-code] You can enable it with `inline` option: ```ts import { type RehypeCodeOptions } from 'fumadocs-core/mdx-plugins'; const rehypeCodeOptions: RehypeCodeOptions = { // [!code ++] inline: 'tailing-curly-colon', }; ``` ```md title="Syntax" This is a highlighted inline code: `console.log("hello world"){:js}`. ``` This is a highlighted inline code: `console.log("hello world"){:js}`. ### Icon [#icon] The plugin will automatically adds an `icon` attribute according to the language meta string. It is a HTML string, you can render it with React `dangerouslySetInnerHTML`. ````md tab="Input" ```ts console.log('This should shows the logo of TypeScript'); ``` ```` ```jsx tab="Output"
...
``` Disable or customize icons with the `icon` option. ### Unknown Languages [#unknown-languages] A code block with a language that Shiki doesn't support fails the build. To highlight it as another language instead, set `fallbackLanguage`: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { rehypeCodeOptions: { fallbackLanguage: 'plaintext', }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { rehypeCodeOptions: { fallbackLanguage: 'plaintext', }, }, }); ``` ### More Options [#more-options] The options are inherited from [Shiki](https://shiki.style), see their docs for other options. # Fumadocs Core (the core library of Fumadocs): Remark Admonition URL: /docs/headless/mdx/remark-admonition Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-admonition.mdx Use Admonition in Fumadocs In Docusaurus, there's an [Admonition syntax](https://docusaurus.io/docs/markdown-features/admonitions). For people migrating from Docusaurus, you can enable this remark plugin to support the Admonition syntax. ## Usage [#usage] It requires the directive syntax. On unified, install `remark-directive`: ```package-install remark-directive ``` Sätteri parses directives with its `directive` feature, which Fumadocs MDX enables by default. ```ts tab="unified" title="source.config.ts" import remarkDirective from 'remark-directive'; import { remarkDirectiveAdmonition } from 'fumadocs-core/mdx-plugins'; import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkPlugins: [remarkDirective, remarkDirectiveAdmonition], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { remarkDirectiveAdmonition } from '@fumadocs/satteri/remark-directive-admonition'; import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { mdastPlugins: [remarkDirectiveAdmonition()], }, }); ``` ### Example [#example] ```md tab="Input" :::tip[This is a `title`] Hello World ::: :::warning Hello World ::: ``` ```mdx tab="Output" This is a `title` Hello World Hello World ``` ### When to use [#when-to-use] We highly recommend using the JSX syntax of MDX instead. It's more flexible, some editors support IntelliSense in MDX files. ```mdx Hello World ``` # Fumadocs Core (the core library of Fumadocs): Remark Image URL: /docs/headless/mdx/remark-image Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-image.mdx Adding size attributes to images. A remark plugin that adds `width` and `height` attributes to your image elements, which is needed for Image Optimization on Next.js and some other frameworks. ## Usage [#usage] Fumadocs MDX enables it by default. Pass options with `remarkImageOptions`. The options are the same on unified and Sätteri. Supported: - Local Images - External URLs - Next.js static imports ### How It Works [#how-it-works] With `useImport`, local images become **static imports** for your bundler to handle. Fumadocs MDX enables it except in `dynamic` collections. On Next.js, the built-in image loader handles them, which supports the `placeholder` option of Next.js Image. Otherwise, it uses the file system or an HTTP request to download the image and obtain its size. Do not pass untrusted image URLs. They are fetched when compiling, private hosts included. Set `external: false` to skip external images. ### Options [#options] ### RemarkImageOptions | Prop | Type | Description | | -------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `publicDir?` | `string \| undefined` | Directory or base URL to resolve absolute image paths | | `placeholder?` | `"blur" \| "none" \| undefined` | Preferred placeholder type, only available with `useImport` + local images. Default: `'none'` | | `onError?` | `"error" \| "hide" \| "ignore" \| ((error: Error) => void) \| undefined` | Define how to handle errors when fetching image size. - `error` (default): throw an error. - `ignore`: do absolutely nothing (Next.js Image component may complain). - `hide`: remove that image element. Default: `'error'` | | `useImport?` | `boolean \| undefined` | Import images in the file, and let bundlers handle it. ```tsx import MyImage from "./public/img.png"; ``` When disabled, `placeholder` will be ignored. Default: `true` | | `external?` | `ExternalImageOptions \| undefined` | Fetch image size of external URLs Default: `true` | ### Example: With Imports [#example-with-imports] ```mdx ![Hello](/hello.png) ![Test](https://example.com/image.png) ``` Yields: ```mdx import HelloImage from './public/hello.png'; Hello Test ``` Where `./public/hello.png` points to the image in public directory. ### Example: Without Imports [#example-without-imports] For Next.js, you can disable static imports on local images. ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkImageOptions: { useImport: false, }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { remarkImageOptions: { useImport: false, }, }, }); ``` ```mdx ![Hello](/hello.png) ![Test](https://example.com/image.png) ``` Yields: ```mdx Hello Test ``` ### Example: Relative Paths [#example-relative-paths] When `useImport` is enabled, you can reference local images using relative paths. ```mdx ![Hello](./hello.png) ``` Be careful that using it with `useImport` disabled **doesn't work**. Next.js will not add the image to public assets unless you have imported it in code. For images in public directory, you can just reference them without relative paths. ### Example: Public Directory [#example-public-directory] Customize the path of public directory. ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import path from 'node:path'; export default defineConfig({ mdxOptions: { remarkImageOptions: { publicDir: path.join(process.cwd(), 'dir'), }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; import path from 'node:path'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { remarkImageOptions: { publicDir: path.join(process.cwd(), 'dir'), }, }, }); ``` `publicDir` accepts a base URL too, like `https://my-cdn.com/images`. # Fumadocs Core (the core library of Fumadocs): Remark Include URL: /docs/headless/mdx/remark-include Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-include.mdx Reuse content from other files. ## Usage [#usage] Remark Include is a remark plugin. Fumadocs MDX enables it by default on both unified and Sätteri. See [Include](/docs/mdx/include) for the syntax. Paths are relative to the compiled file. On unified, included Markdown & MDX files are parsed by the current processor unless you pass `getProcessor`. Fumadocs MDX passes it, so each file is parsed by its own format. | Prop | Type | Description | | --------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `getProcessor?` | `((format: 'md' \| 'mdx') => Pick) \| undefined` | The processor to parse an included Markdown or MDX file with. Default: `the current processor` | # Fumadocs Core (the core library of Fumadocs): Remark LLMs URL: /docs/headless/mdx/remark-llms Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-llms.mdx Export the Markdown of your documents for LLMs. The `remarkLLMs` plugin exports the Markdown of a document as `_markdown`, for LLMs. It keeps the Markdown you wrote. See [Stringification](/docs/headless/mdx/stringification) for how it's generated. ```mdx tab="Input" import { Callout } from 'fumadocs-ui/components/callout'; ## Getting Started Hello **world**. ``` ```md tab="Output" ## Getting Started [#getting-started] Hello **world**. ``` ESM is removed, headings get their IDs (see `headingIds`), and included content is expanded with Fumadocs MDX. ## Usage [#usage] `remarkLLMs` is a remark plugin. Enable it in Fumadocs MDX with `includeProcessedMarkdown`, on both unified and Sätteri: ```ts title="source.config.ts" import { defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { postprocess: { // `true`, or the options of `remarkLLMs` includeProcessedMarkdown: true, }, }, }); ``` Read it from your pages with `getText('processed')`, which renders the Markdown with the page props: ```ts const markdown = await page.data.getText('processed'); ``` ## Images [#images] Images beside your pages, imported by [Remark Image](/docs/headless/mdx/remark-image), get the URLs your bundler serves them at: ```md tab="Input" ![How a calculation flows](./flow.png) ``` ```md tab="Output" ![How a calculation flows](/assets/flow-Dxg6sAyC.png) ``` Images in the public directory keep their address. Vite inlines images smaller than [`build.assetsInlineLimit`](https://vite.dev/config/build-options#build-assetsinlinelimit) as `data:` URLs. ## Output [#output] The `output` option sets the form of `_markdown`: - `function`: `_markdown` is a component, which you render with [`renderToMarkdown()`](/docs/headless/utils/markdown). The Markdown is generated with the page props: content inside a [``](/docs/next/markdown#show) that isn't rendered is left out, expressions are replaced by their values, and JSX elements by their [Markdown form](#jsx-elements). - `string`: `_markdown` is a string. Expressions and JSX elements are kept as source text, and a document with `` fails to compile. The default is `function` in Fumadocs MDX and `@fumadocs/astro`, and `string` elsewhere. A custom content source gets `function` with [runtime outputs](/docs/headless/source-api/source#runtime-outputs). ## JSX Elements [#jsx-elements] With [`output: 'function'`](#output), a component is looked up like in MDX: first in the imports and declarations of the file, then in the MDX components of the [page props](/docs/headless/source-api#custom-props). Pass MDX components to a page with `getPage()`: ```ts const page = source.getPage(slugs, { props: { components } }); ``` A component defines its Markdown form with [`asMarkdown()`](/docs/headless/utils/markdown#asmarkdown). A component without one is kept as JSX. To remove elements, or replace them with their children, use `filterElement` (unavailable on Sätteri). ### Placeholders [#placeholders] To render JSX elements yourself, list them as placeholders: ```ts import type { LLMsOptions } from 'fumadocs-core/mdx-plugins/remark-llms'; const llmsOptions: LLMsOptions = { mdxAsPlaceholder: ['Callout'], }; ``` Then render them, from runtime data if needed: ```ts import { renderPlaceholder } from 'fumadocs-core/mdx-plugins/remark-llms.runtime'; const markdown = await renderPlaceholder(await page.data.getText('processed'), { // `children` is the Markdown of its content Callout: ({ attributes, children }) => `> **${attributes.title}**\n>\n> ${children}`, }); ``` On Sätteri, `mdxAsPlaceholder` is unavailable. ## Options [#options] | Prop | Type | Description | | ------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `as?` | `string \| undefined` | export name for output Markdown. Default: `_markdown` | | `headingIds?` | `boolean \| undefined` | Explicit heading IDs in output. Default: `true` | | `filterElement?` | `((node: Nodes) => boolean \| 'children-only') \| undefined` | Filter the elements to be included in the output: - `true`: include element & its children. - `children-only`: exclude element but keep its children. - `false`: exclude element & its children. ESM nodes are always excluded. | | `mdxAsPlaceholder?` | `string[] \| undefined` | Tag names of MDX components to be output as placeholders, render them with `renderPlaceholder()`. | | `output?` | `"function" \| "string" \| undefined` | Form of the export: - `string`: the output Markdown, authored expressions keep their source. - `function`: a component, render it with `renderToMarkdown` from `fumadocs-core/server`: JSX elements are kept as JSX, receiving their original props and resolving like in the content, a component can call `asMarkdown()` to define its own Markdown form. Default: `` `function` for a content source that renders pages for props, otherwise `string` `` | # Fumadocs Core (the core library of Fumadocs): Remark Files URL: /docs/headless/mdx/remark-mdx-files Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-mdx-files.mdx Generate files from codeblocks. ## Introduction [#introduction] This plugin takes a codeblock like: ````md ```files project ├── src │ ├── index.js │ └── utils │ └── helper.js ├── package.json ``` ```` and convert into: ```mdx ``` ## Setup [#setup] Remark Files is a remark plugin. Add it to your config: ```ts tab="unified" title="source.config.ts" import { remarkMdxFiles } from 'fumadocs-core/mdx-plugins'; import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkPlugins: [remarkMdxFiles], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { remarkMdxFiles } from '@fumadocs/satteri/remark-mdx-files'; import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { mdastPlugins: [remarkMdxFiles()], }, }); ``` And make sure you have defined ``, ``, `` MDX components. # Fumadocs Core (the core library of Fumadocs): Remark NPM URL: /docs/headless/mdx/remark-npm Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-npm.mdx Generate code blocks for package managers ## Usage [#usage] Remark NPM is a remark plugin. Fumadocs MDX enables it by default. Pass options with `remarkNpmOptions`. Define the required components: ```tsx tab="Custom" title="components/mdx.tsx" import { CodeBlockTabs, CodeBlockTab, CodeBlockTabsList, CodeBlockTabsTrigger } from 'my-ui'; import type { MDXComponents } from 'mdx/types'; export function getMDXComponents(components?: MDXComponents) { return { CodeBlockTabs, CodeBlockTab, CodeBlockTabsList, CodeBlockTabsTrigger, ...components, } satisfies MDXComponents; } ``` ```tsx tab="Fumadocs UI" title="components/mdx.tsx" import defaultComponents from 'fumadocs-ui/mdx'; import type { MDXComponents } from 'mdx/types'; export function getMDXComponents(components?: MDXComponents) { return { // it's included by default in `defaultComponents` ...defaultComponents, ...components, } satisfies MDXComponents; } ``` ### Input [#input] Create code blocks with `npm` as language. ````mdx ```npm npm i my-package ``` ```npm npm i my-package -D ``` ```` `package-install` code blocks work too. They take package names, like `my-package`, and turn them into `npm install` commands. ### Output [#output] The following structure should be generated by the plugin. ```mdx npm pnpm yarn bun ... ... ... ... ``` ```npm npm i my-package ``` ### Persistent [#persistent] When using with Fumadocs UI, you can persist the selected value with the `persist` option. ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkNpmOptions: { persist: { id: 'package-manager', }, }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { remarkNpmOptions: { persist: { id: 'package-manager', }, }, }, }); ``` This will generate a [`persist`](/docs/ui/components/tabs#persistent) prop to ``. # Fumadocs Core (the core library of Fumadocs): Remark Show URL: /docs/headless/mdx/remark-show Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-show.mdx Show content on a condition. ## Usage [#usage] Remark Show is a remark plugin for the [``](/docs/next/markdown#show) syntax. Fumadocs MDX, `@fumadocs/astro` and [Local Markdown](/docs/next/integrations/content/local-md) enable it by default. `` renders its content when the `when` expression is true. The expression is evaluated when the page renders, so it can read the page props, like [path params](/docs/headless/page-conventions#path-params). A `` without `when` fails to compile. ## Page Data [#page-data] Content that isn't rendered is also left out of the page data: the table of contents, [heading IDs](/docs/headless/mdx/headings#headings-with-expressions), [structured data](/docs/headless/mdx/structure) and [processed Markdown](/docs/headless/mdx/remark-llms). The data comes from Rehype TOC, Remark Structure and Remark LLMs. Without Fumadocs MDX, they generate it at compile time, before any condition can be evaluated, so a document with `` fails to compile. In a custom content source, enable [runtime outputs](/docs/headless/source-api/source#runtime-outputs). ## Steps and Tab Groups [#steps-and-tab-groups] `` can wrap a [step](/docs/headless/mdx/remark-steps), or a code block of a [tab group](/docs/next/markdown#tab-groups). See the [example](/docs/next/markdown#show). - Add Remark Show before Remark Steps and `remarkCodeTab` in your plugins. - Keep at least one step, or one tab, outside ``. Otherwise each `` gets its own steps or tab group. # Fumadocs Core (the core library of Fumadocs): Remark Steps URL: /docs/headless/mdx/remark-steps Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-steps.mdx Generate steps from headings ## Usage [#usage] Remark Steps is a remark plugin. Add it to your config: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import { remarkSteps } from 'fumadocs-core/mdx-plugins/remark-steps'; export default defineConfig({ mdxOptions: { remarkPlugins: [remarkSteps], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; import { remarkSteps } from '@fumadocs/satteri/remark-steps'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { mdastPlugins: [remarkSteps()], }, }); ``` ### Input [#input] Create step headings: ```md tab="Using Tag" # Heading 1 [step] ## Sub Heading 1 [step] ## Sub Heading 2 [step] # Heading 2 [step] ``` ```md tab="Using Number" # 1. Heading 1 ## 1. Sub Heading 1 ## 2. Sub Heading 2 # 2. Heading 2 ``` ### Output [#output] The following structure should be generated by the plugin. ```mdx
# Heading 1
## Sub Heading 1
## Sub Heading 2
# Heading 2
``` # Fumadocs Core (the core library of Fumadocs): Remark TS to JS URL: /docs/headless/mdx/remark-ts2js Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/remark-ts2js.mdx A remark plugin to transform TypeScript codeblocks into two tabs of codeblock with its JavaScript variant. ## Usage [#usage] Install the dependencies: ```package-install tab="unified" fumadocs-docgen ``` ```package-install tab="Sätteri" @fumadocs/satteri ``` Remark TS to JS is a remark plugin. Add it to your config: ```ts tab="unified" title="source.config.ts" import { remarkTypeScriptToJavaScript } from 'fumadocs-docgen/remark-ts2js'; import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkPlugins: [remarkTypeScriptToJavaScript], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { remarkTs2js } from '@fumadocs/satteri/remark-ts2js'; import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { mdastPlugins: [remarkTs2js()], }, }); ``` It generates the same `CodeBlockTabs` components as [Remark NPM](/docs/headless/mdx/remark-npm#usage), which Fumadocs UI includes by default. You can now enable it on TypeScript/TSX codeblocks, like: ````md ```tsx ts2js import { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return
{children}
; } ``` ```` ```tsx ts2js import { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return
{children}
; } ``` # Fumadocs Core (the core library of Fumadocs): Stringification URL: /docs/headless/mdx/stringification Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/stringification.mdx How Fumadocs turns your documents into Markdown. [Remark LLMs](/docs/headless/mdx/remark-llms) and [Remark Structure](/docs/headless/mdx/structure) output Markdown, for LLMs and search. Instead of stringifying the syntax tree, they slice your authored source: - Markdown stays as you wrote it, nothing is escaped or reformatted. - Remark plugins change it only by recording edits. - It's fast, since no syntax tree is serialized. ## How It Works [#how-it-works] The output is the source of your document, with the edits of plugins applied. Nodes are located by their `position`: - A node with a `position` outputs its source. - A node without one, like those inserted by plugins, outputs nothing. Its plugin defines its Markdown instead. For example, [Remark Image](/docs/headless/mdx/remark-image) turns `![alt](/image.png)` into an `` element, and the output keeps `![alt](/image.png)`. ## Editing the Output [#editing-the-output] A plugin replacing authored content records the Markdown of its node with `replaceSource()`: ```ts title="remark-note.ts" import type { Root } from 'mdast'; import type { VFile } from 'vfile'; import { visit } from 'unist-util-visit'; import { replaceSource } from 'fumadocs-core/mdx-plugins/stringifier'; export function remarkNote() { return (tree: Root, file: VFile) => { visit(tree, 'mdxJsxFlowElement', (node) => { if (node.name !== 'Note') return; replaceSource(file, node, (s) => `**Note:**\n\n${s.inner(node)}`); // transform the node for rendering... }); }; } ``` - A string replaces the node, along with the edits inside it. - A function runs after every plugin. `s.stringify(node)` and `s.inner(node)` (its children) give their Markdown, with the edits inside. - When a node is edited more than once, the last edit wins. To edit one output only, pass its namespace as the last argument: `search` for the records of Remark Structure, `markdown` for Remark LLMs. ```ts // the Markdown for LLMs keeps the tag, search records don't replaceSource(file, node, (s) => s.stringify(node).replace(' [step]', ''), 'search'); ``` For search, a plugin adds the records of its nodes with [`data.structuredData`](/docs/headless/mdx/structure#plugins). ### Runtime Values [#runtime-values] For Markdown only known at runtime, output a JS expression with `s.expression()`. Remark LLMs evaluates it where it exports the Markdown. Other outputs use the fallback: ```ts import type { Expression } from 'estree'; // the URL of `import image from './image.png'` in the compiled document const url: Expression = { type: 'Identifier', name: 'image' }; replaceSource(file, node, (s) => `![alt](${s.expression(url, './image.png')})`); ``` ## Embedded Content [#embedded-content] Nodes parsed from another source, like an [included file](/docs/mdx/include), have positions in that source. Embed them with `embedSource()` to stringify them like your own content: ```ts import { embedSource } from 'fumadocs-core/mdx-plugins/stringifier'; // replaces `node` with the nodes parsed from `otherSource` embedSource(file, node, otherSource, otherTree.children); ``` Other nodes parsed from a string must not keep their `position`, because it doesn't point into your document. The helpers on this page are for unified plugins. On Sätteri, Remark LLMs and Remark Structure output Markdown the same way, with no public API to edit it. # Fumadocs Core (the core library of Fumadocs): Remark Structure URL: /docs/headless/mdx/structure Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/mdx/structure.mdx Extract search records from your documents. The `remarkStructure` plugin extracts the headings and contents of a document as records for [search](/docs/headless/search). Records keep the Markdown you wrote. See [Stringification](/docs/headless/mdx/stringification) for how it's generated. ```mdx tab="Input" ## Installation Run the [command](/docs/cli) below. Restart the **server** after it. | Option | Default | | ------ | ------- | | `dir` | `docs` | ``` ```json tab="Output" { "headings": [{ "id": "installation", "content": "Installation" }], "contents": [ { "heading": "installation", "content": "Run the command below." }, { "heading": "installation", "content": "Restart the **server** after it." }, { "heading": "installation", "content": "| Option | Default |\n| --- | --- |\n| `dir` | `docs` |", "table": "table-0" } ] } ``` ## Usage [#usage] Remark Structure is a remark plugin. Fumadocs MDX enables it by default and exports the records as `structuredData`. Pass options with `remarkStructureOptions`. In Fumadocs MDX, the records are generated with the page props: content inside a [``](/docs/next/markdown#show) that isn't rendered is left out, and expressions are replaced by their values. Outside Fumadocs MDX, expressions are kept as source text. ## Records [#records] Headings, paragraphs, blockquotes, tables and JSX elements are recorded (see `types`): - Links are replaced by their text, images are removed. - A table has a record per row, as a table of its header and that row. The rows share a `table` field. - JSX elements are replaced by their content, except those that `filterElement` keeps (see [Components](#components)). - A JSX element is a record when it has no children (see `mdxTypes`), or fits on one line. - Content inside a record isn't recorded again. In Fumadocs MDX, the plugin keeps the elements of components by default, like `` but not `
`. Outside Fumadocs MDX, it keeps `File`, `TypeTable`, `Callout` and `Card`. Change it with `filterElement`: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { remarkStructureOptions: { filterElement: (node) => node.name === 'Callout' || node.name === 'Banner', }, }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri' }, }); export default defineConfig({ satteriOptions: { remarkStructureOptions: { filterElement: (node) => node.name === 'Callout' || node.name === 'Banner', }, }, }); ``` ## Components [#components] In Fumadocs MDX, a kept JSX element is recorded in one of two forms, depending on how you read the records: - `page.data.structuredData`: components aren't rendered. The element is kept as an HTML tag, which search dialogs render as a component. With `async` or `dynamic` collections, read it from the loaded page. - `await page.data.structuredData()`: components are rendered for the [`search` target](/docs/headless/utils/markdown#targets), and the element is replaced by its Markdown form. Only `async` and `dynamic` collections have this function. When rendering, a component is looked up like in MDX: first in the imports and declarations of the file, then in the MDX components of the [page props](/docs/headless/source-api#custom-props). Search reads pages from `getPages()`, which have no custom props. Import or declare a component in the file if search should render it. A component defines its text for search with [`asMarkdown()`](/docs/headless/utils/markdown#asmarkdown): ```tsx import { asMarkdown } from 'fumadocs-core/server'; export function ProductName() { if (asMarkdown()) return 'Fumadocs'; return Fumadocs; } ``` A component without a Markdown form is kept as JSX syntax, like an MDX component that is missing from the page props. ## Plugins [#plugins] Nodes inserted by plugins aren't recorded. A plugin adds the records of its node with `data.structuredData`: ```ts node.data = { ...node.data, structuredData: { // `heading` defaults to the current heading contents: [{ heading: undefined, content: 'Generated **content**' }], }, }; ``` To change the Markdown of authored content in records only, edit the `search` namespace with [`replaceSource()`](/docs/headless/mdx/stringification#editing-the-output). ## As a Function [#as-a-function] On unified, `structure()` extracts the records from a string: ```ts import { structure } from 'fumadocs-core/mdx-plugins'; import remarkMath from 'remark-math'; // with the remark plugins your content needs const data = structure(content, [remarkMath], options); ``` ## Options [#options] ### StructureOptions | Prop | Type | Description | | ---------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `types?` | `string[] \| ((node: Nodes) => boolean) \| undefined` | MDAST node types to be scanned as a content block. If a node's type is listed in this array, it will be converted into a single content block, except tables which become a content block per row, along with the header row. Default: `['heading', 'paragraph', 'blockquote', 'table', 'mdxJsxFlowElement']` | | `mdxTypes?` | `((node: JsxElement) => boolean) \| undefined` | Whether the MDX element should be treated as a single content block, only effective if `types` has `mdxJsxFlowElement`. Default: return `true` if the element is a leaf node, otherwise `false`. | | `filterElement?` | `((node: JsxElement) => boolean) \| undefined` | Return `true` to keep a JSX element, other elements are replaced by their content. Kept elements are HTML tags, or render into Markdown like processed Markdown when the export is a function of the props. Default: `File`, `TypeTable`, `Callout` and `Card` elements, or the elements of components when the export is a function of the props. | | `exportAs?` | `string \| boolean \| undefined` | export as `structuredData` (if true) or specified variable name. | # Fumadocs Core (the core library of Fumadocs): Page Slugs & Page Tree URL: /docs/headless/page-conventions Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/page-conventions.mdx Customize generated page slugs and page tree. > This guide only applies for content sources that uses `loader()` API, such as **Fumadocs MDX**. ## Overview [#overview] Fumadocs generates **page slugs** and **page tree** (sidebar items) from your content directory using [`loader()`](/docs/headless/source-api), the routing functionality will be handled by your React framework. You can define folders and pages similar to file-system based routing. To customize its output further, you may use [Loader Plugins](/docs/headless/source-api/plugins). ## File [#file] For [MDX](https://mdxjs.com) & Markdown file, you can customize page information from frontmatter. ```mdx --- title: My Page description: Best document ever icon: House --- ## Learn More ``` Fumadocs detects from the following properties to construct page trees. | name | description | | ------------- | ------------------------------------- | | `title` | The title of page | | `description` | The description of page | | `icon` | The name of icon, see [Icons](#icons) | Page information is supplied by the content source such as **Fumadocs MDX**. On Fumadocs MDX, you can specify a [`schema`](/docs/mdx/collections#schema-1) option to customize frontmatter schema. ### Slugs [#slugs] The slugs of a page are generated from its file path. | path (relative to content folder) | slugs | | --------------------------------- | ----------------- | | `./dir/page.mdx` | `['dir', 'page']` | | `./dir/index.mdx` | `['dir']` | ## Folder [#folder] Put multiple pages in a folder to group them, and create a [meta file](#meta) to customize the folder. A folder with `index` as its only page becomes a page item in the page tree, unless the folder has a meta file. For example, `guide/index.mdx` appears in the sidebar the same way as `guide.mdx`. ### Folder Group [#folder-group] By default, putting a file into folder will change its slugs. You can wrap the folder name in parentheses to avoid impacting the slugs of child files. | path (relative to content folder) | slugs | | --------------------------------- | ---------- | | `./(group-name)/page.mdx` | `['page']` | ### Root Folder [#root-folder] Marks the folder as a root folder, only items in the opened root folder will be visible. ```json title="meta.json" { "title": "Name of Folder", "description": "The description of root folder (optional)", "root": true } ``` For example, when you are opening root folder `framework`, the other folders (e.g. `headless`) are not shown on the sidebar and other navigation elements. Fumadocs UI renders root folders as [Layout Tabs](/docs/ui/layouts/docs#layout-tabs), which allows users to switch between them. ### Root Type [#root-type] `root` also accepts a string, the **type** of root folder: root folders of the same type under the same parent scope are interchangeable, such as versions of the same docs. ```json tab="v1/meta.json" { "title": "1.0.0", "root": "version" } ``` ```json tab="v2/meta.json" { "title": "2.0.0", "root": "version" } ``` `root: true` is simply the default type, displayed as tabs. Switching to another root folder of the same type maps a page to its **structural projection**, the page at the same path relative to the root folder: | Page | Projection in `v2` | | --------------------- | --------------------------------------------------- | | `v1/guide.mdx` | `v2/guide.mdx` | | `v1/python/guide.mdx` | `v2/python/guide.mdx`, nested root folders are kept | Fumadocs UI renders a [dropdown](/docs/ui/layouts/docs#tabs-groups) for each root folder on the current page's path to switch between root folders of its type, see [Versioning](/docs/next/navigation#versioning) for a complete example. ## Meta [#meta] Customize folders by creating a `meta.json` file in the folder. ```json tab="meta.json" { "title": "Display Name", "icon": "MyIcon", "pages": ["index", "getting-started"], "defaultOpen": true } ``` ```ts tab="meta.ts" export default { title: 'Display Name', icon: 'MyIcon', pages: ['index', 'getting-started'], defaultOpen: true, }; ``` When your content source supports it, you can write meta files in code (`meta.ts` or `meta.js`), with the data as default export. | name | description | | ------------- | -------------------------------------------- | | `title` | Display name | | `icon` | The name of icon, see [Icons](#icons) | | `defaultOpen` | Open the folder by default | | `collapsible` | Collapsible folder content (default: `true`) | | `pages` | Folder items (see below) | | `pagesIndex` | The index item (see below) | ### Pages [#pages] Folder items are sorted alphabetically by default, you can add or control the order of items using `pages`. ```json title="meta.json" { "pages": ["index", "getting-started"] } ``` > When specified, items are not included unless they are listed in `pages`. | Type | Syntax | Description | | ----------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | **Path** | `./path/to/page` | a path to page or folder. | | **Separator** | `---Label---`
`---[Icon]Label---` | a separator between two sections (icon supported). | | **Link** | `[Text](url)`
`[Icon][Text](url)`
`external:[Text](url)` | insert links (icon supported)
add a `external:` prefix to mark links as external. | | **Rest** | `...` | include remaining pages (sorted alphabetically). | | **Reversed Rest** | `z...a` | reversed **Rest** item. | | **Extract** | `...folder` | extract the items from a folder. | | **Except** | `!item` | Exclude an item from `...` or `z...a`. | ```json title="meta.json" { "pages": [ "components", "---My Separator---", "...folder", "...", "!file", "!otherFolder", "[Vercel](https://vercel.com)", "[Triangle][Vercel](https://vercel.com)" ] } ``` The same page URL must not appear more than once in the entire page tree. Duplicated page items are not allowed for the same reason. This is intentional, such that Fumadocs can locate the active tree item purely based on current pathname. ### Folder Index [#folder-index] When folder owns a index item, it becomes clickable and jumps to the index item when clicked. By default, it is the `index` file under each folder. You can specify the index item of a folder, it accepts **Path** and **Link**. ```json tab="meta.json (Path)" { // assume there's a "overview.mdx" file under the folder "pagesIndex": "overview" } ``` ```json tab="meta.json (Link)" { "pagesIndex": "[Example](https://example.com)" } ``` ## Icons [#icons] Since Fumadocs doesn't include an icon library, you have to convert the icon names to JSX elements in runtime, and render it as a component. You can add an [`icon` handler](/docs/headless/source-api#icons) to `loader()`. ## i18n Routing [#i18n-routing] You can define different style for i18n routing. ```ts title="lib/i18n.ts" import type { I18nConfig } from 'fumadocs-core/i18n'; export const i18n: I18nConfig = { // default parser: 'dot', // or parser: 'dir', }; ``` Add Markdown/meta files for different languages by appending `.{locale}` to your file name, like: For the default locale, the locale code is optional. All content files are grouped by language folders: ## Path Params [#path-params] A folder named `[name]` is generated for each value of the param. List the values in `staticParams` of its meta file: ```json title="[framework]/meta.json" { "title": "Framework", "staticParams": [{ "framework": "waku" }, { "framework": "astro" }] } ``` | path (relative to content folder) | slugs | | --------------------------------- | ------------------------------------------- | | `./[framework]/deploy.mdx` | `['waku', 'deploy']`, `['astro', 'deploy']` | The meta file applies to every generated folder. Pages receive their params as [props](/docs/next/markdown#props), and as `page.params` from `loader()`. In `meta.ts`, you can export a function of the params instead, with `staticParams` as a named export: ```ts title="[framework]/meta.ts" const names = { waku: 'Waku', astro: 'Astro' }; export const staticParams = [{ framework: 'waku' }, { framework: 'astro' }]; export default ({ framework }: { framework: keyof typeof names }) => ({ title: names[framework], }); ``` A `[name]` folder stays a normal folder when nothing lists its values. ### Page Params [#page-params] A page can also list `staticParams` in its frontmatter. When its folder lists them too, the page is only generated for the values in both. ```mdx title="[framework]/fumadocs-mdx.mdx" --- title: Fumadocs MDX staticParams: - framework: waku --- ``` ### Static Paths [#static-paths] Files at a literal path take priority over generated ones. For example, `astro/deploy.mdx` replaces the `astro` page of `[framework]/deploy.mdx`. The same applies to meta files. ### Localized Pages [#localized-pages] With [i18n](#i18n-routing), the files of a locale take priority over those of its fallback locale. For `/cn/docs/astro/deploy`, the first existing file is used: 1. `astro/deploy.cn.mdx` 2. `[framework]/deploy.cn.mdx` 3. `astro/deploy.mdx` 4. `[framework]/deploy.mdx` Localized pages read `staticParams` from `meta.cn.json` first. With the `dir` parser, each language folder lists its own values. # Fumadocs Core (the core library of Fumadocs): Page Tree URL: /docs/headless/page-tree Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/page-tree.mdx The structure of page tree. Page tree is a tree structure that describes all navigation links, with other items like separator and folders. It will be sent to the client and being referenced in navigation elements including the sidebar and breadcrumb. Hence, you shouldn't store any sensitive or large data in page tree. By design, page tree only contains necessary information of all pages and folders. Unserializable data such as functions can't be passed to page tree. ## Conventions [#conventions] You can import the type definitions of page tree, useful if you want to hardcode or generate it. ```ts import type * as PageTree from 'fumadocs-core/page-tree'; const tree: PageTree.Root = { // props }; ``` Certain nodes contain a `$ref` property, they are internal and not used when hardcoding it. ### Root [#root] The initial root of page trees. ### PageTreeRoot | Prop | Type | Description | | -------------- | ---------------------------- | ------------------------------------------------------------------------- | | `type?` | `"root" \| undefined` | | | `name` | `React.ReactNode` | | | `description?` | `React.ReactNode` | | | `children` | `PageTree.Node[]` | | | `fallback?` | `PageTree.Root \| undefined` | Another page tree that won't be displayed unless being opened. | | `$id?` | `string \| undefined` | ID for the node, unique in all page trees (even across different locales) | ### Page [#page] A node representing link. ```json { "type": "page", "name": "Quick Start", "url": "/docs" } ``` > External urls are also supported ### PageTreeItem | Prop | Type | Description | | -------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `type` | `"page"` | | | `name` | `React.ReactNode` | | | `url` | `string` | | | `external?` | `boolean \| undefined` | Whether the link should be treated as external (e.g. use HTML
tag). When unspecified, it depends on the value of `url`. | | `description?` | `React.ReactNode` | | | `icon?` | `React.ReactNode` | | | `$id?` | `string \| undefined` | ID for the node, unique in all page trees (even across different locales) | ### Folder [#folder] A node containing multiple children nodes. ```json { "type": "folder", "name": "Guide", "index": { "type": "page", ... } "children": [ ... ] } ``` ### PageTreeFolder | Prop | Type | Description | | -------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | `"folder"` | | | `name` | `React.ReactNode` | | | `description?` | `React.ReactNode` | | | `root?` | `string \| boolean \| undefined` | Mark as a root folder, `true` for the default type. A string value specifies its **root type**: root folders of the same type under the same parent scope are interchangeable (e.g. versions), and pages can map to their structural projection in another root. | | `defaultOpen?` | `boolean \| undefined` | | | `collapsible?` | `boolean \| undefined` | | | `index?` | `PageTree.Item \| undefined` | | | `icon?` | `React.ReactNode` | | | `children` | `PageTree.Node[]` | | | `$id?` | `string \| undefined` | ID for the node, unique in all page trees (even across different locales) | ### Separator [#separator] A label between items. ```json { "type": "separator", "name": "Components" } ``` ### PageTreeSeparator | Prop | Type | Description | | ------- | --------------------- | ------------------------------------------------------------------------- | | `type` | `"separator"` | | | `name?` | `React.ReactNode` | | | `icon?` | `React.ReactNode` | | | `$id?` | `string \| undefined` | ID for the node, unique in all page trees (even across different locales) | ## Icons [#icons] Icon is a `ReactElement`, supported by pages and folders. # Fumadocs Core (the core library of Fumadocs): Algolia Search URL: /docs/headless/search/algolia Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/algolia.mdx Integrate Algolia Search with Fumadocs If you're using Algolia's free tier, you have to [display their logo on your search dialog](https://algolia.com/policies/free-services-terms). ## Setup [#setup] Install dependencies: ```package-install algoliasearch ``` ### Sign up on Algolia [#sign-up-on-algolia] Sign up and obtain the app id and API keys for your search, store them in `.env.local` (`NEXT_PUBLIC_` is `VITE_` on Vite frameworks, `PUBLIC_` on Astro): ```dotenv NEXT_PUBLIC_ALGOLIA_APP_ID="app ID" NEXT_PUBLIC_ALGOLIA_SEARCH_KEY="search-only API key" ALGOLIA_WRITE_KEY="write API key" ``` ### Sync Search Indexes [#sync-search-indexes] Pre-render a `static.json` route to export the search indexes on build, and sync them to Algolia with a script after each build: ```ts tab="Next.js" title="app/static.json/route.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export const revalidate = false; export async function GET() { return Response.json(await toDocuments(source)); } ``` ```ts tab="Next.js" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/algolia'; import { algoliasearch } from 'algoliasearch'; // Next.js writes it under `route-cache` when built with an adapter, like on Vercel const [file] = await Array.fromAsync(fs.glob('.next/server/{app,route-cache/*/*/$}/static.json.body')); const records = JSON.parse(await fs.readFile(file, 'utf-8')) as DocumentRecord[]; const client = algoliasearch( process.env.NEXT_PUBLIC_ALGOLIA_APP_ID!, process.env.ALGOLIA_WRITE_KEY!, ); await sync(client, { indexName: 'document', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Next.js" title="package.json" { "scripts": { "build": "next build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="React Router" title="app/routes/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export async function loader() { return Response.json(await toDocuments(source)); } ``` ```ts tab="React Router" title="app/routes.ts" import { index, route, type RouteConfig } from '@react-router/dev/routes'; export default [ index('routes/home.tsx'), route('static.json', 'routes/static.json.ts'), // [!code ++:1] ] satisfies RouteConfig; ``` ```ts tab="React Router" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/algolia'; import { algoliasearch } from 'algoliasearch'; const records = JSON.parse(await fs.readFile('build/client/static.json', 'utf-8')) as DocumentRecord[]; const client = algoliasearch( process.env.VITE_ALGOLIA_APP_ID!, process.env.ALGOLIA_WRITE_KEY!, ); await sync(client, { indexName: 'document', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="React Router" title="package.json" { "scripts": { "build": "react-router build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="TanStack Start" title="src/routes/static[.]json.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export const Route = createFileRoute('/static.json')({ server: { handlers: { GET: async () => Response.json(await toDocuments(source)), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { nitro } from 'nitro/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, pages: [ // [!code ++:3] { path: '/static.json' } ], }), nitro({ preset: 'vercel', }), ], }); ``` ```ts tab="TanStack Start" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/algolia'; import { algoliasearch } from 'algoliasearch'; const records = JSON.parse(await fs.readFile('.vercel/output/static/static.json', 'utf-8')) as DocumentRecord[]; const client = algoliasearch( process.env.VITE_ALGOLIA_APP_ID!, process.env.ALGOLIA_WRITE_KEY!, ); await sync(client, { indexName: 'document', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="TanStack Start" title="package.json" { "scripts": { "build": "vite build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Waku" title="src/pages/_api/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export async function GET() { return Response.json(await toDocuments(source)); } export async function getConfig() { return { render: 'static' as const, } as const; } ``` ```ts tab="Waku" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/algolia'; import { algoliasearch } from 'algoliasearch'; const records = JSON.parse(await fs.readFile('dist/public/static.json', 'utf-8')) as DocumentRecord[]; const client = algoliasearch( process.env.VITE_ALGOLIA_APP_ID!, process.env.ALGOLIA_WRITE_KEY!, ); await sync(client, { indexName: 'document', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Waku" title="package.json" { "scripts": { "build": "waku build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Astro" title="src/pages/static.json.ts" import type { APIRoute } from 'astro'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export const prerender = true; export const GET: APIRoute = async () => Response.json(await toDocuments(source)); ``` ```ts tab="Astro" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/algolia'; import { algoliasearch } from 'algoliasearch'; const records = JSON.parse(await fs.readFile('dist/static.json', 'utf-8')) as DocumentRecord[]; const client = algoliasearch( process.env.PUBLIC_ALGOLIA_APP_ID!, process.env.ALGOLIA_WRITE_KEY!, ); await sync(client, { indexName: 'document', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Astro" title="package.json" { "scripts": { "build": "astro build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` `sync()` updates the index settings and replaces all records. The `build` script syncs on every build, set the same variables on your deployment platform. ### Search UI [#search-ui] You can consider different options for implementing the UI: - Using [Fumadocs UI search dialog](/docs/next/search/algolia). - Build your own using the built-in search client hook: ```ts twoslash import { liteClient } from 'algoliasearch/lite'; import { useAlgoliaSearch } from 'fumadocs-core/search/client'; const algolia = liteClient('id', 'key'); const { search, onSearchChange, isLoading, data } = useAlgoliaSearch({ indexName: 'document', client: algolia, }); ``` - Use their official clients directly. ## Advanced [#advanced] ### Tag Filter [#tag-filter] To configure tag filtering, pass a `tag` to `toDocuments()` in the `static.json` route: ```ts toDocuments(source, { tag: (page) => page.slugs[0] }); ``` And update your search client: - **Fumadocs UI**: Enable [Tag Filter](/docs/next/search/algolia#tag-filter) on Search UI. - **Search Client**: You can add the tag filter like: ```ts import { useAlgoliaSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useAlgoliaSearch({ tag: '', // ... }); ``` The `tag` field is an attribute for faceting. You can also use the filter `tag:value` on Algolia search clients. ### Under the Hood [#under-the-hood] The Algolia Integration automatically configures Algolia Search for document search. It creates a record for **each paragraph** in your document, it is also recommended by Algolia. Each record contains searchable attributes: | Attribute | Description | | --------- | --------------------- | | `title` | Page Title | | `section` | Heading ID (nullable) | | `content` | Paragraph content | The `section` field only exists in paragraphs under a heading. Headings and paragraphs are indexed as an individual record, grouped by their page ID. Notice that it expects the `url` property of a page to be unique, you shouldn't have two pages with the same url. # Fumadocs Core (the core library of Fumadocs): FlexSearch URL: /docs/headless/search/flexsearch Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/flexsearch.mdx Fast & minimal document search ## Setup [#setup] ```npm npm install flexsearch ``` ```npm npm install @types/flexsearch -D ``` ### From Source [#from-source] Create the server from source object. ```ts tab="Next.js" title="app/api/search/route.ts" import { source } from '@/lib/source'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; export const { GET } = flexsearchFromSource(source); ``` ```ts tab="React Router" title="app/routes/search.ts" import type { Route } from './+types/search'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; import { source } from '@/lib/source'; const server = flexsearchFromSource(source); export async function loader({ request }: Route.LoaderArgs) { return server.GET(request); } ``` ```ts tab="TanStack Start" title="src/routes/api/search.ts" import { createFileRoute } from '@tanstack/react-router'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; import { source } from '@/lib/source'; const server = flexsearchFromSource(source); export const Route = createFileRoute('/api/search')({ server: { handlers: { GET: async ({ request }) => server.GET(request), }, }, }); ``` ```ts tab="Waku" title="src/pages/_api/api/search.ts" import { source } from '@/lib/source'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; export const { GET } = flexsearchFromSource(source); ``` ```ts tab="Astro" title="src/pages/api/search.ts" import type { APIRoute } from 'astro'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; import { source } from '@/lib/source'; // render per request, needs an adapter export const prerender = false; const server = flexsearchFromSource(source); export const GET: APIRoute = ({ request }) => server.GET(request); ``` ### From Search Indexes [#from-search-indexes] Create the server from search indexes, each index needs a `structuredData` field. Usually, it is provided by your content source (e.g. Fumadocs MDX). You can also extract it from Markdown/MDX document using the [Remark Structure](/docs/headless/mdx/structure) plugin. Serve it from your search route in place of `flexsearchFromSource()`: ```ts import { source } from '@/lib/source'; import { flexsearch } from 'fumadocs-core/search/flexsearch'; const server = flexsearch({ indexes: source.getPages().map((page) => ({ title: page.data.title!, description: page.data.description, url: page.url, id: page.url, structuredData: page.data.structuredData, })), }); ``` ### Searching Documents [#searching-documents] You can search documents using: - **Fumadocs UI**: Supported out-of-the-box, see [Search UI](/docs/next/search/flexsearch) for details. - **Search Client**: ```ts twoslash import { useFetchSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useFetchSearch(); ``` | Prop | Type | Description | | --------- | -------------------------------------------------- | ------------------------------------------------------------------------------ | | `api?` | `string \| undefined` | API route for search endpoint, support absolute URLs. Default: `'/api/search'` | | `tag?` | `string \| string[] \| undefined` | Filter results with specific tag(s). | | `locale?` | `string \| undefined` | Filter by locale | | `cache?` | `Map[]> \| undefined` | | ## Configurations [#configurations] ### Tag Filter [#tag-filter] Support filtering results by tag, it's useful for implementing multi-docs similar to this documentation. ```ts import { source } from '@/lib/source'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; const server = flexsearchFromSource(source, { buildIndex(page) { return { title: page.data.title!, description: page.data.description, url: page.url, id: page.url, structuredData: page.data.structuredData, // use your desired value, like page.slugs[0] [!code ++:2] tag: '', }; }, }); ``` and update your search client: - **Fumadocs UI**: Configure [Tag Filter](/docs/next/search/flexsearch#tag-filter) on Search UI. - **Search Client**: pass a tag to `useFetchSearch()`. ```ts import { useFetchSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useFetchSearch({ tag: '', // [!code ++] }); ``` ### Static Mode [#static-export] To support usage with static site, use `staticGET` from search server and make the route static or pre-rendered. ```ts tab="Next.js" title="app/api/search/route.ts" import { source } from '@/lib/source'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; // statically cached [!code highlight:3] export const revalidate = false; export const { staticGET: GET } = flexsearchFromSource(source); ``` ```ts tab="React Router" title="app/routes/search.ts" // make sure this route is pre-rendered in `react-router.config.ts`. export async function loader() { // [!code highlight] return server.staticGET(); } ``` ```ts tab="TanStack Start" title="src/routes/api/search.ts" import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/api/search')({ server: { handlers: { // [!code highlight] GET: async () => server.staticGET(), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, // [!code ++:2] pre-render the index file pages: [{ path: '/api/search' }], }), ], }); ``` ```ts tab="Waku" title="src/pages/_api/api/search.ts" import { source } from '@/lib/source'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; // [!code highlight] export const { staticGET: GET } = flexsearchFromSource(source); // statically cached [!code highlight:4] export const getConfig = async () => ({ render: 'static', }); ``` ```ts tab="Astro" title="src/pages/api/search.ts" import type { APIRoute } from 'astro'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; import { source } from '@/lib/source'; const server = flexsearchFromSource(source); // prerendered by default [!code highlight] export const GET: APIRoute = () => server.staticGET(); ``` > `staticGET` is also available on `flexsearch()`. and update your search clients: - **Fumadocs UI**: use [static client](/docs/next/search/flexsearch#static) on Search UI. - **Search Client**: change your client adapter. ```ts import { useFlexsearchStatic } from 'fumadocs-core/search/client/flexsearch-static'; const { search, onSearchChange, isLoading, data } = useFlexsearchStatic({ // optional: pass tag & locale tag, }); ``` | Prop | Type | Description | | --------- | --------------------------------- | ---------------------------- | | `from?` | `string \| undefined` | Default: `` `/api/search` `` | | `locale?` | `string \| undefined` | | | `tag?` | `string \| string[] \| undefined` | | Static Search requires clients to download the exported search indexes. For large docs sites, it can be expensive. You should use cloud solutions like Orama Cloud or Algolia for these cases. ## Internationalization [#internationalization] Flexsearch doesn't require configurations to work for other languages, but you can improve the results by specifying Flexsearch options for each locale. ```ts tab="From Source" import { source } from '@/lib/source'; import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch'; import { Charset } from 'flexsearch'; const server = flexsearchFromSource(source, { localeMap: { // [locale]: Flexsearch options [!code ++:2] jp: { encoder: Charset.CJK }, }, }); ``` ```ts tab="From Search Indexes" import { source } from '@/lib/source'; import { flexsearchI18n } from 'fumadocs-core/search/flexsearch'; import { i18n } from '@/lib/i18n'; import { Charset } from 'flexsearch'; const server = flexsearchI18n({ i18n, // [!code ++] localeMap: { // [locale]: Flexsearch options [!code ++:2] jp: { encoder: Charset.CJK }, }, indexes: source.getPages().map((page) => ({ title: page.data.title!, description: page.data.description, structuredData: page.data.structuredData, id: page.url, url: page.url, locale: page.locale!, })), }); ``` # Fumadocs Core (the core library of Fumadocs): Search URL: /docs/headless/search Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/index.mdx Configure Search in Fumadocs - [Algolia Search](/docs/headless/search/algolia): Integrate Algolia Search with Fumadocs - [FlexSearch](/docs/headless/search/flexsearch): Fast & minimal document search - [Meilisearch](/docs/headless/search/meilisearch): Integrate Meilisearch with Fumadocs - [Mixedbread](/docs/headless/search/mixedbread): Integrate Mixedbread Search with Fumadocs - [Orama Cloud](/docs/headless/search/orama-cloud): Integrate with Orama Cloud - [Built-in Search](/docs/headless/search/orama): Built-in document search of Fumadocs - [Trieve Search](/docs/headless/search/trieve): Integrate Trieve Search with Fumadocs - [Typesense Search](/docs/headless/search/typesense): Integrate Typesense Search with Fumadocs # Fumadocs Core (the core library of Fumadocs): Meilisearch URL: /docs/headless/search/meilisearch Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/meilisearch.mdx Integrate Meilisearch with Fumadocs [Meilisearch](https://www.meilisearch.com) is an open-source search engine with typo tolerance and filtering, you can self-host it or use Meilisearch Cloud. ## Setup [#setup] Install dependencies: ```package-install meilisearch ``` ### API Keys [#api-keys] Start a Meilisearch instance by [self-hosting](https://www.meilisearch.com/docs/learn/self_hosted/getting_started_with_self_hosted_meilisearch) or on [Meilisearch Cloud](https://www.meilisearch.com/cloud), and store its credentials in `.env.local` (`NEXT_PUBLIC_` is `VITE_` on Vite frameworks, `PUBLIC_` on Astro): ```dotenv NEXT_PUBLIC_MEILISEARCH_HOST="URL of your instance" NEXT_PUBLIC_MEILISEARCH_SEARCH_KEY="search API key" MEILISEARCH_ADMIN_KEY="Default Admin API Key" ``` The search key is exposed to the browser, [create one](https://www.meilisearch.com/docs/learn/security/basic_security) that can only search the `docs` index. Keep the admin key private. ### Sync Documents [#sync-documents] Pre-render a `static.json` route to export the search documents on build, and sync them to Meilisearch with a script after each build: ```ts tab="Next.js" title="app/static.json/route.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/meilisearch'; export const revalidate = false; export async function GET() { return Response.json(await toDocuments(source)); } ``` ```ts tab="Next.js" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch'; import { Meilisearch } from 'meilisearch'; // Next.js writes it under `route-cache` when built with an adapter, like on Vercel const [file] = await Array.fromAsync(fs.glob('.next/server/{app,route-cache/*/*/$}/static.json.body')); const records = JSON.parse(await fs.readFile(file, 'utf-8')) as DocumentRecord[]; const client = new Meilisearch({ host: process.env.NEXT_PUBLIC_MEILISEARCH_HOST!, apiKey: process.env.MEILISEARCH_ADMIN_KEY!, }); await sync(client, { indexName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Next.js" title="package.json" { "scripts": { "build": "next build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="React Router" title="app/routes/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/meilisearch'; export async function loader() { return Response.json(await toDocuments(source)); } ``` ```ts tab="React Router" title="app/routes.ts" import { index, route, type RouteConfig } from '@react-router/dev/routes'; export default [ index('routes/home.tsx'), route('static.json', 'routes/static.json.ts'), // [!code ++:1] ] satisfies RouteConfig; ``` ```ts tab="React Router" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch'; import { Meilisearch } from 'meilisearch'; const records = JSON.parse(await fs.readFile('build/client/static.json', 'utf-8')) as DocumentRecord[]; const client = new Meilisearch({ host: process.env.VITE_MEILISEARCH_HOST!, apiKey: process.env.MEILISEARCH_ADMIN_KEY!, }); await sync(client, { indexName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="React Router" title="package.json" { "scripts": { "build": "react-router build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="TanStack Start" title="src/routes/static[.]json.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/meilisearch'; export const Route = createFileRoute('/static.json')({ server: { handlers: { GET: async () => Response.json(await toDocuments(source)), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { nitro } from 'nitro/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, pages: [ // [!code ++:3] { path: '/static.json' } ], }), nitro({ preset: 'vercel', }), ], }); ``` ```ts tab="TanStack Start" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch'; import { Meilisearch } from 'meilisearch'; const records = JSON.parse(await fs.readFile('.vercel/output/static/static.json', 'utf-8')) as DocumentRecord[]; const client = new Meilisearch({ host: process.env.VITE_MEILISEARCH_HOST!, apiKey: process.env.MEILISEARCH_ADMIN_KEY!, }); await sync(client, { indexName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="TanStack Start" title="package.json" { "scripts": { "build": "vite build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Waku" title="src/pages/_api/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/meilisearch'; export async function GET() { return Response.json(await toDocuments(source)); } export async function getConfig() { return { render: 'static' as const, } as const; } ``` ```ts tab="Waku" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch'; import { Meilisearch } from 'meilisearch'; const records = JSON.parse(await fs.readFile('dist/public/static.json', 'utf-8')) as DocumentRecord[]; const client = new Meilisearch({ host: process.env.VITE_MEILISEARCH_HOST!, apiKey: process.env.MEILISEARCH_ADMIN_KEY!, }); await sync(client, { indexName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Waku" title="package.json" { "scripts": { "build": "waku build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Astro" title="src/pages/static.json.ts" import type { APIRoute } from 'astro'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/meilisearch'; export const prerender = true; export const GET: APIRoute = async () => Response.json(await toDocuments(source)); ``` ```ts tab="Astro" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch'; import { Meilisearch } from 'meilisearch'; const records = JSON.parse(await fs.readFile('dist/static.json', 'utf-8')) as DocumentRecord[]; const client = new Meilisearch({ host: process.env.PUBLIC_MEILISEARCH_HOST!, apiKey: process.env.MEILISEARCH_ADMIN_KEY!, }); await sync(client, { indexName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Astro" title="package.json" { "scripts": { "build": "astro build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` `sync()` configures the index and replaces its documents, the old documents stay searchable until the new ones are indexed. The `build` script syncs on every build, set the same variables on your deployment platform. ### Search UI [#search-ui] You can consider different options for implementing the UI: - Using [Fumadocs UI search dialog](/docs/next/search/meilisearch). - Build your own using the built-in search client hook: ```ts twoslash import { Meilisearch } from 'meilisearch'; import { useMeilisearch } from 'fumadocs-core/search/client'; const client = new Meilisearch({ host: 'host url', apiKey: 'search api key', }); const { search, onSearchChange, isLoading, data } = useMeilisearch({ client, indexName: 'docs', }); ``` | Prop | Type | Description | | ----------- | --------------------------------- | ---------------------------------------- | | `client` | `Meilisearch` | Meilisearch client with a search API key | | `indexName` | `string` | | | `tag?` | `string \| string[] \| undefined` | Filter results with specific tag(s). | | `locale?` | `string \| undefined` | Filter results by locale. | - Use their official clients directly. ## Options [#options] ### Tag Filter [#tag-filter] To configure tag filtering, pass a `tag` to `toDocuments()` in the `static.json` route: ```ts toDocuments(source, { tag: (page) => page.slugs[0] }); ``` And update your search client: - **Fumadocs UI**: Enable [Tag Filter](/docs/next/search/meilisearch#tag-filter) on Search UI. - **Search Client**: pass a tag to `useMeilisearch()`. ```ts import { useMeilisearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useMeilisearch({ tag: '', // [!code ++] // ... }); ``` ### Internationalization [#internationalization] Documents include the locale of their pages, pass `locale` to search in a language: ```ts import { useI18n } from 'fumadocs-ui/contexts/i18n'; import { useMeilisearch } from 'fumadocs-core/search/client'; const { locale } = useI18n(); const { search, onSearchChange, isLoading, data } = useMeilisearch({ locale, // [!code ++] // ... }); ``` ### Index Settings [#index-settings] `sync()` only sets `searchableAttributes` and `filterableAttributes`, other settings like synonyms and typo tolerance are kept. You can tune them from the Meilisearch dashboard or the `meilisearch` client. ## Under the Hood [#under-the-hood] Each heading and paragraph is a document, with the page title, URL and breadcrumbs. Only `content` is searchable, the search client groups results by page. | Attribute | Description | | --------- | ------------------------------------------ | | `type` | `page`, `heading` or `text` | | `content` | Page title, heading or paragraph | | `heading` | ID of the heading it belongs to (optional) | | `tag` | Tag(s) to filter results (optional) | | `locale` | Locale of page (optional) | # Fumadocs Core (the core library of Fumadocs): Mixedbread URL: /docs/headless/search/mixedbread Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/mixedbread.mdx Integrate Mixedbread Search with Fumadocs [Mixedbread](https://www.mixedbread.com) provides semantic search, users can search with natural language and find content by meaning rather than keywords. ## Setup [#setup] Install dependencies: ```package-install @mixedbread/sdk ``` ### API Key [#api-key] Sign up at [Mixedbread](https://platform.mixedbread.com), create an [API key](https://platform.mixedbread.com/platform?next=api-keys) and a [store](https://platform.mixedbread.com/platform?next=stores) for your docs, and store them in `.env.local`: ```dotenv MXBAI_API_KEY="your API key" MIXEDBREAD_STORE_ID="your store ID" ``` Searching runs on your server, the API key is never exposed to the browser. ### Sync Documents [#sync-documents] Pre-render a `static.json` route to export the search documents on build, and sync them to your store with a script after each build: ```ts tab="Next.js" title="app/static.json/route.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/mixedbread'; export const revalidate = false; export async function GET() { return Response.json(await toDocuments(source)); } ``` ```ts tab="Next.js" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; // Next.js writes it under `route-cache` when built with an adapter, like on Vercel const [file] = await Array.fromAsync(fs.glob('.next/server/{app,route-cache/*/*/$}/static.json.body')); const records = JSON.parse(await fs.readFile(file, 'utf-8')) as DocumentRecord[]; await sync(new Mixedbread(), { storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Next.js" title="package.json" { "scripts": { "build": "next build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="React Router" title="app/routes/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/mixedbread'; export async function loader() { return Response.json(await toDocuments(source)); } ``` ```ts tab="React Router" title="app/routes.ts" import { index, route, type RouteConfig } from '@react-router/dev/routes'; export default [ index('routes/home.tsx'), route('static.json', 'routes/static.json.ts'), // [!code ++:1] ] satisfies RouteConfig; ``` ```ts tab="React Router" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; const records = JSON.parse(await fs.readFile('build/client/static.json', 'utf-8')) as DocumentRecord[]; await sync(new Mixedbread(), { storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="React Router" title="package.json" { "scripts": { "build": "react-router build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="TanStack Start" title="src/routes/static[.]json.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/mixedbread'; export const Route = createFileRoute('/static.json')({ server: { handlers: { GET: async () => Response.json(await toDocuments(source)), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { nitro } from 'nitro/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, pages: [ // [!code ++:3] { path: '/static.json' } ], }), nitro({ preset: 'vercel', }), ], }); ``` ```ts tab="TanStack Start" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; const records = JSON.parse(await fs.readFile('.vercel/output/static/static.json', 'utf-8')) as DocumentRecord[]; await sync(new Mixedbread(), { storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="TanStack Start" title="package.json" { "scripts": { "build": "vite build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Waku" title="src/pages/_api/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/mixedbread'; export async function GET() { return Response.json(await toDocuments(source)); } export async function getConfig() { return { render: 'static' as const, } as const; } ``` ```ts tab="Waku" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; const records = JSON.parse(await fs.readFile('dist/public/static.json', 'utf-8')) as DocumentRecord[]; await sync(new Mixedbread(), { storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Waku" title="package.json" { "scripts": { "build": "waku build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Astro" title="src/pages/static.json.ts" import type { APIRoute } from 'astro'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/mixedbread'; export const prerender = true; export const GET: APIRoute = async () => Response.json(await toDocuments(source)); ``` ```ts tab="Astro" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; const records = JSON.parse(await fs.readFile('dist/static.json', 'utf-8')) as DocumentRecord[]; await sync(new Mixedbread(), { storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Astro" title="package.json" { "scripts": { "build": "astro build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` `sync()` uploads a file for each page, and skips the pages unchanged since the last sync. Files of removed pages are deleted, use a store dedicated to your docs. The `build` script syncs on every build, set the same variables on your deployment platform. ### Search API [#search-api] Create a route to search your store: ```ts tab="Next.js" title="app/api/search/route.ts" import { createMixedbreadSearchAPI } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; export const { GET } = createMixedbreadSearchAPI({ client: new Mixedbread(), // reads `MXBAI_API_KEY` storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, }); ``` ```ts tab="React Router" title="app/routes/search.ts" import type { Route } from './+types/search'; import { createMixedbreadSearchAPI } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; const server = createMixedbreadSearchAPI({ client: new Mixedbread(), // reads `MXBAI_API_KEY` storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, }); export async function loader({ request }: Route.LoaderArgs) { return server.GET(request); } ``` ```ts tab="TanStack Start" title="src/routes/api/search.ts" import { createFileRoute } from '@tanstack/react-router'; import { createMixedbreadSearchAPI } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; const server = createMixedbreadSearchAPI({ client: new Mixedbread(), // reads `MXBAI_API_KEY` storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, }); export const Route = createFileRoute('/api/search')({ server: { handlers: { GET: async ({ request }) => server.GET(request), }, }, }); ``` ```ts tab="Waku" title="src/pages/_api/api/search.ts" import { createMixedbreadSearchAPI } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; export const { GET } = createMixedbreadSearchAPI({ client: new Mixedbread(), // reads `MXBAI_API_KEY` storeIdentifier: process.env.MIXEDBREAD_STORE_ID!, }); ``` ```ts tab="Astro" title="src/pages/api/search.ts" import type { APIRoute } from 'astro'; import { createMixedbreadSearchAPI } from 'fumadocs-core/search/mixedbread'; import Mixedbread from '@mixedbread/sdk'; import { getSecret } from 'astro:env/server'; // render per request, needs an adapter export const prerender = false; const server = createMixedbreadSearchAPI({ client: new Mixedbread({ apiKey: getSecret('MXBAI_API_KEY') }), storeIdentifier: getSecret('MIXEDBREAD_STORE_ID')!, }); export const GET: APIRoute = ({ request }) => server.GET(request); ``` ### Search UI [#search-ui] You can consider different options for implementing the UI: - Using [Fumadocs UI search dialog](/docs/next/search/mixedbread). - Build your own using the built-in search client hook: ```ts twoslash import { useFetchSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useFetchSearch({ api: '/api/search', // every search is a request to Mixedbread delayMs: 300, }); ``` ## Options [#options] ### Tag Filter [#tag-filter] To configure tag filtering, pass a `tag` to `toDocuments()` in the `static.json` route: ```ts toDocuments(source, { tag: (page) => page.slugs[0] }); ``` And update your search client: - **Fumadocs UI**: Enable [Tag Filter](/docs/next/search/mixedbread#tag-filter) on Search UI. - **Search Client**: pass a tag to `useFetchSearch()`. ```ts import { useFetchSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useFetchSearch({ tag: '', // [!code ++] // ... }); ``` ### Internationalization [#internationalization] Documents include the locale of their pages, pass `locale` to search in a language: ```ts import { useI18n } from 'fumadocs-ui/contexts/i18n'; import { useFetchSearch } from 'fumadocs-core/search/client'; const { locale } = useI18n(); const { search, onSearchChange, isLoading, data } = useFetchSearch({ locale, // [!code ++] // ... }); ``` ## Under the Hood [#under-the-hood] Each page is a file keyed by its URL, with the page title, URL, breadcrumbs, tags and locale as metadata. Its chunks are the title, headings and paragraphs of the page, every result is a chunk: | Chunk Metadata | Description | | -------------- | ------------------------------------------ | | `kind` | `page`, `heading` or `text` | | `heading` | ID of the heading it belongs to (optional) | | `table` | Table of a table row (optional) | # Fumadocs Core (the core library of Fumadocs): Orama Cloud URL: /docs/headless/search/orama-cloud Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/orama-cloud.mdx Integrate with Orama Cloud To begin, create an account on Orama Cloud. ## REST API [#rest-api] REST API integration requires your docs to upload the indexes. 1. Create a new project with **REST API** data source on Orama Cloud dashboard. Store your credentials in `.env.local`, for example (`NEXT_PUBLIC_` is `VITE_` on Vite frameworks, `PUBLIC_` on Astro): ```dotenv NEXT_PUBLIC_ORAMA_DATASOURCE_ID="Rest API data source ID" NEXT_PUBLIC_ORAMA_PROJECT_ID="project ID" NEXT_PUBLIC_ORAMA_API_KEY="public API key" ORAMA_PRIVATE_API_KEY="private API key" ``` 2. Pre-render a `static.json` route to export the search indexes on build, and sync them to Orama Cloud with a script after each build: ```ts tab="Next.js" title="app/static.json/route.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/orama-cloud'; export const revalidate = false; export async function GET() { return Response.json(await toDocuments(source)); } ``` ```ts tab="Next.js" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type OramaDocument as DocumentRecord, sync } from 'fumadocs-core/search/orama-cloud'; import { OramaCloud } from '@orama/core'; // Next.js writes it under `route-cache` when built with an adapter, like on Vercel const [file] = await Array.fromAsync(fs.glob('.next/server/{app,route-cache/*/*/$}/static.json.body')); const records = JSON.parse(await fs.readFile(file, 'utf-8')) as DocumentRecord[]; const orama = new OramaCloud({ projectId: process.env.NEXT_PUBLIC_ORAMA_PROJECT_ID!, apiKey: process.env.ORAMA_PRIVATE_API_KEY!, }); await sync(orama, { index: process.env.NEXT_PUBLIC_ORAMA_DATASOURCE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Next.js" title="package.json" { "scripts": { "build": "next build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="React Router" title="app/routes/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/orama-cloud'; export async function loader() { return Response.json(await toDocuments(source)); } ``` ```ts tab="React Router" title="app/routes.ts" import { index, route, type RouteConfig } from '@react-router/dev/routes'; export default [ index('routes/home.tsx'), route('static.json', 'routes/static.json.ts'), // [!code ++:1] ] satisfies RouteConfig; ``` ```ts tab="React Router" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type OramaDocument as DocumentRecord, sync } from 'fumadocs-core/search/orama-cloud'; import { OramaCloud } from '@orama/core'; const records = JSON.parse(await fs.readFile('build/client/static.json', 'utf-8')) as DocumentRecord[]; const orama = new OramaCloud({ projectId: process.env.VITE_ORAMA_PROJECT_ID!, apiKey: process.env.ORAMA_PRIVATE_API_KEY!, }); await sync(orama, { index: process.env.VITE_ORAMA_DATASOURCE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="React Router" title="package.json" { "scripts": { "build": "react-router build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="TanStack Start" title="src/routes/static[.]json.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/orama-cloud'; export const Route = createFileRoute('/static.json')({ server: { handlers: { GET: async () => Response.json(await toDocuments(source)), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { nitro } from 'nitro/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, pages: [ // [!code ++:3] { path: '/static.json' } ], }), nitro({ preset: 'vercel', }), ], }); ``` ```ts tab="TanStack Start" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type OramaDocument as DocumentRecord, sync } from 'fumadocs-core/search/orama-cloud'; import { OramaCloud } from '@orama/core'; const records = JSON.parse(await fs.readFile('.vercel/output/static/static.json', 'utf-8')) as DocumentRecord[]; const orama = new OramaCloud({ projectId: process.env.VITE_ORAMA_PROJECT_ID!, apiKey: process.env.ORAMA_PRIVATE_API_KEY!, }); await sync(orama, { index: process.env.VITE_ORAMA_DATASOURCE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="TanStack Start" title="package.json" { "scripts": { "build": "vite build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Waku" title="src/pages/_api/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/orama-cloud'; export async function GET() { return Response.json(await toDocuments(source)); } export async function getConfig() { return { render: 'static' as const, } as const; } ``` ```ts tab="Waku" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type OramaDocument as DocumentRecord, sync } from 'fumadocs-core/search/orama-cloud'; import { OramaCloud } from '@orama/core'; const records = JSON.parse(await fs.readFile('dist/public/static.json', 'utf-8')) as DocumentRecord[]; const orama = new OramaCloud({ projectId: process.env.VITE_ORAMA_PROJECT_ID!, apiKey: process.env.ORAMA_PRIVATE_API_KEY!, }); await sync(orama, { index: process.env.VITE_ORAMA_DATASOURCE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Waku" title="package.json" { "scripts": { "build": "waku build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Astro" title="src/pages/static.json.ts" import type { APIRoute } from 'astro'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/orama-cloud'; export const prerender = true; export const GET: APIRoute = async () => Response.json(await toDocuments(source)); ``` ```ts tab="Astro" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type OramaDocument as DocumentRecord, sync } from 'fumadocs-core/search/orama-cloud'; import { OramaCloud } from '@orama/core'; const records = JSON.parse(await fs.readFile('dist/static.json', 'utf-8')) as DocumentRecord[]; const orama = new OramaCloud({ projectId: process.env.PUBLIC_ORAMA_PROJECT_ID!, apiKey: process.env.ORAMA_PRIVATE_API_KEY!, }); await sync(orama, { index: process.env.PUBLIC_ORAMA_DATASOURCE_ID!, documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Astro" title="package.json" { "scripts": { "build": "astro build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` The `build` script syncs on every build, set the same variables on your deployment platform. ### Search Client [#search-client] To search documents on the client side, consider: - Using [Fumadocs UI search dialog](/docs/next/search/orama-cloud). - Custom search UI using the built-in hook of Fumadocs: ```ts import { useOramaCloudSearch } from 'fumadocs-core/search/client'; import { OramaCloud } from '@orama/core'; const orama = new OramaCloud({ projectId: process.env.NEXT_PUBLIC_ORAMA_PROJECT_ID, apiKey: process.env.NEXT_PUBLIC_ORAMA_API_KEY, }); const params = { // optional search params }; const { search, onSearchChange, isLoading, data } = useOramaCloudSearch({ client: orama, params, }); ``` - Use their search client directly. ## Web Crawler [#web-crawler] 1. Create a Crawler data source from dashboard, and configure it correctly with the "Documentation" preset. 2. Copy the credentials from dashboard. ### Search Client [#search-client-1] Same as REST API integration, but make sure to set `index` to `crawler`. ```ts import { useOramaCloudSearch } from 'fumadocs-core/search/client'; import { OramaCloud } from '@orama/core'; const orama = new OramaCloud({ projectId: '', apiKey: '', }); const params = { // optional search params }; const { search, onSearchChange, isLoading, data } = useOramaCloudSearch({ index: 'crawler', client: orama, params, }); ``` It's same for Fumadocs UI. # Fumadocs Core (the core library of Fumadocs): Built-in Search URL: /docs/headless/search/orama Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/orama.mdx Built-in document search of Fumadocs Fumadocs supports document search with [ZBSearch](https://www.zbsearch.dev), It is the default but also the recommended option since it can be self-hosted and totally free. ## Setup [#setup] Host the server for handling search requests. ### From Source [#from-source] Create the server from source object. ```ts tab="Next.js" title="app/api/search/route.ts" import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; export const { GET } = createFromSource(source); ``` ```ts tab="React Router" title="app/routes/search.ts" import type { Route } from './+types/search'; import { createFromSource } from 'fumadocs-core/search/server'; import { source } from '@/lib/source'; const server = createFromSource(source); export async function loader({ request }: Route.LoaderArgs) { return server.GET(request); } ``` ```ts tab="TanStack Start" title="src/routes/api/search.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; const server = createFromSource(source); export const Route = createFileRoute('/api/search')({ server: { handlers: { GET: async ({ request }) => server.GET(request), }, }, }); ``` ```ts tab="Waku" title="src/pages/_api/api/search.ts" import { createFromSource } from 'fumadocs-core/search/server'; import { source } from '@/lib/source'; export const { GET } = createFromSource(source); ``` ```ts tab="Astro" title="src/pages/api/search.ts" import type { APIRoute } from 'astro'; import { createFromSource } from 'fumadocs-core/search/server'; import { source } from '@/lib/source'; // render per request, needs an adapter export const prerender = false; const server = createFromSource(source); export const GET: APIRoute = ({ request }) => server.GET(request); ``` ### From Search Indexes [#from-search-indexes] Create the server from search indexes, each index needs a `structuredData` field. Usually, it is provided by your content source (e.g. Fumadocs MDX). You can also extract it from Markdown/MDX document using the [Remark Structure](/docs/headless/mdx/structure) plugin. ```ts tab="Next.js" title="app/api/search/route.ts" import { source } from '@/lib/source'; import { createSearchAPI } from 'fumadocs-core/search/server'; export const { GET } = createSearchAPI('advanced', { indexes: source.getPages().map((page) => ({ title: page.data.title, description: page.data.description, url: page.url, id: page.url, structuredData: page.data.structuredData, })), }); ``` ```ts tab="React Router" title="app/routes/search.ts" import type { Route } from './+types/search'; import { createSearchAPI } from 'fumadocs-core/search/server'; import { source } from '@/lib/source'; const server = createSearchAPI('advanced', { indexes: source.getPages().map((page) => ({ title: page.data.title, description: page.data.description, url: page.url, id: page.url, structuredData: page.data.structuredData, })), }); export async function loader({ request }: Route.LoaderArgs) { return server.GET(request); } ``` ```ts tab="TanStack Start" title="src/routes/api/search.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import { createSearchAPI } from 'fumadocs-core/search/server'; const server = createSearchAPI('advanced', { indexes: source.getPages().map((page) => ({ title: page.data.title, description: page.data.description, url: page.url, id: page.url, structuredData: page.data.structuredData, })), }); export const Route = createFileRoute('/api/search')({ server: { handlers: { GET: async ({ request }) => server.GET(request), }, }, }); ``` ```ts tab="Waku" title="src/pages/_api/api/search.ts" import { source } from '@/lib/source'; import { createSearchAPI } from 'fumadocs-core/search/server'; export const { GET } = createSearchAPI('advanced', { indexes: source.getPages().map((page) => ({ title: page.data.title, description: page.data.description, url: page.url, id: page.url, structuredData: page.data.structuredData, })), }); ``` ```ts tab="Astro" title="src/pages/api/search.ts" import type { APIRoute } from 'astro'; import { createSearchAPI } from 'fumadocs-core/search/server'; import { source } from '@/lib/source'; const server = createSearchAPI('advanced', { // `structuredData` is loaded on demand indexes: () => Promise.all( source.getPages().map(async (page) => ({ title: page.data.title, description: page.data.description, url: page.url, id: page.url, structuredData: await page.data.structuredData(), })), ), }); // render per request, needs an adapter export const prerender = false; export const GET: APIRoute = ({ request }) => server.GET(request); ``` ### Searching Documents [#searching-documents] You can search documents using: - **Fumadocs UI**: Supported out-of-the-box, see [Search UI](/docs/next/search/orama) for details. - **Search Client**: ```ts twoslash import { useFetchSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useFetchSearch(); ``` | Prop | Type | Description | | --------- | -------------------------------------------------- | ------------------------------------------------------------------------------ | | `api?` | `string \| undefined` | API route for search endpoint, support absolute URLs. Default: `'/api/search'` | | `tag?` | `string \| string[] \| undefined` | Filter results with specific tag(s). | | `locale?` | `string \| undefined` | Filter by locale | | `cache?` | `Map[]> \| undefined` | | ## Configurations [#configurations] ### Tag Filter [#tag-filter] Support filtering results by tag, it's useful for implementing multi-docs similar to this documentation. ```ts import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; const server = createFromSource(source, { buildIndex(page) { return { title: page.data.title, description: page.data.description, url: page.url, id: page.url, structuredData: page.data.structuredData, // use your desired value, like page.slugs[0] [!code ++:2] tag: '', }; }, }); ``` and update your search client: - **Fumadocs UI**: Configure [Tag Filter](/docs/next/search/orama#tag-filter) on Search UI. - **Search Client**: pass a tag to `useFetchSearch()`. ```ts import { useFetchSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useFetchSearch({ tag: '', // [!code ++] }); ``` ### Static Mode [#static-export] To support usage with static site, use `staticGET` from search server and make the route static or pre-rendered. ```ts tab="Next.js" title="app/api/search/route.ts" import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; // statically cached [!code highlight:3] export const revalidate = false; export const { staticGET: GET } = createFromSource(source); ``` ```ts tab="React Router" title="app/routes/search.ts" // make sure this route is pre-rendered in `react-router.config.ts`. export async function loader() { // [!code highlight] return server.staticGET(); } ``` ```ts tab="TanStack Start" title="src/routes/api/search.ts" import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/api/search')({ server: { handlers: { // [!code highlight] GET: async () => server.staticGET(), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, // [!code ++:2] pre-render the index file pages: [{ path: '/api/search' }], }), ], }); ``` ```ts tab="Waku" title="src/pages/_api/api/search.ts" import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; // [!code highlight] export const { staticGET: GET } = createFromSource(source); // statically cached [!code highlight:4] export const getConfig = async () => ({ render: 'static', }); ``` ```ts tab="Astro" title="src/pages/api/search.ts" import type { APIRoute } from 'astro'; import { createFromSource } from 'fumadocs-core/search/server'; import { source } from '@/lib/source'; const server = createFromSource(source); // prerendered by default [!code highlight] export const GET: APIRoute = () => server.staticGET(); ``` > `staticGET` is also available on `createSearchAPI`. and update your search clients: - **Fumadocs UI**: use [static client](/docs/next/search/orama#static) on Search UI. - **Search Client**: use `useStaticSearch()` instead of `useFetchSearch()`. ```ts import { useStaticSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useStaticSearch(); ``` | Prop | Type | Description | | ------------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `from?` | `string \| undefined` | Where to download exported search indexes (URL) Default: `'/api/search'` | | `initDB?` | `((locale?: string) => AnyZBSearch \| Promise) \| undefined` | Customize how the search database is initialized (advanced). For legacy per-locale exports, it is called once per locale. | | `initOrama?` | `((locale?: string) => AnyZBSearch \| Promise) \| undefined` | **Deprecated.** | | `tag?` | `string \| string[] \| undefined` | Filter results with specific tag(s). | | `locale?` | `string \| undefined` | Filter by locale (for i18n) | | `search?` | `Partial> \| undefined` | extra options for search | Static Search requires clients to download the exported search indexes. For large docs sites, it can be expensive. You should use cloud solutions like Orama Cloud or Algolia for these cases. ## Internationalization [#internationalization] Search works with every language out of the box - the default `multilingual` mode uses Unicode word segmentation, so all locales (including Chinese and Japanese) share a single search database with zero config. ```ts title="app/api/search/route.ts" tab="From Source" import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; // no extra configuration needed for i18n const server = createFromSource(source); ``` ```ts tab="From Search Indexes" import { source } from '@/lib/source'; import { createI18nSearchAPI } from 'fumadocs-core/search/server'; import { i18n } from '@/lib/i18n'; const server = createI18nSearchAPI('advanced', { i18n, // [!code ++] indexes: source.getLanguages().flatMap(({ language, pages }) => pages.map((page) => ({ title: page.data.title, description: page.data.description, structuredData: page.data.structuredData, id: `${language}:${page.url}`, // [!code ++] url: page.url, locale: language, // [!code ++] })), ), }); ``` and update your search clients: - **Fumadocs UI**: No changes needed, Fumadocs UI handles this when you have i18n configured correctly. - **Search Client**: Add `locale` to the search client, this will only allow pages with specified locale to be searchable by the user. ```ts import { useFetchSearch } from 'fumadocs-core/search/client'; const { search, onSearchChange, isLoading, data } = useFetchSearch({ locale: 'cn', }); ``` This also applies to **Static Mode**, pass `locale` to `useStaticSearch()` instead. The `multilingual` mode doesn't apply language-specific stemming or stop-words. Without stemming, a plural query like `recordings` won't match a page containing `recording`. To attach a stemmer while keeping multilingual segmentation and a single database, pass a `tokenizer`: ```ts import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; import { stemmer } from '@zbsearch/stemmers/english'; const server = createFromSource(source, { tokenizer: { language: 'multilingual', stemming: true, stemmer }, // [!code ++] }); ``` Alternatively, use a language on the [supported languages](https://www.zbsearch.dev/docs/zbsearch/supported-languages) list per locale with `localeMap`: ```ts import { source } from '@/lib/source'; import { createFromSource } from 'fumadocs-core/search/server'; const server = createFromSource(source, { localeMap: { // [locale]: search options [!code ++:3] ru: { language: 'russian' }, en: { language: 'english' }, }, }); ``` Note that a separate search database is created for each locale when `localeMap` is enabled. A custom `tokenizer` must also be given to the client, since it needs to tokenize the query the same way. Pass it via `initDB` on `useStaticSearch()`. ## Headless [#headless] You can host the search server on other backend such as Express and Elysia. ```ts import { initAdvancedSearch } from 'fumadocs-core/search/server'; const server = initAdvancedSearch({ // you still have to pass indexes }); server.search('query', { // you can specify `locale` and `tag` here }); ``` # Fumadocs Core (the core library of Fumadocs): Trieve Search URL: /docs/headless/search/trieve Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/trieve.mdx Integrate Trieve Search with Fumadocs > This is a community maintained integration. ## Introduction [#introduction] The Trieve Integration automatically configures Trieve Search for site search. By default, it creates a chunk for **each paragraph** in your document, it is officially recommended by Trieve. ## Setup [#setup] ### Install Dependencies [#install-dependencies] ```package-install trieve-ts-sdk trieve-fumadocs-adapter ``` ### Sign up on Trieve [#sign-up-on-trieve] Sign up and create a dataset. Then obtain 2 API keys where one has only read access and the other has admin access to create and delete chunks. Store the dataset ID and admin key in `.env.local` for syncing: ```dotenv TRIEVE_DATASET_ID="dataset ID" TRIEVE_ADMIN_API_KEY="admin API key" ``` One API Key should have only read access for the public facing search and the other should have admin access to create and delete chunks. ### Sync Dataset [#sync-dataset] Trieve takes the records of the [Algolia integration](/docs/headless/search/algolia). Export them with a pre-rendered `static.json` route, and sync them to Trieve with a script after each build: ```ts tab="Next.js" title="app/static.json/route.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export const revalidate = false; export async function GET() { return Response.json(await toDocuments(source)); } ``` ```ts tab="Next.js" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { sync, type TrieveDocument as DocumentRecord } from 'trieve-fumadocs-adapter/search/sync'; import { TrieveSDK } from 'trieve-ts-sdk'; // Next.js writes it under `route-cache` when built with an adapter, like on Vercel const [file] = await Array.fromAsync(fs.glob('.next/server/{app,route-cache/*/*/$}/static.json.body')); const records = JSON.parse(await fs.readFile(file, 'utf-8')) as DocumentRecord[]; const client = new TrieveSDK({ apiKey: process.env.TRIEVE_ADMIN_API_KEY!, datasetId: process.env.TRIEVE_DATASET_ID!, }); await sync(client, records); console.log(`search updated: ${records.length} records`); ``` ```json tab="Next.js" title="package.json" { "scripts": { "build": "next build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="React Router" title="app/routes/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export async function loader() { return Response.json(await toDocuments(source)); } ``` ```ts tab="React Router" title="app/routes.ts" import { index, route, type RouteConfig } from '@react-router/dev/routes'; export default [ index('routes/home.tsx'), route('static.json', 'routes/static.json.ts'), // [!code ++:1] ] satisfies RouteConfig; ``` ```ts tab="React Router" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { sync, type TrieveDocument as DocumentRecord } from 'trieve-fumadocs-adapter/search/sync'; import { TrieveSDK } from 'trieve-ts-sdk'; const records = JSON.parse(await fs.readFile('build/client/static.json', 'utf-8')) as DocumentRecord[]; const client = new TrieveSDK({ apiKey: process.env.TRIEVE_ADMIN_API_KEY!, datasetId: process.env.TRIEVE_DATASET_ID!, }); await sync(client, records); console.log(`search updated: ${records.length} records`); ``` ```json tab="React Router" title="package.json" { "scripts": { "build": "react-router build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="TanStack Start" title="src/routes/static[.]json.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export const Route = createFileRoute('/static.json')({ server: { handlers: { GET: async () => Response.json(await toDocuments(source)), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { nitro } from 'nitro/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, pages: [ // [!code ++:3] { path: '/static.json' } ], }), nitro({ preset: 'vercel', }), ], }); ``` ```ts tab="TanStack Start" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { sync, type TrieveDocument as DocumentRecord } from 'trieve-fumadocs-adapter/search/sync'; import { TrieveSDK } from 'trieve-ts-sdk'; const records = JSON.parse(await fs.readFile('.vercel/output/static/static.json', 'utf-8')) as DocumentRecord[]; const client = new TrieveSDK({ apiKey: process.env.TRIEVE_ADMIN_API_KEY!, datasetId: process.env.TRIEVE_DATASET_ID!, }); await sync(client, records); console.log(`search updated: ${records.length} records`); ``` ```json tab="TanStack Start" title="package.json" { "scripts": { "build": "vite build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Waku" title="src/pages/_api/static.json.ts" import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export async function GET() { return Response.json(await toDocuments(source)); } export async function getConfig() { return { render: 'static' as const, } as const; } ``` ```ts tab="Waku" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { sync, type TrieveDocument as DocumentRecord } from 'trieve-fumadocs-adapter/search/sync'; import { TrieveSDK } from 'trieve-ts-sdk'; const records = JSON.parse(await fs.readFile('dist/public/static.json', 'utf-8')) as DocumentRecord[]; const client = new TrieveSDK({ apiKey: process.env.TRIEVE_ADMIN_API_KEY!, datasetId: process.env.TRIEVE_DATASET_ID!, }); await sync(client, records); console.log(`search updated: ${records.length} records`); ``` ```json tab="Waku" title="package.json" { "scripts": { "build": "waku build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Astro" title="src/pages/static.json.ts" import type { APIRoute } from 'astro'; import { source } from '@/lib/source'; import { toDocuments } from 'fumadocs-core/search/algolia'; export const prerender = true; export const GET: APIRoute = async () => Response.json(await toDocuments(source)); ``` ```ts tab="Astro" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { sync, type TrieveDocument as DocumentRecord } from 'trieve-fumadocs-adapter/search/sync'; import { TrieveSDK } from 'trieve-ts-sdk'; const records = JSON.parse(await fs.readFile('dist/static.json', 'utf-8')) as DocumentRecord[]; const client = new TrieveSDK({ apiKey: process.env.TRIEVE_ADMIN_API_KEY!, datasetId: process.env.TRIEVE_DATASET_ID!, }); await sync(client, records); console.log(`search updated: ${records.length} records`); ``` ```json tab="Astro" title="package.json" { "scripts": { "build": "astro build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` The `build` script syncs on every build, set the same variables on your deployment platform. ### Search UI [#search-ui] You can use their `SearchDialog` component: ```tsx title="components/search.tsx" 'use client'; import type { SharedProps } from 'fumadocs-ui/components/dialog/search'; import SearchDialog from 'trieve-fumadocs-adapter/components/dialog/search'; import { TrieveSDK } from 'trieve-ts-sdk'; const trieveClient = new TrieveSDK({ apiKey: 'readOnlyApiKey', datasetId: 'datasetId', }); export default function CustomSearchDialog(props: SharedProps) { return ; } ``` 1. Replace `apiKey` and `datasetId` with your desired values. 2. Replace the default search dialog with your new one. ### Search Client [#search-client] Add the `useTrieveSearch` hook: ```ts import { TrieveSDK } from 'trieve-ts-sdk'; import { useTrieveSearch } from 'trieve-fumadocs-adapter/search/trieve'; const client = new TrieveSDK({ apiKey: 'readOnlyApiKey', datasetId: 'datasetId', }); const { search, setSearch, query } = useTrieveSearch(client); ``` ## Options [#options] ### Tag Filter [#tag-filter] To configure tag filtering, add a `tag` value to indexes. ```js import { sync } from 'trieve-fumadocs-adapter/search/sync'; import { TrieveSDK } from 'trieve-ts-sdk'; const client = new TrieveSDK({ apiKey: 'adminApiKey', datasetId: 'datasetId', }); const documents = records.map((index) => ({ ...index, tag: 'value', // [!code highlight] })); sync(client, documents); ``` #### Search UI [#search-ui-1] Enable Tag Filter. ```tsx title="components/search.tsx" import SearchDialog from 'trieve-fumadocs-adapter/components/dialog/search'; ; ``` #### Search Client [#search-client-1] The `tag_set` field is an attribute for filtering. To filter indexes by tag, use the filter on Trieve search clients. ```json { "must": [ { "field": "tag_set", "match": ["value"] } ] } ``` Or with `useTrieveSearch` hook: ```ts import { TrieveSDK } from 'trieve-ts-sdk'; import { useTrieveSearch } from 'trieve-fumadocs-adapter/search/trieve'; const client = new TrieveSDK({ apiKey: 'readOnlyApiKey', datasetId: 'datasetId', }); const { search, setSearch, query } = useTrieveSearch(client, undefined, ''); ``` # Fumadocs Core (the core library of Fumadocs): Typesense Search URL: /docs/headless/search/typesense Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/typesense.mdx Integrate Typesense Search with Fumadocs > This is a community-maintained integration. ## Setup [#setup] ### Install Dependencies [#install-dependencies] ```package-install typesense typesense-fumadocs-adapter ``` ### Start Typesense Server [#start-typesense-server] You can either self-host the Typesense server or use their cloud service. Follow their [getting started guide](https://typesense.org/docs/guide/install-typesense.html) to set up your server, and store its credentials in `.env.local` (`NEXT_PUBLIC_` is `VITE_` on Vite frameworks, `PUBLIC_` on Astro): ```dotenv NEXT_PUBLIC_TYPESENSE_URL="server URL" NEXT_PUBLIC_TYPESENSE_SEARCH_KEY="search-only API key" TYPESENSE_API_KEY="API key with write access" ``` ### Sync Dataset [#sync-dataset] Export the search indexes with a pre-rendered `static.json` route, and sync them to Typesense with a script after each build: ```ts tab="Next.js" title="app/static.json/route.ts" import { source } from '@/lib/source'; import type { DocumentRecord } from 'typesense-fumadocs-adapter'; async function getDocuments() { const documents: DocumentRecord[] = []; for (const page of source.getPages()) { documents.push({ _id: page.url, structured: page.data.structuredData, url: page.url, title: page.data.title, description: page.data.description, locale: page.locale, }); } return documents; } export const revalidate = false; export async function GET() { return Response.json(await getDocuments()); } ``` ```ts tab="Next.js" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'typesense-fumadocs-adapter'; import { Client } from 'typesense'; // Next.js writes it under `route-cache` when built with an adapter, like on Vercel const [file] = await Array.fromAsync(fs.glob('.next/server/{app,route-cache/*/*/$}/static.json.body')); const records = JSON.parse(await fs.readFile(file, 'utf-8')) as DocumentRecord[]; const client = new Client({ nodes: [{ url: process.env.NEXT_PUBLIC_TYPESENSE_URL! }], apiKey: process.env.TYPESENSE_API_KEY!, connectionTimeoutSeconds: 60 * 15, }); await sync(client, { typesenseCollectionName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Next.js" title="package.json" { "scripts": { "build": "next build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="React Router" title="app/routes/static.json.ts" import { source } from '@/lib/source'; import type { DocumentRecord } from 'typesense-fumadocs-adapter'; async function getDocuments() { const documents: DocumentRecord[] = []; for (const page of source.getPages()) { documents.push({ _id: page.url, structured: await page.data.structuredData(), url: page.url, title: page.data.title, description: page.data.description, locale: page.locale, }); } return documents; } export async function loader() { return Response.json(await getDocuments()); } ``` ```ts tab="React Router" title="app/routes.ts" import { index, route, type RouteConfig } from '@react-router/dev/routes'; export default [ index('routes/home.tsx'), route('static.json', 'routes/static.json.ts'), // [!code ++:1] ] satisfies RouteConfig; ``` ```ts tab="React Router" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'typesense-fumadocs-adapter'; import { Client } from 'typesense'; const records = JSON.parse(await fs.readFile('build/client/static.json', 'utf-8')) as DocumentRecord[]; const client = new Client({ nodes: [{ url: process.env.VITE_TYPESENSE_URL! }], apiKey: process.env.TYPESENSE_API_KEY!, connectionTimeoutSeconds: 60 * 15, }); await sync(client, { typesenseCollectionName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="React Router" title="package.json" { "scripts": { "build": "react-router build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="TanStack Start" title="src/routes/static[.]json.ts" import { createFileRoute } from '@tanstack/react-router'; import { source } from '@/lib/source'; import type { DocumentRecord } from 'typesense-fumadocs-adapter'; async function getDocuments() { const documents: DocumentRecord[] = []; for (const page of source.getPages()) { documents.push({ _id: page.url, structured: await page.data.structuredData(), url: page.url, title: page.data.title, description: page.data.description, locale: page.locale, }); } return documents; } export const Route = createFileRoute('/static.json')({ server: { handlers: { GET: async () => Response.json(await getDocuments()), }, }, }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { nitro } from 'nitro/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tanstackStart({ prerender: { enabled: true, }, pages: [ // [!code ++:3] { path: '/static.json' } ], }), nitro({ preset: 'vercel', }), ], }); ``` ```ts tab="TanStack Start" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'typesense-fumadocs-adapter'; import { Client } from 'typesense'; const records = JSON.parse(await fs.readFile('.vercel/output/static/static.json', 'utf-8')) as DocumentRecord[]; const client = new Client({ nodes: [{ url: process.env.VITE_TYPESENSE_URL! }], apiKey: process.env.TYPESENSE_API_KEY!, connectionTimeoutSeconds: 60 * 15, }); await sync(client, { typesenseCollectionName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="TanStack Start" title="package.json" { "scripts": { "build": "vite build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Waku" title="src/pages/_api/static.json.ts" import { source } from '@/lib/source'; import type { DocumentRecord } from 'typesense-fumadocs-adapter'; async function getDocuments() { const documents: DocumentRecord[] = []; for (const page of source.getPages()) { documents.push({ _id: page.url, structured: page.data.structuredData, url: page.url, title: page.data.title, description: page.data.description, locale: page.locale, }); } return documents; } export async function GET() { return Response.json(await getDocuments()); } export async function getConfig() { return { render: 'static' as const, } as const; } ``` ```ts tab="Waku" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'typesense-fumadocs-adapter'; import { Client } from 'typesense'; const records = JSON.parse(await fs.readFile('dist/public/static.json', 'utf-8')) as DocumentRecord[]; const client = new Client({ nodes: [{ url: process.env.VITE_TYPESENSE_URL! }], apiKey: process.env.TYPESENSE_API_KEY!, connectionTimeoutSeconds: 60 * 15, }); await sync(client, { typesenseCollectionName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Waku" title="package.json" { "scripts": { "build": "waku build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` ```ts tab="Astro" title="src/pages/static.json.ts" import type { APIRoute } from 'astro'; import { source } from '@/lib/source'; import type { DocumentRecord } from 'typesense-fumadocs-adapter'; async function getDocuments() { const documents: DocumentRecord[] = []; for (const page of source.getPages()) { documents.push({ _id: page.url, structured: await page.data.structuredData(), url: page.url, title: page.data.title, description: page.data.description, locale: page.locale, }); } return documents; } export const prerender = true; export const GET: APIRoute = async () => Response.json(await getDocuments()); ``` ```ts tab="Astro" title="scripts/sync-content.ts" import * as fs from 'node:fs/promises'; import { type DocumentRecord, sync } from 'typesense-fumadocs-adapter'; import { Client } from 'typesense'; const records = JSON.parse(await fs.readFile('dist/static.json', 'utf-8')) as DocumentRecord[]; const client = new Client({ nodes: [{ url: process.env.PUBLIC_TYPESENSE_URL! }], apiKey: process.env.TYPESENSE_API_KEY!, connectionTimeoutSeconds: 60 * 15, }); await sync(client, { typesenseCollectionName: 'docs', documents: records, }); console.log(`search updated: ${records.length} records`); ``` ```json tab="Astro" title="package.json" { "scripts": { "build": "astro build && node --env-file-if-exists=.env.local scripts/sync-content.ts" } } ``` The `build` script syncs on every build, set the same variables on your deployment platform. ### Search UI [#search-ui] To implement the search UI, you can either: - Use [Fumadocs UI search dialog](/docs/next/search/typesense). - Build your own search UI with the Typesense search client hook. ```ts import { Client } from 'typesense'; import { useTypesenseSearch } from 'typesense-fumadocs-adapter/client'; const client = new Client({ nodes: [{ url: 'YOUR_TYPESENSE_SERVER_URL' }], apiKey: 'YOUR_TYPESENSE_SEARCH_ONLY_API_KEY', }); const { search, setSearch, query } = useTypesenseSearch({ typesenseCollectionName: 'docs', client, }); ``` ## Options [#options] ### Tag Filter [#tag-filter] To configure tag filtering, add a `tag` value to the documents in the `static.json` route: ```ts documents.push({ // other fields... // [!code ++] tag: '', }); ``` And update your search client: - **Fumadocs UI**: Enable [Tag Filter](/docs/next/search/typesense#tag-filter) on Search UI. - **Search Client**: You can add the tag filter like: ```ts import { useTypesenseSearch } from 'typesense-fumadocs-adapter/client'; const { search, setSearch, query } = useTypesenseSearch({ tag: '', // ... }); ``` ### Internationalization (i18n) [#internationalization-i18n] Documents include the `locale` of their pages, pass `locale` to the search client: ```ts import { useI18n } from 'fumadocs-ui/contexts/i18n'; import { useTypesenseSearch } from 'typesense-fumadocs-adapter/client'; const { locale } = useI18n(); const { search, setSearch, query } = useTypesenseSearch({ // [!code ++] locale, // other fields... }); ``` Under the hood, Typesense will create separate collections for each locale. The collection name is appended with the `_{locale}` suffix (e.g., `docs_en`, `docs_fr`). # Fumadocs Core (the core library of Fumadocs): Loader API URL: /docs/headless/source-api Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/source-api/index.mdx Turn content sources into a unified interface ## What it does? [#what-it-does] `loader()` provides an interface for Fumadocs to integrate with different content sources. - Generate [page slugs and page tree](/docs/headless/page-conventions). - Assign URL to each page. - Output useful utilities to interact with content. - `loader()` is a server-side API, not a build-time magic or browser compatible API. - It uses in-memory storage, the files are passed from your content sources. ## Usage [#usage] You can use it with content sources like Fumadocs MDX, see [`source`](/docs/headless/source-api/source) for details. ```ts import { loader } from 'fumadocs-core/source'; import { docs } from 'collections/server'; export const source = loader({ source: docs.toFumadocsSource(), baseUrl: '/docs', }); ``` ### URL [#url] You can override the base URL, or specify a function to generate URL for each page. ```ts import { loader } from 'fumadocs-core/source'; loader({ baseUrl: '/docs', // or you can customize it with function url(slugs, locale) { if (locale) return '/' + [locale, 'docs', ...slugs].join('/'); return '/' + ['docs', ...slugs].join('/'); }, }); ``` ### Slugs [#slugs] Define a custom function to generate slugs from page files. ```ts import { loader } from 'fumadocs-core/source'; loader({ slugs(file, next) { console.log(file.path, file.data); // you can build on the default slugs with `next()` if (file.path.startsWith('blog/')) return ['blog', ...next()]; // or return `undefined` to fallback to default value return ['my', 'slug']; }, }); ``` ### Icons [#icons] Load the [icon](/docs/headless/page-conventions#icons) property specified by page and meta files. ```ts import { loader } from 'fumadocs-core/source'; import { icons } from 'lucide-react'; import { createElement } from 'react'; loader({ icon(icon) { if (!icon) { // You may set a default icon return; } if (icon in icons) return createElement(icons[icon as keyof typeof icons]); }, }); ``` ### I18n [#i18n] Pass the `i18n` config to loader. ```ts title="lib/source.ts" import { i18n } from '@/lib/i18n'; import { loader } from 'fumadocs-core/source'; export const source = loader({ i18n, // [!code highlight] }); ``` With i18n enabled, loader will generate a page tree for every locale. If translations are missing for a page, it fallbacks to [`fallbackLanguage`](/docs/headless/internationalization/config#fallback-language). ## Output [#output] It outputs a content loader instance. ### Get Page [#get-page] Get page with slugs. ```ts import { source } from '@/lib/source'; source.getPage(['slug', 'of', 'page']); // with i18n source.getPage(['slug', 'of', 'page'], 'locale'); ``` #### Custom Props [#custom-props] Pass props to the content of a page, like a version that the reader picks. The content reads them as `props`, like [path params](/docs/headless/page-conventions#path-params): ```ts import { source } from '@/lib/source'; const page = source.getPage(['slug', 'of', 'page'], { props: { version: 'v2' }, // with i18n language: 'locale', }); ``` The page data is generated with these props, including the content and the table of contents. MDX components are props too. Pass them when processed Markdown should render your components: ```ts import { getMDXComponents } from '@/components/mdx'; const page = source.getPage(['slug', 'of', 'page'], { props: { components: getMDXComponents() }, }); const markdown = await page.data.getText('processed'); ``` Search and LLM routes read pages from `getPages()`, which only have their path params. A variant that search or LLMs should see must be a path param. ### Get Pages [#get-pages] Get a list of page available for locale. ```ts import { source } from '@/lib/source'; // from any locale source.getPages(); // for a specific locale source.getPages('locale'); ``` ### Page Tree [#page-tree] ```ts import { source } from '@/lib/source'; // without i18n source.getPageTree(); // with i18n source.getPageTree('locale'); ``` ### Get from Node [#get-from-node] The page tree nodes contain references to their original file path. You can find their original page or meta file from the tree nodes. ```ts import { source } from '@/lib/source'; source.getNodePage(pageNode); source.getNodeMeta(folderNode); ``` ### Params [#params] Generate the path params of every page, for pre-rendering pages. The generated parameter names will be `slug: string[]` and `lang: string` (i18n only). ```ts tab="Next.js" title="app/docs/[[...slug]]/page.tsx" import { source } from '@/lib/source'; export function generateStaticParams() { return source.generateParams(); } ``` ```ts tab="Waku" title="src/pages/docs/[...slugs].tsx" import { source } from '@/lib/source'; export async function getConfig() { const pages = source .generateParams() .map((item) => (item.lang ? [item.lang, ...item.slug] : item.slug)); return { render: 'static' as const, staticPaths: pages, } as const; } ``` ```astro tab="Astro" title="src/pages/docs/[...slug].astro" --- import type { GetStaticPaths } from 'astro'; import { source } from '@/lib/source'; export const prerender = true; export const getStaticPaths = (() => { return source.getPages().map((page) => ({ params: { slug: decodeURI(page.slugs.join('/')) || undefined }, props: { page }, })); }) satisfies GetStaticPaths; --- ``` React Router and TanStack Start pre-render by URL. List the `url` of `source.getPages()` instead. ### Language Entries [#language-entries] Get available languages and its pages. ```ts import { source } from '@/lib/source'; // language -> pages const entries = source.getLanguages(); ``` ## Client API [#client-api] Loader API is best when used in RSC environments, which allows passing JSX nodes across the server-client boundary. For non-RSC environments, it provides a tiny serialization layer. ```ts tab="Server" import { source } from '@/lib/source'; // where you pass loader data async function loader() { const pageTree = source.getPageTree(); return { pageTree: await source.serializePageTree(pageTree), }; } ``` ```tsx tab="Client" import { useFumadocsLoader } from 'fumadocs-core/source/client'; function MyComponent() { // `useLoaderData()` receives loader data (provided by your React framework) const { pageTree, ...data } = useFumadocsLoader(useLoaderData()); // now render it (e.g. via Fumadocs UI) return ...; } ``` ## Dynamic Loader [#dynamic-loader] `dynamicLoader()` provides extra revalidation functionality to content sources, you should use it with a [dynamic source](/docs/headless/source-api/source#dynamic-source). ```ts import { dynamicLoader } from 'fumadocs-core/source'; import { createMySource } from './my-source'; const source = dynamicLoader(createMySource(), { baseUrl: '/docs', }); export async function getSource() { return source.get(); } ``` When you call `await source.get()`, it returns a normal content loader object: ```ts const docs = await getSource(); const page = docs.getPage(['...']); ``` ### Revalidation [#revalidation] Dynamic sources are cached by the loader. If your source changes over time, call `invalidate()` to clear the cache, or `revalidate()` to update the cache: ```ts source.invalidate(); await source.revalidate(); ``` For [multi-source](/docs/headless/source-api/source#multiple-sources) setups, you can invalidate/revalidate a specific source: ```ts source.invalidate('docs'); await source.revalidate('docs'); ``` # Fumadocs Core (the core library of Fumadocs): Loader Plugins URL: /docs/headless/source-api/plugins Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/source-api/plugins.mdx Extend Loader API ## Overview [#overview] Loader plugins can extend `loader()` to customize its output. A list of built-in plugins: - **Lucide Icons**: use icons from [Lucide React](https://lucide.dev) (require `lucide-react` to be installed). ```ts import { loader } from 'fumadocs-core/source'; import { lucideIconsPlugin } from 'fumadocs-core/source/lucide-icons'; export const source = loader({ // ... plugins: [lucideIconsPlugin()], }); ``` ## Creating Plugins [#creating-plugins] Each plugin is an object: ```ts tab="Strictly Typed" import { loader } from 'fumadocs-core/source'; export const source = loader({ plugins: ({ typedPlugin }) => [ typedPlugin({ // plugin config }), ], }); ``` ```ts tab="Simple" import { loader, type LoaderPlugin } from 'fumadocs-core/source'; export const source = loader({ plugins: [myPlugin()], }); function myPlugin(): LoaderPlugin { return { // plugin config }; } ``` `typedPlugin` enforces a more accurate type for plugin, including custom properties from your content source. But to make the plugin reusable (across different loaders), use the `LoaderPlugin` type instead. ### Storage [#storage] During the process, your input source files will be parsed and form a virtual storage in memory. To perform virtual file-system operations before processing, you can hook `transformStorage`. ```ts import { loader } from 'fumadocs-core/source'; export const source = loader({ plugins: ({ typedPlugin }) => [ typedPlugin({ transformStorage({ storage }) { storage.read('my/path'); }, }), ], }); ``` ### Page Tree [#page-tree] The page tree is generated from your file system, some unnecessary information (e.g. unused frontmatter properties) will be filtered. You can customize it using the `transformPageTree`, such as attaching custom properties to nodes, or customising the display name of pages. ```tsx import { loader } from 'fumadocs-core/source'; export const source = loader({ plugins: ({ typedPlugin }) => [ typedPlugin({ transformPageTree: { file(node, file) { // access the original (unfiltered) file data if (file) console.log(this.storage.read(file)); // modify nodes node.name = <>Some JSX Nodes here; return node; }, }, }), ], }); ``` # Fumadocs Core (the core library of Fumadocs): Source URL: /docs/headless/source-api/source Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/source-api/source.mdx Setup sources for Loader API ## Overview [#overview] Content loader accepts different content sources based on a `source` interface. ### Multiple Sources [#multiple-sources] Pass a record of source objects instead ```ts import { loader } from 'fumadocs-core/source'; import { blog, docs } from 'collections/server'; import { lucideIconsPlugin } from 'fumadocs-core/source/lucide-icons'; export const source = loader( { docs: docs.toFumadocsSource(), openapi: blog.toFumadocsSource(), }, { baseUrl: '/docs', }, ); ``` To access properties exclusive to each source: ```ts const page = source.getPage(['...']); if (page.type === 'docs') { console.log(page.data); } else { console.log(page.data); } ``` ### Static Source [#static-source] To plug your own content source, create a `StaticSource` object. Since Loader API doesn't rely on file system, file paths only allow virtual paths like `file.mdx` and `content/file.mdx`, `./file.mdx` and `D://content/file.mdx` are not allowed. ```ts twoslash import type { StaticSource } from 'fumadocs-core/source'; export function createMySource(): StaticSource<{ metaData: { title: string; pages: string[] }; // Your custom type pageData: { title: string; description?: string }; // Your custom type }> { return { files: [ { type: 'page', path: 'folder/index.mdx', data: { title: 'Hello World', // ... }, }, { type: 'meta', path: 'meta.json', data: { title: 'Docs', pages: ['folder'], // ... }, }, ], }; } ``` With [i18n](/docs/headless/internationalization/config), the language of a file is parsed from its path, unless the file specifies a `locale`. ### Dynamic Source [#dynamic-source] For content sources with revalidation, return a `DynamicSource` instead: ```ts import type { DynamicSource } from 'fumadocs-core/source'; export function createMySource(): DynamicSource<{ metaData: { title: string; pages: string[] }; pageData: { title: string; description?: string }; }> { return { async files() { return [ { type: 'page', path: 'folder/index.mdx', data: { title: 'Hello World', }, }, { type: 'meta', path: 'meta.json', data: { title: 'Docs', pages: ['folder'], }, }, ]; }, configure(loader) { // you can revalidate the loader from source, e.g. onMyEvent(() => { void loader.revalidate(); }); }, }; } ``` Dynamic sources can only be consumed by [`dynamicLoader()`](/docs/headless/source-api#dynamic-loader). ## Path Params [#path-params] To support [path params](/docs/headless/page-conventions#path-params) in your source, pass a file like `[framework]/deploy.mdx` as one virtual file. The loader generates a page for each value, with the data from `dataAt()`, or `data` without it. Meta files work the same way: ```ts twoslash import type { StaticSource } from 'fumadocs-core/source'; const files: StaticSource['files'] = [ { type: 'page', path: '[framework]/deploy.mdx', data: { title: 'Deploy' }, dataAt: (params) => ({ title: `Deploy on ${params.framework}` }), }, { type: 'meta', path: '[framework]/meta.json', data: { staticParams: [{ framework: 'waku' }, { framework: 'astro' }] }, dataAt: (params) => ({ title: params.framework }), }, ]; ``` ### Listing Params [#listing-params] To resolve the data of each value ahead of the loader, like frontmatter in code, `getStaticParams()` lists the params with the same rules. It reads the `staticParams` of meta files from your storage, by their paths without extension: ```ts twoslash import { getStaticParams, type Params } from 'fumadocs-core/source'; declare const frontmatter: { staticParams?: Params[] }; declare const metaFiles: Map; // ---cut--- const params = getStaticParams('[framework]/deploy.mdx', { staticParams: frontmatter.staticParams, readStaticParams: (path) => metaFiles.get(path)?.staticParams, }); ``` It returns `undefined` when nothing lists the values. The file is then one page at its literal path. ### Custom Props [#custom-props] To support [custom props](/docs/headless/source-api#custom-props), `dataAt()` takes them as a second argument, with the page data after the loader plugins. Return that data rendered for the params and custom props: ```tsx twoslash import type { StaticSource } from 'fumadocs-core/source'; declare function pageAt(props: object): { title: string }; // ---cut--- const files: StaticSource['files'] = [ { type: 'page', path: '[framework]/deploy.mdx', data: pageAt({}), dataAt: (params, custom) => custom ? { ...custom.data, ...pageAt({ ...params, ...custom.props }) } : pageAt(params), }, ]; ``` A page without `dataAt()` ignores custom props. ### Runtime Outputs [#runtime-outputs] If your source compiles MDX, compile each file once and pass the page props to its content. To generate the table of contents, search records and Markdown with the same props: - set `unstable_runtimeOutputs: true` in the data of the file you compile. On Sätteri, set it in the `data` of the compile options. - add `rehypeHeading` as your last rehype plugin, to generate [heading IDs](/docs/headless/mdx/headings#headings-with-expressions) from the rendered text. ```ts import { VFile } from 'vfile'; const file = new VFile({ path: '[framework]/deploy.mdx', value: source, data: { unstable_runtimeOutputs: true }, }); ``` The plugins then export functions instead of values, like `toc` of [Rehype TOC](/docs/headless/mdx/headings#rehype-toc) and the `_markdown` component of [Remark LLMs](/docs/headless/mdx/remark-llms). Call them with the props of each page: ```tsx twoslash import type { StaticSource } from 'fumadocs-core/source'; import type { StructuredData } from 'fumadocs-core/mdx-plugins/remark-structure'; import type { TOCItemType } from 'fumadocs-core/toc'; import { renderToMarkdown } from 'fumadocs-core/server'; import type { MDXContent, MDXProps } from 'mdx/types'; declare const compiled: { default: MDXContent; toc: (props: object) => TOCItemType[]; _markdown: MDXContent; }; declare const file: { data: { structuredData: StructuredData } }; // ---cut--- const { default: Content, toc, _markdown: Markdown } = compiled; function pageAt(props: object) { return { title: 'Deploy', body: (own: MDXProps) => , toc: toc(props), getMarkdown: () => renderToMarkdown(), structuredData: file.data.structuredData, }; } const files: StaticSource['files'] = [ { type: 'page', path: '[framework]/deploy.mdx', data: pageAt({}), dataAt: (params) => pageAt(params), }, ]; ``` For search, read the records of [Remark Structure](/docs/headless/mdx/structure) from `file.data.structuredData`, not from the export. They include every `` branch, and expressions keep their source text. The `unstable_` prefix means the API may change. Without the flag, a document with [``](/docs/next/markdown#show) fails to compile when Rehype TOC, Remark Structure or Remark LLMs runs. # Fumadocs Core (the core library of Fumadocs): Get TOC URL: /docs/headless/utils/get-toc Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/get-toc.mdx Parse Table of contents from markdown/mdx content Parse Table of contents from markdown/mdx content. > [You can use the remark plugin directly](/docs/headless/mdx/headings) ## Usage [#usage] Note: If you're using a CMS, you should use the API provided by the CMS instead. ```ts import { getTableOfContents } from 'fumadocs-core/content/toc'; const toc = getTableOfContents('## markdown content'); ``` ### Output [#output] An array of [`TOCItemType`](/docs/headless/mdx/headings#output) is returned. # Fumadocs Core (the core library of Fumadocs): Last Modified Time URL: /docs/headless/utils/git-last-edit Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/git-last-edit.mdx Get the last edit time of a file in Github repository ## Usage [#usage] Pass your repository name, and the path to file. ```ts import { getGithubLastEdit } from 'fumadocs-core/content/github'; const time = await getGithubLastEdit({ owner: 'fuma-nama', repo: 'fumadocs', // example: "content/docs/index.mdx" path: `content/docs/${page.path}`, }); ``` ### Github Token [#github-token] Notice that you may easily reach the rate limit in development mode. Hence, you should pass a Github token for a higher rate limit. Learn more about [Authenticating to the REST API](https://docs.github.com/en/rest/overview/authenticating-to-the-rest-api). ```ts import { getGithubLastEdit } from 'fumadocs-core/content/github' const time = await getGithubLastEdit({ ..., token: `Bearer ${process.env.GIT_TOKEN}` }) ``` Also, you can skip this in development mode if you don't need that functionality. ```ts process.env.NODE_ENV === 'development'? null : getGithubLastEdit(...) ``` ### Custom GitHub Base URL [#custom-github-base-url] If you need to access GitHub a instance at a url other than `https://api.github.com`, you can override the base URL: ```ts import { getGithubLastEdit } from 'fumadocs-core/content/github'; const time = await getGithubLastEdit({ owner: 'your-org', repo: 'your-repo', path: `content/docs/${page.path}`, baseUrl: 'https://api.octocorp.ghe.com', // Your custom GitHub API URL }); ``` The `baseUrl` parameter defaults to `'https://api.github.com'` if not specified. # Fumadocs Core (the core library of Fumadocs): Utilities URL: /docs/headless/utils Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/index.mdx Utilities to provide extra functionality to your docs - [Get TOC](/docs/headless/utils/get-toc): Parse Table of contents from markdown/mdx content - [Last Modified Time](/docs/headless/utils/git-last-edit): Get the last edit time of a file in Github repository - [Markdown Rendering](/docs/headless/utils/markdown): Render React elements into Markdown. - [MCP](/docs/headless/utils/mcp): Expose your docs to AI agents as MCP tools. - [Negotiation](/docs/headless/utils/negotiation): Content negotiation utilities. - [Page Tree Utils](/docs/headless/utils/page-tree): Common utilities to interact with page tree. - [Highlighter](/docs/headless/utils/shiki): Highlight code with Shiki, or a highlighter of your choice. # Fumadocs Core (the core library of Fumadocs): Markdown Rendering URL: /docs/headless/utils/markdown Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/markdown.mdx Render React elements into Markdown. ## Overview [#overview] `fumadocs-core/server` renders React Server Components, into a Markdown document: ```tsx tab="Input" import { renderToMarkdown } from 'fumadocs-core/server'; const text = await renderToMarkdown(

Hello World

Some rich content.

, ); ``` ```md tab="Output" ## Hello World Some **rich** content. ``` It powers the component exported by [Remark LLMs](/docs/headless/mdx/remark-llms#jsx-elements), and works on any server-rendered content you want to serve as Markdown. > `renderToMarkdown()` is server-only. ## `asMarkdown` [#asmarkdown] Components define their own Markdown form. Calling `asMarkdown()` during render is the opt-in: it returns the [target](#targets) when the component is being rendered into Markdown, and the HTML elements it returns are converted. ```tsx import { asMarkdown, md } from 'fumadocs-core/server'; function Callout({ title, children }) { if (asMarkdown()) return md.linePrefix('> ')`**${title}**\n${children}`; return
...
; } ``` A component that never calls it is kept as JSX syntax with its props, like: ```mdx ... ``` This includes client components, which don't execute on the server. ### Targets [#targets] A tree renders for a target, the `target` option of `renderToMarkdown()`: - `markdown` (default): the document for agents. - `search`: the text of [search records](/docs/headless/mdx/structure#components). It has the text of links, no images or code blocks, and a component without a Markdown form is an HTML tag with its text props. These rules apply to the elements a component returns, like `
`. A link written as text in an `md` template keeps its target in search, so return the element, or check the target. `asMarkdown()` returns the target, so a component can give agents more than search indexes: ```tsx import { asMarkdown, md } from 'fumadocs-core/server'; function Version({ name, released }) { const target = asMarkdown(); if (target === 'search') return name; if (target) return md`${name} (released ${released})`; return {name}; } ``` ## `md` [#md] Tagged template for Markdown output, interpolated values can be strings, React nodes, promises, or arrays of them. Use it to stringify `children` before manipulating them. Two variants return the content as a block: - `md.linePrefix(prefix)`: prefix every line, e.g. `'> '` for quote blocks. - `md.indent(size)`: indent every line. ## `renderRoute` [#renderroute] Render a page element into Markdown, or `undefined` when its component doesn't call `asMarkdown()`. ```tsx import { renderRoute } from 'fumadocs-core/server'; const text = await renderRoute(); ``` Useful for serving a Markdown variant of a route: pages that opt in produce Markdown, other pages return `undefined` so you can fall back to a 404 or another source. # Fumadocs Core (the core library of Fumadocs): MCP URL: /docs/headless/utils/mcp Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/mcp.mdx Expose your docs to AI agents as MCP tools. `fumadocs-core/mcp` registers tools on a [MCP](https://modelcontextprotocol.io) server, for AI agents to read and search your docs. The [MCP Server](/docs/next/integrations/llms#mcp-server) guide sets up a route with these tools for you. ## Usage [#usage] ```package-install fumadocs-core @modelcontextprotocol/server zod ``` Register the tools with your source, its [`docsLlms`](/docs/next/integrations/llms#markdown-for-llms) renderer, and a search server: ```ts title="lib/mcp.ts" import { McpServer } from '@modelcontextprotocol/server'; import { registerSearchTool, registerSourceTools } from 'fumadocs-core/mcp'; import { createFromSource } from 'fumadocs-core/search/server'; import { source, docsLlms } from '@/lib/source'; export const mcp = new McpServer({ name: 'docs', version: '1.0.0' }); // `list_pages` & `get_page` registerSourceTools(mcp, source, docsLlms); // `search` registerSearchTool(mcp, createFromSource(source)); ``` For runtime content sources, pass the getter of your source: ```ts registerSourceTools(mcp, getSource, docsLlms); ``` Then connect the server to a transport, like the streamable HTTP transport. ## Tools [#tools] | Tool | Input | Output | | ------------ | ------------------ | --------------------------------------------------- | | `list_pages` | None | `llms.index()`, the index of pages | | `get_page` | `url` of a page | `llms.page(page)`, or an error when no page matches | | `search` | `query`, `locale?` | the search results, as JSON | # Fumadocs Core (the core library of Fumadocs): Negotiation URL: /docs/headless/utils/negotiation Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/negotiation.mdx Content negotiation utilities. ## Overview [#overview] For React frameworks supporting middlewares, you can use the Negotiation API of Fumadocs for basic functionalities. On Waku, use it in a [Hono middleware](https://hono.dev/docs/guides/middleware) in `src/middleware`. On Astro, use it in a [middleware](https://docs.astro.build/en/guides/middleware), which only runs for pages rendered on request. ### Accept Markdown [#accept-markdown] Serve markdown or HTML depending on the `Accept` header, this can improve the experience for AI agents. ```ts tab="Next.js" title="proxy.ts" import { NextRequest, NextResponse } from 'next/server'; import { isMarkdownPreferred, rewritePath } from 'fumadocs-core/negotiation'; const { rewrite: rewriteLLM } = rewritePath('/docs/*path', '/llms.mdx/*path'); export default function proxy(request: NextRequest) { if (isMarkdownPreferred(request)) { const result = rewriteLLM(request.nextUrl.pathname); if (result) { return NextResponse.rewrite(new URL(result, request.nextUrl)); } } return NextResponse.next(); } ``` ```tsx tab="React Router" title="app/root.tsx" import type { Route } from './+types/root'; import { isMarkdownPreferred, rewritePath } from 'fumadocs-core/negotiation'; const { rewrite: rewriteLLM } = rewritePath('/docs/*path', '/llms.mdx/*path'); const serverMiddleware: Route.MiddlewareFunction = async ({ request }, next) => { const url = new URL(request.url); const result = isMarkdownPreferred(request) && rewriteLLM(url.pathname); // the headers of `Response.redirect()` are immutable, build the response directly if (result) return new Response(null, { status: 302, headers: { Location: new URL(result, url).toString(), Vary: 'Accept' }, }); return next(); }; export const middleware = [serverMiddleware]; ``` ```ts tab="TanStack Start" title="src/start.ts" import { createMiddleware, createStart } from '@tanstack/react-start'; import { redirect } from '@tanstack/react-router'; import { isMarkdownPreferred, rewritePath } from 'fumadocs-core/negotiation'; const { rewrite: rewriteLLM } = rewritePath('/docs/*path', '/llms.mdx/*path'); const llmMiddleware = createMiddleware().server(({ next, request }) => { const url = new URL(request.url); const result = isMarkdownPreferred(request) && rewriteLLM(url.pathname); // redirect to the Markdown URL if (result) throw redirect({ href: new URL(result, url).href, headers: { Vary: 'Accept' } }); return next(); }); export const startInstance = createStart(() => ({ requestMiddleware: [llmMiddleware], })); ``` # Fumadocs Core (the core library of Fumadocs): Page Tree Utils URL: /docs/headless/utils/page-tree Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/page-tree.mdx Common utilities to interact with page tree. ## Usage [#usage] See [Definitions](/docs/headless/page-tree) to learn more about Page Tree. ```ts import { findNeighbour, findSiblings, getPageTreeRoots, findParent, findPath, type Root, } from 'fumadocs-core/page-tree'; const pageTree: Root = { // ...the root of page tree }; // Get neighbours of a page const neighbours = findNeighbour(pageTree, '/url/to/page'); // Get a list of root folders const roots = getPageTreeRoots(pageTree); // Get the sibling nodes of a page const siblings = findSiblings(pageTree, '/url/to/page'); // Get the parent node of a page const parent = findParent(pageTree, '/url/to/page'); // Find the path to the first matching node const path = findPath( pageTree.children, // matcher (node) => node.type === 'page' && node.url === '/url/to/page', ); ``` # Fumadocs Core (the core library of Fumadocs): Highlighter URL: /docs/headless/utils/shiki Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/utils/shiki.mdx Highlight code with Shiki, or a highlighter of your choice. Fumadocs highlights code with [Shiki](https://shiki.style) by default. You can create a highlighter and pass it to the places that highlight code instead, Shiki isn't loaded then. ```ts tab="Highlights" title="lib/highlighter.ts" // npm i @pierre/highlights import { createHighlights } from 'fumadocs-core/highlight/highlights'; import githubLight from '@pierre/highlights/themes/github-light'; import githubDark from '@pierre/highlights/themes/github-dark'; export const highlighter = createHighlights({ themes: { light: githubLight, dark: githubDark }, }); ``` ```ts tab="Shiki" title="lib/highlighter.ts" import { createShikiHighlighter } from 'fumadocs-core/highlight/shiki'; import { defaultShikiFactory } from 'fumadocs-core/highlight/shiki/full'; export const highlighter = createShikiHighlighter(() => defaultShikiFactory.getOrInit(), { themes: { light: 'github-light', dark: 'github-dark' }, // Fumadocs UI colors tokens with CSS variables defaultColor: false, }); ``` [Highlights](https://diffs.com/highlights) is written in WebAssembly and many times faster than Shiki. It has 80 languages built in (others are highlighted as plain text), uses [its own themes](https://diffs.com/docs#highlights) from `@pierre/highlights/themes`, and runs Shiki transformers through `shikiTransformers`, a compatibility layer. `highlighter.override()` creates a highlighter with other options, like other transformers. ## Usage [#usage] `rehypeCodeFromHighlighter` is a rehype plugin. Use it in place of the default Shiki plugin of Fumadocs MDX: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import { rehypeCodeFromHighlighter } from 'fumadocs-core/mdx-plugins/rehype-code.core'; import { highlighter } from './lib/highlighter'; export default defineConfig({ mdxOptions: { // disable the default Shiki plugin rehypeCodeOptions: false, rehypePlugins: (v) => [ () => rehypeCodeFromHighlighter( // created with the transformers of Fumadocs, like notations and icons ({ transformers }) => highlighter.override({ shikiTransformers: transformers }), ), ...v, ], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; import { rehypeCodeFromHighlighter } from '@fumadocs/satteri/rehype-code'; import { highlighter } from './lib/highlighter'; export const docs = defineDocs({ docs: { compiler: 'satteri', }, }); export default defineConfig({ satteriOptions: { // disable the default Shiki plugin rehypeCodeOptions: false, hastPlugins: [ rehypeCodeFromHighlighter( // created with the transformers of Fumadocs, like notations and icons ({ transformers }) => highlighter.override({ shikiTransformers: transformers }), ), ], }, }); ``` Pass it to the code block components: ```tsx tab="Server Code Block" title="components/codeblock.tsx" import { createServerCodeBlock } from 'fumadocs-ui/components/codeblock.rsc'; import { highlighter } from '@/lib/highlighter'; export const ServerCodeBlock = createServerCodeBlock({ highlighter }); ``` ```tsx tab="Dynamic Code Block" title="components/dynamic-codeblock.tsx" 'use client'; import { createDynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock.core'; import { highlighter } from '@/lib/highlighter'; export const DynamicCodeBlock = createDynamicCodeBlock({ highlighter }); ``` Integrations take it in their main entry: | Integration | Option | | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | | [Local Markdown (Sätteri)](/docs/next/integrations/content/satteri-local-md) | `rehypeCodeFromHighlighter()` from `@fumadocs/satteri/rehype-code` in `hastPlugins` | | [Python](/docs/next/integrations/content/python), [Local HTML](/docs/next/integrations/content/local-html) | `createPython({ highlighter })`, `localHtml({ highlighter })` | | [OpenAPI](/docs/next/integrations/openapi), GraphQL, AsyncAPI | `createOpenAPIPage({ highlighter })` | | [Type Table](/docs/ui/components/auto-type-table) | `remarkAutoTypeTable({ highlighter })`, `` | | shadcn | `createSnippet({ highlighter })` from `@fumadocs/shadcn/rsc` | Where Fumadocs adds transformers to code blocks, like `rehypeCodeFromHighlighter()` and the ones of Python, Local HTML and shadcn, a function receives them. ## Shiki Factory [#shiki-factory] Fumadocs manages Shiki instances with Shiki factories, you can create one for special purposes like using fine-grained bundles: ```ts import { createShikiFactory } from 'fumadocs-core/highlight/shiki'; export const myShikiFactory = createShikiFactory({ async init(options) { const { createHighlighter, createJavaScriptRegexEngine } = await import('shiki'); return createHighlighter({ langs: [], themes: [], langAlias: options?.langAlias, engine: createJavaScriptRegexEngine(), }); }, }); ``` Then pass it to different modules/features: ```tsx tab="Dynamic CodeBlock (UI)" 'use client'; import * as Base from 'fumadocs-ui/components/dynamic-codeblock.core'; export type DynamicCodeblockProps = Omit; export function DynamicCodeBlock(props: DynamicCodeblockProps) { return myShikiFactory.getOrInit()} {...props} />; } ``` ```ts tab="Highlighter" import { createShikiHighlighter } from 'fumadocs-core/highlight/shiki'; export const highlighter = createShikiHighlighter(() => myShikiFactory.getOrInit(), { themes: { light: 'github-light', dark: 'github-dark' }, defaultColor: false, }); ``` ## Custom Highlighter [#custom-highlighter] Implement the `Highlighter` interface: ```ts import type { Highlighter } from 'fumadocs-core/highlight'; export const highlighter: Highlighter = { codeToHast(code, { lang, structure, meta }) { // return `pre > code > span.line` with `meta` on `
`, or the content of `` when `structure` is `inline`
  },
  // optional, for languages loaded on demand
  async loadLanguage(...langs) {},
};
```

Fumadocs UI colors the tokens with CSS variables like `--shiki-light` and `--shiki-dark`. Pass it like other highlighters, or highlight a rehype pipeline of your own with `rehypeCodeFromHighlighter`:

```ts
import { rehypeCodeFromHighlighter } from 'fumadocs-core/mdx-plugins/rehype-code.core';

unified().use(rehypeCodeFromHighlighter, highlighter);
```

# Fumadocs MDX (the built-in content source): Bun
URL: /docs/mdx/loader/bun
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/(integrations)/loader/bun.mdx

Access content in Bun.

## Setup [#setup]

Register the plugin in preload script:

```toml tab="bunfig.toml"
preload = ["./scripts/preload.ts"]
```

```ts tab="scripts/preload.ts"
import { createMdxPlugin } from 'fumadocs-mdx/bun';

await Bun.plugin(createMdxPlugin());
```

The plugin loads MDX and meta files at runtime. Its setup is asynchronous, so `await` it. Without `await`, your scripts import `lib/source.ts` before the plugin is ready, and the [Macro API](/docs/mdx/macro) throws an error.

Now running any script with Bun, you can access your content files directly.

### Re-generate `.source` folder [#re-generate-source-folder]

Optionally, you can re-generate the `.source` folder.

It is useful when the folder could be missing,
or you are on a Vite framework (React Router, TanStack Start, Waku), which defaults to generating code with Vite-specific APIs.

```ts title="scripts/preload.ts" tab="Next.js"
import { postInstall } from 'fumadocs-mdx/next';

await postInstall({ configPath: 'source.config.ts' });
```

```ts title="scripts/preload.ts" tab="Vite"
import { postInstall } from 'fumadocs-mdx/vite';

await postInstall({
  configPath: 'source.config.ts',
  index: {
    target: 'bun',
  },
});
```

# Fumadocs MDX (the built-in content source): Runtime Loader
URL: /docs/mdx/loader
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/(integrations)/loader/index.mdx

Fumadocs MDX loader integration.

## Introduction [#introduction]

By default, Fumadocs MDX requires a bundler to work.

When you are accessing your content without a bundler, such as:

- A script executed by Node.js or Bun.
- Any unbundled environment.

You will need a runtime loader. See below for available loader integrations.

- [Bun](/docs/mdx/loader/bun): Access content in Bun.
- [Node.js](/docs/mdx/loader/node): Access content in Node.js runtime.

# Fumadocs MDX (the built-in content source): Node.js
URL: /docs/mdx/loader/node
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/(integrations)/loader/node.mdx

Access content in Node.js runtime.

## Setup [#setup]

Run your scripts with a TypeScript runner like [tsx](https://tsx.is), because `lib/source.ts` of the templates has extensionless imports and path aliases that Node.js can't resolve.

```ts title="scripts/example.ts"
import { register } from 'fumadocs-mdx/node';

// register the Node.js loader
register();

// accessing content
const { source } = await import('../lib/source');
console.log(source.getPages());
```

```npm
npx tsx scripts/example.ts
```

The loader only transforms ES modules. Set `"type": "module"` in your `package.json`, so `lib/source.ts` loads as one. It applies to every `.js` file of the package, so convert CommonJS files like `next.config.js` to ESM first.

The `register()` function accepts options:

```ts
register({
  configPath: '...',
  // ...
});
```

# Fumadocs MDX (the built-in content source): Next.js
URL: /docs/mdx/next
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/(integrations)/next.mdx

Use Fumadocs MDX with Next.js

## Setup [#setup]

Set up Fumadocs MDX for your Next.js application.

### Installation [#installation] ```npm npm i fumadocs-mdx fumadocs-core @types/mdx ``` Add the plugin to Next.js config: ```js title="next.config.mjs" import { createMDX } from 'fumadocs-mdx/next'; /** @type {import('next').NextConfig} */ const config = { reactStrictMode: true, }; // [!code ++:4] const withMDX = createMDX(); // [!code highlight] export default withMDX(config); ``` Fumadocs MDX is ESM-only, it's recommended to use `next.config.mjs` for accurate ESM resolution. For TypeScript config file, it requires Native Node.js TypeScript Resolver, you can see [Next.js docs](https://nextjs.org/docs/app/api-reference/config/typescript#using-nodejs-native-typescript-resolver-for-nextconfigts) for details. ### Integrate with Fumadocs [#integrate-with-fumadocs] Create a `lib/source.ts` file: ```ts title="lib/source.ts" import { defineDocs } from 'fumadocs-mdx/macro'; import { loader } from 'fumadocs-core/source'; const docs = defineDocs({ dir: 'content/docs', }); export const source = loader({ baseUrl: '/docs', source: docs.toFumadocsSource(), }); ``` ### Done [#done] You can now write content in `content/docs` folder.
## What is Next? [#what-is-next] Define collections in your app modules with `fumadocs-mdx/macro`. Define collections in `source.config.ts` with generated entry files. Hit performance bottleneck? You can try lazy loading. # Fumadocs MDX (the built-in content source): Vite URL: /docs/mdx/vite Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/(integrations)/vite.mdx Use Fumadocs MDX with Vite ## Setup [#setup] The plugin works with React Router, TanStack Start, Waku and other Vite apps. Next.js has [its own setup](/docs/mdx/next). Astro uses its own content collections with [`@fumadocs/astro`](/docs/astro/manual-installation) instead of Fumadocs MDX.
### Installation [#installation] ```npm npm i fumadocs-mdx fumadocs-core @types/mdx ``` Add the Vite plugin: ```ts tab="React Router" title="vite.config.ts" import { defineConfig } from 'vite'; import { reactRouter } from '@react-router/dev/vite'; import { fumadocsMdx } from 'fumadocs-mdx/vite'; export default defineConfig({ plugins: [ fumadocsMdx(), // [!code ++] reactRouter(), ], }); ``` ```ts tab="TanStack Start" title="vite.config.ts" import { defineConfig } from 'vite'; import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import react from '@vitejs/plugin-react'; import { fumadocsMdx } from 'fumadocs-mdx/vite'; export default defineConfig({ plugins: [ fumadocsMdx(), // [!code ++] tanstackStart(), react(), ], }); ``` ```ts tab="Waku" title="waku.config.ts" import { type Config, defineConfig } from 'waku/config'; import { fumadocsMdx } from 'fumadocs-mdx/vite'; import type { UserConfig } from 'vite'; export default defineConfig({ vite: { plugins: [ // [!code ++] fumadocsMdx(), ], resolve: { tsconfigPaths: true, }, } satisfies UserConfig as Config['vite'], }); ``` ### Integrate with Fumadocs [#integrate-with-fumadocs] Create a `lib/source.ts` file: ```ts title="lib/source.ts" import { defineDocs } from 'fumadocs-mdx/macro'; import { loader } from 'fumadocs-core/source'; const docs = defineDocs({ dir: 'content/docs', }); export const source = loader({ baseUrl: '/docs', source: docs.toFumadocsSource(), }); ``` ### Done [#done] You can now write content in `content/docs` folder.
## What is Next? [#what-is-next] Define collections in your app modules with `fumadocs-mdx/macro`. Define collections in `source.config.ts` with generated entry files. Hit performance bottleneck? You can try lazy loading. # Fumadocs MDX (the built-in content source): Lazy Loading URL: /docs/mdx/async Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/async.mdx Configure lazy loading on collection outputs. ## Introduction [#introduction] By default, all Markdown and MDX files need to be pre-compiled first. The same constraint also applies to the development server. This may result in longer dev server start times for large docs sites. You can enable Async or Dynamic mode on doc collections to improve this. ## Async Mode [#async-mode] Async mode will generate collection outputs using async imports. ```ts tab="Docs Collection" import { defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ dir: 'content/docs', docs: { // [!code ++] async: true, }, }); ``` ```ts tab="Doc Collection" import { defineCollections } from 'fumadocs-mdx/config'; export const doc = defineCollections({ type: 'doc', dir: 'content/docs', // [!code ++] async: true, }); ``` Depending on your bundler, this may reduce compilation time significantly on development server. Turbopack doesn't support lazy bundling at the moment, async mode will only improve server performance. ## Dynamic Mode [#dynamic-mode] Dynamic mode works by performing **on-demand compilation**, then execute the output on runtime. It is recommended to install & externalize `shiki`: ```npm npm i shiki ``` Enable dynamic mode in collections like: ```ts tab="Docs Collection" import { defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ dir: 'content/docs', docs: { // [!code ++] dynamic: true, }, }); ``` ```ts tab="Doc Collection" import { defineCollections } from 'fumadocs-mdx/config'; export const doc = defineCollections({ type: 'doc', dir: 'content/docs', // [!code ++] dynamic: true, }); ``` Then, follow [Dynamic Entry](/docs/mdx/entry/dynamic) to access the collection from dynamic entry instead. Dynamic mode comes with some limitations on MDX features. - **No import/export allowed in MDX files.** For MDX components, pass them from the `components` prop instead. - **Images must be referenced with URL (e.g. `/images/test.png`).** Don't use **file paths** like `./image.png`. You should locate your images in the `public` folder and reference them with URLs. ## Usage [#usage] Frontmatter properties are still available on `page` object, but you need to invoke the `load()` async function to load the compiled content (and its exports). For example: ```tsx title="page.tsx" import { source } from '@/lib/source'; import { getMDXComponents } from '@/components/mdx'; const page = source.getPage(['...']); if (page) { // frontmatter properties are available console.log(page.data); // Markdown content requires await const { body: MdxContent, toc } = await page.data.load(); console.log(toc); return ; } ``` When using Async or Dynamic mode, we highly recommend to use third-party services to implement search, which usually have better capability to handle massive amount of content to index. # Fumadocs MDX (the built-in content source): Collections URL: /docs/mdx/collections Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/collections.mdx Collection of content data for your app ## Define Collections [#define-collections] Define a collection to parse a certain set of files. The examples on this page define collections in `source.config.ts`, while the [Macro API](/docs/mdx/macro) defines them in `lib/source.ts` with largely the same options. ```ts import { defineCollections } from 'fumadocs-mdx/config'; import { z } from 'zod'; export const blog = defineCollections({ type: 'doc', dir: './content/blog', schema: z.object({ // schema }), // other options }); ``` ### `type` [#type] The accepted type of collection. ```ts import { defineCollections } from 'fumadocs-mdx/config'; // only scan for meta files export const metaFiles = defineCollections({ type: 'meta', // options }); ``` - `type: meta` Accept JSON/YAML files and code modules (`meta.ts` or `meta.js`) with a default export. See [Meta](/docs/next/page-conventions#meta). Available options: ### MetaCollection | Prop | Type | Description | | --------- | ------------------------------------------------------ | ----------- | | `type` | `"meta"` | | | `schema?` | `CollectionSchema \| undefined` | | | `dir` | `string` | | | `files?` | `string[] \| undefined` | | - `type: doc` Markdown/MDX documents, available options: ### DocCollection | Prop | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | `"doc"` | | | `compiler?` | `"mdx" \| "satteri" \| undefined` | | | `mdxOptions?` | `ProcessorOptions \| ((environment: BuildEnvironment) => Promise) \| undefined` | By defining a collection-level MDX options, **the default options & plugins will be removed**. | | `satteriOptions?` | `SatteriOptionsInput` | Sätteri compile options. When omitted, the global `satteriOptions` preset is used. | | `dir` | `string` | | | `files?` | `string[] \| undefined` | | | `postprocess?` | `Partial \| undefined` | | | `async?` | `boolean \| undefined` | | | `dynamic?` | `boolean \| undefined` | | | `schema?` | `CollectionSchema \| undefined` | | | `lastModified?` | `boolean \| LastModifiedFn \| undefined` | Expose the last modified date of each document. - `true`: obtained from Git. Requires `git` to be installed. If you are using Vercel, please set the `VERCEL_DEEP_CLONE` environment variable to `true`. - A function: return the last modified time for a given file path. | ### `schema` [#schema] The schema to validate file data (frontmatter on `doc` type, content on `meta` type). ```ts import { defineCollections } from 'fumadocs-mdx/config'; import { z } from 'zod'; export const blog = defineCollections({ type: 'doc', dir: './content/blog', schema: z.object({ name: z.string(), }), }); ``` > [Standard Schema](https://standardschema.dev) compatible libraries, including Zod, are supported. Note that the validation is done at build time, hence the output must be serializable. You can also pass a function that receives the transform context. ```ts import { defineCollections } from 'fumadocs-mdx/config'; import { z } from 'zod'; export const blog = defineCollections({ type: 'doc', dir: './content/blog', schema: (ctx) => { return z.object({ name: z.string(), testPath: z.string().default( // absolute path of the file ctx.path, ), }); }, }); ``` ### `mdxOptions` [#mdxoptions] Customize MDX options at the collection level, for collections compiled with unified. > This API is only available on `doc` type. ```ts title="source.config.ts" import { defineCollections } from 'fumadocs-mdx/config'; export const blog = defineCollections({ type: 'doc', dir: './content/blog', mdxOptions: { // mdx options }, }); ``` By design, this will remove all default settings applied by your global config and Fumadocs MDX. You have full control over MDX options. You can use [`applyMdxPreset`](/docs/mdx/mdx) to apply the default MDX preset. ```ts title="source.config.ts" import { applyMdxPreset, defineCollections } from 'fumadocs-mdx/config'; export const blog = defineCollections({ type: 'doc', dir: './content/blog', mdxOptions: applyMdxPreset({ // extend the preset }), }); ``` ### `compiler` [#compiler] > This API is only available on `doc` type. Compile the collection with [Sätteri](/docs/mdx/mdx#satteri) instead of unified, and pass `satteriOptions` in place of `mdxOptions`. ```ts title="source.config.ts" import { defineCollections } from 'fumadocs-mdx/config'; export const blog = defineCollections({ type: 'doc', dir: './content/blog', compiler: 'satteri', // optional, defaults to the global `satteriOptions` satteriOptions: { // Sätteri options }, }); ``` Unlike `mdxOptions`, the collection-level `satteriOptions` keeps the default preset unless you pass `preset: 'minimal'`. It replaces the global `satteriOptions` instead of merging with them. ### `postprocess` [#postprocess] > This API is only available on `doc` type. You can pass build-time information to runtime using the `postprocess` API. - #### `includeProcessedMarkdown` [#includeprocessedmarkdown] Export the Markdown of documents, generated by [Remark LLMs](/docs/headless/mdx/remark-llms). Pass `true` or its options. ```ts tab="docs" import { defineDocs } from 'fumadocs-mdx/config'; export default defineDocs({ docs: { postprocess: { // [!code ++] includeProcessedMarkdown: true, }, }, }); ``` ```ts tab="doc" import { defineCollections } from 'fumadocs-mdx/config'; export const blog = defineCollections({ type: 'doc', postprocess: { // [!code ++] includeProcessedMarkdown: true, }, }); ``` Read it with `getText('processed')`, e.g. from `loader()`: ```ts import { source } from '@/lib/source'; const page = source.getPage('...'); console.log(await page.data.getText('processed')); ``` - #### `valueToExport` [#valuetoexport] Some remark plugins store their output in `vfile.data` (compile-time memory) which cannot be accessed from your code. You can specify the name of properties to include, they will get converted into ESM exports that you can access when importing the MDX file. ```ts tab="docs" import { defineDocs } from 'fumadocs-mdx/config'; export default defineDocs({ docs: { postprocess: { // [!code ++] valueToExport: ['dataName'], }, }, }); ``` ```ts tab="doc" import { defineCollections } from 'fumadocs-mdx/config'; export const blog = defineCollections({ type: 'doc', postprocess: { // [!code ++] valueToExport: ['dataName'], }, }); ``` ## Define Docs [#define-docs] Define a collection for Fumadocs. ```ts import { defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ dir: '/my/content/dir', docs: { // optional, options of `doc` collection }, meta: { // optional, options of `meta` collection }, }); ``` ### `dir` [#dir] Instead of per collection, you should customize content directory from `defineDocs`: ```ts import { defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ dir: 'content/guides', }); ``` ### `schema` [#schema-1] You can extend the default Zod 4 schema of `docs` and `meta`. ```ts import { defineDocs } from 'fumadocs-mdx/config'; import { metaSchema, pageSchema } from 'fumadocs-core/source/schema'; import { z } from 'zod'; export const docs = defineDocs({ docs: { schema: pageSchema.extend({ index: z.boolean().default(false), }), }, meta: { schema: metaSchema.extend({ // other props }), }, }); ``` # Fumadocs MDX (the built-in content source): Browser Entry URL: /docs/mdx/entry/browser Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/entry/browser.mdx Access collections from browser/client environment. Macro collections can be imported on the client directly, without a client loader. See [Macro API](/docs/mdx/macro#browser) for the equivalent usage. ## Usage [#usage] The generated outputs are optimized using async imports for browser environments. Only doc/docs collections are accessible on browser. ```tsx import browserCollections from 'collections/browser'; // unloaded entries console.log(browserCollections['collection name'].raw); // define client-side collection loader const clientLoader = browserCollections['collection name'].createClientLoader({ component( // access the compiled file { default: MDX }, // define props (optional) props: { myProp: string }, ) { return (
); }, }); // server (static generator) return a path async function serverLoader() { return source.getPage(slugs)!.path; } async function loader() { const path = await serverLoader(); // preload the path await clientLoader.preload(path); return { path }; } function Page() { const { path } = loader(); // render the content return clientLoader.useContent(path, { myProp: 'hello world', }); } ``` ### Path Params [#path-params] For a page of [path params](/docs/next/page-conventions#path-params), pass its params after its path: ```tsx async function serverLoader() { const page = source.getPage(slugs)!; return { path: page.path, params: page.params }; } async function loader() { const { path, params } = await serverLoader(); await clientLoader.preload(path, params); return { path, params }; } function Page() { const { path, params } = loader(); return clientLoader.useContent(path, { myProp: 'hello world' }, params); } ``` ## Examples [#examples] The examples below are for non-RSC usage on React Router and TanStack Start. On Next.js and Waku, prefer RSC with the [server entry](/docs/mdx/entry/server) for better client performance. The example apps in our repository use the [Macro API](/docs/mdx/macro) for this instead. They are a good reference for a complete setup. ```tsx tab="React Router" title="app/routes/docs.tsx" import type { Route } from './+types/docs'; import { source } from '@/lib/source'; import browserCollections from 'collections/browser'; export async function loader({ params }: Route.LoaderArgs) { const slugs = params['*'].split('/').filter((v) => v.length > 0); const page = source.getPage(slugs); if (!page) throw new Response('Not found', { status: 404 }); return { path: page.path, }; } const clientLoader = browserCollections.docs.createClientLoader({ component({ frontmatter, default: MDX }) { return (

{frontmatter.title}

); }, }); export default function Page(props: Route.ComponentProps) { const { path } = props.loaderData; return clientLoader.useContent(path); } ``` ```tsx tab="TanStack Start" title="src/routes/docs/$.tsx" import { createFileRoute, notFound } from '@tanstack/react-router'; import { createServerFn } from '@tanstack/react-start'; import { source } from '@/lib/source'; import browserCollections from 'collections/browser'; export const Route = createFileRoute('/docs/$')({ component: Page, loader: async ({ params }) => { const data = await loader({ data: params._splat?.split('/') ?? [] }); await clientLoader.preload(data.path); return data; }, }); const loader = createServerFn({ method: 'GET', }) .validator((slugs: string[]) => slugs) .handler(async ({ data: slugs }) => { const page = source.getPage(slugs); if (!page) throw notFound(); return { path: page.path, }; }); const clientLoader = browserCollections.docs.createClientLoader({ component({ frontmatter, default: MDX }) { return (

{frontmatter.title}

); }, }); function Page() { const data = Route.useLoaderData(); return clientLoader.useContent(data.path); } ``` # Fumadocs MDX (the built-in content source): Dynamic Entry URL: /docs/mdx/entry/dynamic Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/entry/dynamic.mdx Accessing your collections with on-demand compilation. ## Usage [#usage] Enable [dynamic mode](/docs/mdx/async#dynamic-mode) on docs/doc collections, and import it from `dynamic` entry instead of `server`. It offers the same output as `server` entry, while compiled properties have to be loaded via `load()` method. ```ts tab="Docs (Meta + Doc)" // [!code highlight] import { docs } from 'collections/dynamic'; import { loader } from 'fumadocs-core/source'; export const source = loader({ baseUrl: '/docs', source: docs.toFumadocsSource(), }); ``` ```ts tab="Doc" // [!code highlight] import { blogPosts } from 'collections/dynamic'; import { toFumadocsSource } from 'fumadocs-mdx/runtime/server'; import { loader } from 'fumadocs-core/source'; export const blog = loader({ baseUrl: '/blog', source: toFumadocsSource(blogPosts, []), }); ``` # Fumadocs MDX (the built-in content source): Import MDX Files URL: /docs/mdx/entry/import Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/entry/import.mdx Importing MDX files directly. ## Introduction [#introduction] MDX files will be compiled into JavaScript with exports like: - `default`: the main component. - `frontmatter`: frontmatter data. - other properties generated by remark/rehype plugins. Hence, they can also be used as a page, or components that you can import. ### Using as Component [#using-as-component] You can import them as a component: ```tsx title="app/my-page.tsx" import MyPage from '@/content/page.mdx'; import { getMDXComponents } from '@/components/mdx'; export default function Page() { return (
{/* pass MDX components and render it */}
); } ``` ### Using as Page [#using-as-page] On Next.js, you can use `page.mdx` instead of `page.tsx` for creating a new page under the app directory. ```mdx tab="app/my-page/page.mdx" --- title: My Page --- export { default } from '@/components/layouts/page'; # Hello World This is my page. ``` ```tsx tab="components/layouts/page.tsx" import type { ComponentProps } from 'react'; export default function Content(props: ComponentProps<'main'>) { return (
{props.children}
); } ``` It doesn't have **MDX components** by default, you have to provide them: ```tsx tab="components/mdx.tsx" import defaultMdxComponents from 'fumadocs-ui/mdx'; import type { MDXComponents } from 'mdx/types'; export function getMDXComponents(components?: MDXComponents) { return { ...defaultMdxComponents, // for Fumadocs UI ...components, } satisfies MDXComponents; } // export a `useMDXComponents()` that returns MDX components export const useMDXComponents = getMDXComponents; // [!code ++] ``` ```ts tab="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { // Path to import your `components/mdx.tsx` above. [!code ++:2] providerImportSource: '@/components/mdx', }, }); ``` On React Router, TanStack Start and Waku, import MDX files as components in your pages instead. # Fumadocs MDX (the built-in content source): Accessing Collections URL: /docs/mdx/entry Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/entry/index.mdx Access collection outputs from entry files. ## Overview [#overview] After defining collections in your config file, collection entries are compiled into JavaScript files that your app can access. While the compilation will be done by Fumadocs MDX's bundler/runtime plugins, it also generates **entry files** to access the collection outputs. If you prefer defining collections in app modules instead, see the [Macro API](/docs/mdx/macro). ### Entry Files [#entry-files] Collection outputs will be generated under the output directory, you can access them from entry files. See below for a list of available ways to access outputs. - [Browser Entry](/docs/mdx/entry/browser): Access collections from browser/client environment. - [Dynamic Entry](/docs/mdx/entry/dynamic): Accessing your collections with on-demand compilation. - [Import MDX Files](/docs/mdx/entry/import): Importing MDX files directly. - [Server Entry](/docs/mdx/entry/server): Accessing collection outputs from server. # Fumadocs MDX (the built-in content source): Server Entry URL: /docs/mdx/entry/server Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/entry/server.mdx Accessing collection outputs from server. ## Usage [#usage] While you can access the collections directly from entry file, we suggest using it with [`loader()`](/docs/headless/source-api#output). ```ts tab="Docs (Meta + Doc)" import { docs } from 'collections/server'; import { loader } from 'fumadocs-core/source'; // raw collection console.log(docs); export const source = loader({ baseUrl: '/docs', source: docs.toFumadocsSource(), }); ``` ```ts tab="Doc" import { blogPosts } from 'collections/server'; import { toFumadocsSource } from 'fumadocs-mdx/runtime/server'; import { loader } from 'fumadocs-core/source'; // raw collection console.log(blogPosts); export const blog = loader({ baseUrl: '/blog', source: toFumadocsSource(blogPosts, []), }); ``` ## Examples [#examples] ```tsx import { source } from '@/lib/source'; const page = source.getPage(['slugs']); if (page) { // access page data [!code highlight:2] console.log(page.data); // frontmatter properties are also available [!code highlight:2] console.log(page.data.title); } ``` To render the page (on RSC), use `page.data.body` as a component. ```tsx import { getMDXComponents } from '@/components/mdx'; const MDX = page.data.body; // set your MDX components with `components` prop return ; ``` # Fumadocs MDX (the built-in content source): Global Options URL: /docs/mdx/global Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/global.mdx Customize Fumadocs MDX Global options of Fumadocs MDX, like the MDX plugins of every collection, go in `source.config.ts` at the project root. The file is optional, and works with collections defined by the [Macro API](/docs/mdx/macro) in `lib/source.ts`. ## Global Options [#global-options] ```ts title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ // global options }); ``` ### GlobalConfig | Prop | Type | Description | | ------------------------- | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `plugins?` | `PluginOption[] \| undefined` | | | `compiler?` | `"mdx" \| "satteri" \| undefined` | The compiler for files compiled without a collection (e.g. `page.mdx` routes). Collections choose their own compiler via the collection-level `compiler` option. Default: `'mdx'` | | `mdxOptions?` | `(() => Promise) \| MDXPresetOptions \| undefined` | Configure global MDX options, used by `doc` collections with the default MDX compiler. | | `satteriOptions?` | `SatteriOptionsInput` | Configure global Sätteri options, used by `doc` collections with `compiler: "satteri"`. | | `workspaces?` | `Record; }> \| undefined` | | | `experimentalBuildCache?` | `string \| undefined` | | ### MDX Options [#mdx-options] Customize the [default preset](/docs/mdx/mdx) of collections. `mdxOptions` applies to collections compiled with unified, and `satteriOptions` to collections with `compiler: 'satteri'`. ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import { myPlugin } from './remark-plugin'; export default defineConfig({ mdxOptions: { // When order matters remarkPlugins: (v) => [myPlugin, ...v], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import { myPlugin } from './mdast-plugin'; export default defineConfig({ satteriOptions: { // When order matters mdastPlugins: (v) => [myPlugin(), ...v], }, }); ``` Or using the minimal preset: ```ts tab="unified" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { preset: 'minimal', // now it accepts only MDX processor options }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ satteriOptions: { preset: 'minimal', // now it accepts only Sätteri compile options }, }); ``` # Fumadocs MDX (the built-in content source): Include URL: /docs/mdx/include Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/include.mdx Reuse content from other files. ## Usage [#usage] Fumadocs MDX always enables [Remark Include](/docs/headless/mdx/remark-include), on both unified and Sätteri. ### Content [#content] To display content from another Markdown/MDX file, specify its path relative to the file itself in the `` tag. ```mdx tab="MDX" ./another.mdx ``` ```md tab="Markdown" ::include[./another.mdx] ``` Do not pass untrusted paths to ``, it can embed any file on your machine, like `.env`. Markdown (`.md`) files do not support JSX syntax. Use the directive syntax instead. Sätteri parses directives by default. On unified, add the `remark-directive` remark plugin: ```ts title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import remarkDirective from 'remark-directive'; export default defineConfig({ mdxOptions: { // [!code ++] remarkPlugins: [remarkDirective], }, }); ``` You may also need `rehype-raw` for HTML comments and content. ### CodeBlock [#codeblock] For other types of files, it will become a codeblock: ```mdx tab="MDX" ./script.ts page.md ``` ```md tab="Markdown" ::include[./script.ts] ::include[page.md]{lang=md meta='title="lib.md"'} ``` You can include only a region of content: ```ts title="code.ts" export function fn() { //#region a console.log('one'); //#endregion } ``` ```mdx tab="MDX" ./code.ts#a ``` ```md tab="Markdown" ::include[./code.ts#a] ``` ### `cwd` [#cwd] Resolve relative paths from cwd instead of the current file: ```mdx tab="MDX" ./script.ts ``` ```md tab="Markdown" ::include[./script.ts]{cwd lang=tsx meta='title="lib.ts"'} ``` ## Extraction [#extraction] When referencing content files, you can only include a certain part of the document. ### Section [#section] Encapsulate by a `
` tag: ```mdx tab="a.mdx" ## Hello World
This is included
This is not included. ``` ```mdx tab="b.mdx" Include the content from `a.mdx`: a.mdx#test ``` In Markdown: ```md tab="a.md" ## Hello World :::section{#test} This is included ::: This is not included. ``` ```md tab="b.md" Include the content from `a.mdx`: ::include[a.md#test] ``` ### Heading [#heading] Include contents under a certain heading. ```mdx tab="a.mdx" ## Included Section I'm here! ## Not Included Some random text. ``` ```mdx tab="b.mdx" Content under the heading: a.mdx#included-section ``` In Markdown: ```md tab="a.md" ## Included Section I'm here! ## Not Included Some random text. ``` ```md tab="b.md" Content under the heading: ::include[a.mdx#included-section] ``` # Fumadocs MDX (the built-in content source): Getting Started URL: /docs/mdx Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/index.mdx Introducing Fumadocs MDX, the official content source of Fumadocs. ## Introduction [#introduction] Fumadocs MDX is a tool to transform content into type-safe data, similar to Content Collections. It is not a full CMS but rather a content processing layer for React frameworks, you can use it to handle blog posts and other contents. ### What is a Collection? [#what-is-a-collection] **Collection** refers to a collection containing a certain type of files. You can define them with the [Macro API](/docs/mdx/macro) in your app: ```ts title="lib/source.ts" import { defineDocs } from 'fumadocs-mdx/macro'; import { loader } from 'fumadocs-core/source'; const docs = defineDocs({ dir: 'content/docs', }); export const source = loader({ baseUrl: '/docs', source: docs.toFumadocsSource(), }); ``` Available collections: Compile Markdown & MDX files into a React component, with useful properties like **Table of Contents**. ```ts import { defineCollections } from 'fumadocs-mdx/macro'; export const test = defineCollections({ type: 'doc', dir: 'content/docs', }); ``` Transform YAML/JSON files into an array of data. ```ts import { defineCollections } from 'fumadocs-mdx/macro'; export const test = defineCollections({ type: 'meta', dir: 'content/docs', }); ``` Combination of `meta` and `doc` collections, which is needed for Fumadocs. ```ts import { defineDocs } from 'fumadocs-mdx/macro'; export const docs = defineDocs({ dir: 'content/docs', docs: { // options for `doc` collection }, meta: { // options for `meta` collection }, }); ``` For example, a `doc` collection will transform the `.md` and `.mdx` files: You can also define collections in `source.config.ts` with the [Config API](/docs/mdx/collections), which generates entry files under `.source`. ## Installation [#installation] Configure Fumadocs MDX on: Using Fumadocs MDX with Next.js. Using Fumadocs MDX with Vite. Using Fumadocs MDX with a JavaScript runtime. ## FAQ [#faq] ### Built-in Properties [#built-in-properties] These properties are exported from MDX files by default. | Property | Description | | --------------------- | ----------------------------------------------- | | `frontmatter` | Frontmatter | | `toc` | Table of Contents | | `structuredData` | Structured Data, useful for implementing search | | `extractedReferences` | For analyzing `hrefs` references | ### Customize Frontmatter [#customize-frontmatter] Use the [`schema`](/docs/mdx/collections#schema-1) option to pass a validation schema to validate frontmatter and define its output properties. An MDX page can also export [frontmatter in code](/docs/next/markdown#frontmatter). The export is merged over the YAML frontmatter, and the collection schema validates the result: ```mdx title="content/docs/index.mdx" --- title: Introduction --- import { version } from '../../package.json'; export const frontmatter = { description: `The docs of v${version}.`, }; ``` The export runs at build time. It can use the page's imports and the exports written before it in the same block, but not the content or components of the page. `staticParams` stays in the YAML frontmatter, because the loader reads it before the export runs. ### Customize Compiler [#customize-compiler] Fumadocs MDX compiles MDX files into JavaScript files with unified, through [MDX Compiler](https://mdxjs.com/packages/mdx). A collection can compile with [Sätteri](/docs/mdx/mdx#satteri) instead. Both come with a default preset of plugins and configurations. You can customize it on [Global Config](/docs/mdx/global#mdx-options) or [Collection Config](/docs/mdx/collections#mdxoptions). # Fumadocs MDX (the built-in content source): Last Modified Time URL: /docs/mdx/last-modified Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/last-modified.mdx Output the last modified time of a document ## Usage [#usage] You can add the plugin from the config file. Please ensure you have Git installed on your machine, and **the repository is not shallow cloned**, as it relies on your local Git history. ```ts title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import lastModified from 'fumadocs-mdx/plugins/last-modified'; export default defineConfig({ // [!code ++] plugins: [lastModified()], }); ``` ### Access the Property [#access-the-property] After doing this, a `lastModified` property will be exported for each document (as `Date`). ```ts import { source } from '@/lib/source'; const page = source.getPage(['...']); console.log(page.data.lastModified); // or with lazy loading const { lastModified } = await page.data.load(); console.log(lastModified); ``` You can display it from UI like [``](/docs/ui/layouts/page#last-updated-time) # Fumadocs MDX (the built-in content source): Macro API URL: /docs/mdx/macro Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/macro.mdx Define collections in your app with fumadocs-mdx/macro. ## Overview [#overview] Declare collections directly in your application modules with `fumadocs-mdx/macro`. The bundler (or runtime loader) compiles `defineDocs` / `defineCollections` into imports of content files. - No codegen needed. - No `source.config.ts` needed. ## Usage [#usage] ```ts tab="lib/source.ts" import { defineDocs } from 'fumadocs-mdx/macro'; import { loader } from 'fumadocs-core/source'; export const docs = defineDocs({ dir: 'content/docs', }); export const source = loader({ baseUrl: '/docs', source: docs.toFumadocsSource(), }); ``` ```ts tab="lib/blog.ts" import { defineCollections } from 'fumadocs-mdx/macro'; import { loader } from 'fumadocs-core/source'; const blog = defineCollections({ type: 'doc', dir: 'content/blog', }); export const blogSource = loader({ baseUrl: '/blog', source: blog.toFumadocsSource(), }); ``` Collection options are largely the same as the [config API](/docs/mdx/collections). You can still keep a `source.config.ts` for [global options](/docs/mdx/global) and plugins while defining collections with macros. ### Monorepos [#monorepos] To share collections between apps, declare them in a workspace package. `dir` is relative to the app that imports the collection, so each app loads its own content. ```ts tab="packages/content/index.ts" import { defineCollections } from 'fumadocs-mdx/macro'; import { pageSchema } from 'fumadocs-core/source/schema'; export const blog = defineCollections({ type: 'doc', dir: 'content/blog', schema: pageSchema, }); ``` ```ts tab="apps/web/lib/source.ts" import { loader } from 'fumadocs-core/source'; import { blog } from '@acme/content'; export const blogSource = loader({ baseUrl: '/blog', source: blog.toFumadocsSource(), }); ``` ### Browser [#browser] Macro collections work in the browser too. Import the collection in a client component and render an entry with `body`, no [client loader](/docs/mdx/entry/browser) needed. ```tsx import { docs } from '@/lib/source'; export default function Page({ path }: { path: string }) { const page = docs.getPage(path); if (!page) return
Not Found
; const MDX = page.body; return (

{page.title}

); } ``` For a page of [path params](/docs/next/page-conventions#path-params), pass its params from the loader: `docs.getPage(page.path, page.params)`. The browser runs the whole module you import `docs` from. When your `loader()` has server-only sources, like `openapi.staticSource()`, define collections in another module (e.g. `lib/collections.ts`) and import them from there. #### Async collections [#async-collections] With [`async`](/docs/mdx/async) enabled, only the frontmatter is bundled upfront and the content is fetched on demand. `body` works the same way, except it suspends until the content is available. Two extra methods control that: - `preload()` loads the content ahead of rendering, so `body` renders without suspending. Call it in your route loader. - `load()` returns the loaded content, such as `toc`. Its promise is cached, so you can call it during render. ```tsx import { use } from 'react'; import { docs } from '@/lib/source'; // in your route loader (React Router, TanStack Start) export async function loader({ path }: { path: string }) { await docs.getPage(path)?.preload(); return { path }; } export default function Page({ path }: { path: string }) { const page = docs.getPage(path); if (!page) return
Not Found
; const { toc } = use(page.load()); const MDX = page.body; return (

{page.title}

); } ``` Since the content is loaded lazily, wrap the page in a `` boundary unless you preloaded it. ## Configuration [#configuration] The Macro API is enabled by default. Pass `macro` to limit which modules may use it, or `false` to disable it. On React Router and TanStack Start, pass it to the Vite plugin. ```js tab="Next.js" title="next.config.mjs" import { createMDX } from 'fumadocs-mdx/next'; const withMDX = createMDX({ macro: { // glob patterns relative to the project root include: ['lib/**/*.ts', 'lib/**/*.tsx'], }, // or disable entirely: // macro: false, }); ``` ```ts tab="Vite" title="vite.config.ts" import { fumadocsMdx } from 'fumadocs-mdx/vite'; export default { plugins: [ fumadocsMdx({ macro: { include: ['src/**/*.ts', 'src/**/*.tsx'], }, }), ], }; ``` ```ts tab="Waku" title="waku.config.ts" import { defineConfig } from 'waku/config'; import { fumadocsMdx } from 'fumadocs-mdx/vite'; export default defineConfig({ vite: { plugins: [ fumadocsMdx({ macro: { include: ['src/**/*.ts', 'src/**/*.tsx'], }, }), ], }, }); ``` ```js tab="Node.js" import { register } from 'fumadocs-mdx/node'; register({ macro: { include: ['lib/**/*.ts'], }, }); ``` By default, all JS/TS modules are eligible (`node_modules` is always excluded). Narrow `include` if you want the transform to run only on specific paths. ### Constraints [#constraints] Macro calls are compiled statically. Keep these rules in mind: - Assign each call to a top-level `const` (the variable name identifies the collection): ```ts // ✓ const docs = defineDocs({ dir: 'content/docs' }); // ✗ not supported export function create() { return defineDocs({ dir: 'content/docs' }); } ``` - Options that shape how content is bundled (`dir`, `files`, `async`) must be statically analyzable (string / boolean literals). Put dynamic logic in options like `schema` or `mdxOptions` instead. - [`dynamic`](/docs/mdx/async#dynamic-mode) collections are not supported by the Macro API yet. Prefer [`async`](/docs/mdx/async) for lazy loading. - Re-exporting from `fumadocs-mdx/macro` is not supported. # Fumadocs MDX (the built-in content source): MDX Presets URL: /docs/mdx/mdx Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/mdx.mdx Customize the default configurations for MDX processor. Fumadocs MDX provides MDX presets to simplify configurations of features like **syntax highlighting**. It compiles with unified by default. A collection can compile with [Sätteri](#satteri) instead, which has a preset of the same plugins. ## Default Preset [#default-preset] A preset designed for documentation sites, it is enabled by default for global MDX options. To override the defaults, it accepts an interface inherited from [`ProcessorOptions`](https://mdxjs.com/packages/mdx/#processoroptions): ### Remark Plugins [#remark-plugins] These plugins are applied by default: - Remark GFM - [GitHub Flavored Markdown](https://github.github.com/gfm). - [Remark Heading](/docs/headless/mdx/headings) - Extract table of contents. - [Remark Image](/docs/headless/mdx/remark-image) - Handle images. - [Remark Code Tab](/docs/next/markdown#tab-groups) - Code block tab groups. - [Remark NPM](/docs/headless/mdx/remark-npm) - Package manager commands. - [Remark Structure](/docs/headless/mdx/structure) - Generate search indexes. [Include](/docs/mdx/include) is always enabled, also outside the preset. Add other remark plugins with: ```ts tab="Global Config" import { defineConfig } from 'fumadocs-mdx/config'; import { myPlugin } from './remark-plugin'; export default defineConfig({ mdxOptions: { remarkPlugins: [myPlugin], // You can also pass a function to control the order of remark plugins. remarkPlugins: (v) => [myPlugin, ...v], }, }); ``` ```ts tab="Collection Config" import { defineCollections, applyMdxPreset } from 'fumadocs-mdx/config'; import { myPlugin } from './remark-plugin'; export const blog = defineCollections({ type: 'doc', mdxOptions: applyMdxPreset({ remarkPlugins: [myPlugin], // You can also pass a function to control the order of remark plugins. remarkPlugins: (v) => [myPlugin, ...v], }), }); ``` ### Rehype Plugins [#rehype-plugins] These plugins are applied by default: - [Rehype Code](/docs/headless/mdx/rehype-code) - Syntax highlighting. - [Rehype TOC](/docs/headless/mdx/headings#rehype-toc) - Export table of contents. Same as remark plugins, you can pass an array or a function to add other rehype plugins. ```ts tab="Global Config" import { defineConfig } from 'fumadocs-mdx/config'; import { myPlugin } from './rehype-plugin'; export default defineConfig({ mdxOptions: { rehypePlugins: (v) => [myPlugin, ...v], }, }); ``` ```ts tab="Collection Config" import { defineCollections, applyMdxPreset } from 'fumadocs-mdx/config'; import { myPlugin } from './rehype-plugin'; export const blog = defineCollections({ type: 'doc', mdxOptions: applyMdxPreset({ rehypePlugins: (v) => [myPlugin, ...v], }), }); ``` ### Customize Built-in Plugins [#customize-built-in-plugins] Customize the options of built-in plugins like: ```ts tab="Global Config" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { rehypeCodeOptions: { // options }, remarkImageOptions: { // set image placeholder to `blur` (only effective on Next.js) placeholder: 'blur', }, remarkHeadingOptions: { // options }, }, }); ``` ```ts tab="Collection Config" import { defineCollections, applyMdxPreset } from 'fumadocs-mdx/config'; export const blog = defineCollections({ type: 'doc', mdxOptions: applyMdxPreset({ rehypeCodeOptions: { // options }, remarkImageOptions: { // options }, remarkHeadingOptions: { // options }, }), }); ``` ## Sätteri [#satteri] [Sätteri](https://github.com/bruits/satteri) is a compiler with its own plugin model. Install it: ```package-install @fumadocs/satteri satteri ``` Set `compiler: 'satteri'` on a [collection](/docs/mdx/collections#compiler). It reads the global `satteriOptions` instead of `mdxOptions`: ```ts title="source.config.ts" import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; import { remarkSteps } from '@fumadocs/satteri/remark-steps'; export const docs = defineDocs({ docs: { compiler: 'satteri', }, }); export default defineConfig({ satteriOptions: { // in place of remark plugins, and `hastPlugins` in place of rehype plugins mdastPlugins: [remarkSteps()], // built-in plugins take the same options as in `mdxOptions` rehypeCodeOptions: { themes: { light: 'github-light', dark: 'github-dark' }, }, }, }); ``` Remark and rehype plugins don't run on Sätteri. Fumadocs ports its plugins to `@fumadocs/satteri/`, like `@fumadocs/satteri/remark-steps`. Both plugin options accept an array or a function, like `mdxOptions`. The preset applies the same plugins as on unified. GFM and directives are parser `features` enabled by default, and `features: { math: true }` also renders [math](/docs/next/markdown/math) with KaTeX. The global `compiler` option only selects the compiler of MDX files outside collections. ## Source Map [#source-map] Source maps are disabled by default on unified, since generating them slows down compilation. To enable, install `source-map` and pass its generator to MDX options: ```npm npm i -D source-map ``` ```ts tab="Global Config" title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; import { SourceMapGenerator } from 'source-map'; export default defineConfig({ mdxOptions: { SourceMapGenerator, }, }); ``` ```ts tab="Collection Config" import { defineCollections, applyMdxPreset } from 'fumadocs-mdx/config'; import { SourceMapGenerator } from 'source-map'; export const blog = defineCollections({ type: 'doc', mdxOptions: applyMdxPreset({ SourceMapGenerator, }), }); ``` Errors thrown from compiled content can now be traced back to the original Markdown file. # Fumadocs MDX (the built-in content source): Performance URL: /docs/mdx/performance Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/performance.mdx The performance of Fumadocs MDX ## Overview [#overview] Fumadocs MDX is a bundler plugin, in other words, it has a higher performance bottleneck depending on the underlying bundler. For typical bundlers like Turbopack and Vite, it is enough for large docs sites with nearly 500+ MDX files, which is sufficient for almost all use cases. Since Fumadocs MDX works with your bundler, you can import any files including client components in your MDX files. This allows high flexibility and ensures everything is optimized by default. ### Development Server [#development-server] There's two categories: - **Lazy**: Bundlers like Vite, and runtime-side loaders like Node.js & Bun, can compile MDX files on-demand when a module is requested (e.g. when `await import()` is called), the dev server performance will not be significantly affected by the number of MDX files. However, ensure to enable [Lazy Loading](/docs/mdx/async), so that lazy compilation can take effect. - **Precompiled**: Webpack & Turbopack do not support lazy compilation on dev mode, all MDX files must be precompiled ahead of time. The dev server might be slow depending of the number of MDX files to precompile. While this is a bundler-level limitation, we recommend [Local Markdown](/docs/next/integrations/content/local-md) as an alternative if the slowness is a concern. It skips the bundler layer, MDX files are loaded & compiled on runtime. See the linked introduction for details. ### Image Optimization [#image-optimization] Fumadocs MDX resolves images into static imports with [Remark Image](/docs/headless/mdx/remark-image). Therefore, your images will be optimized automatically for your React framework (e.g. Next.js Image API). ```mdx ![Hello](./hello.png) or in public folder ![Hello](/hello.png) ``` Yields: ```mdx import HelloImage from './hello.png'; Hello ``` ![Banner](/banner.png) ### Production Build [#production-build] In a production build, the most consuming parts are usually TypeScript docgens (the TypeScript Compiler is slow without tsgo), and the trivial work with all MDX files summed up. Without cache, a huge amount of MDX files can cause extremely high memory usage during build. This is because: - After MDX files are compiled into JavaScript, bundlers also have to bundle the output JavaScript files. - Even the compilation time of each MDX file is trivial, it can be slow when summed up. For example, ~2500 files, assuming 25ms per file, cold build will take up to 62.5 seconds. The main solution is to make the compilation on-demand, such that content is only loaded when it's being requested. #### Local Markdown [#local-markdown] As suggested in the development server section, [Local Markdown](/docs/next/integrations/content/local-md) is a good alternative that runs purely on runtime, without extra compilation work. #### Remote Source [#remote-source] Create your custom content source with remoting content loading. If your content source doesn't need to pre-compile content files, it can process them on-demand with SSG which can **improve your build speed.** However, you cannot leverage build time optimizations (e.g. bundling). See [Custom Source](/docs/next/integrations/content/custom) for implementing custom sources. # Fumadocs MDX (the built-in content source): Generate Types URL: /docs/mdx/typegen Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/typegen.mdx Generate types without running dev/build server ### Overview [#overview] You can run `fumadocs-mdx` to generate types & entry files (the `.source` folder) of the collections defined in `source.config.ts`. Collections of the [Macro API](/docs/mdx/macro) need no generated files. Optionally, you can run it in post install to ensure types are generated when initializing the project. ```json title="package.json" { "scripts": { "postinstall": "fumadocs-mdx" } } ``` If your project uses a custom path for configuration file or output directory, you can provide them as command arguments: ```npm npx fumadocs-mdx "config-path" "output-dir" ``` - `config-path`: Fumadocs MDX config file, default to `source.config.ts`. - `output-dir`: Directory of generated files, default to `.source`. # Fumadocs MDX (the built-in content source): Workspace URL: /docs/mdx/workspace Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/mdx/workspace.mdx Use Fumadocs MDX in multiple workspace. ## Overview [#overview] **Workspace** in Fumadocs MDX, refers to an independent project with its own config and content. Fumadocs MDX Workspace is not limited to the traditional meaning of workspace in package managers. They do not need to have its own `package.json`, only a config file is needed. To define a workspace, add: ```ts title="source.config.ts" import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ workspaces: { 'my-workspace': { dir: 'my-workspace', config: await import('./my-workspace/source.config.ts'), }, }, }); ``` When writing content in a workspace, note that: - `cwd` refers to the **current workspace directory**. - configs will not inherit, workspaces are always independent. By running dev or build server, you should see collection entries from all workspaces to be generated. ### Accessing Collections [#accessing-collections] You can access the generated files of a workspace at `.source/{workspace}/*`. For example: ```ts title="lib/source.ts" import { docs } from 'collections/my-workspace/server'; ``` > The output location of root workspace is not changed. To integrate [multi-source](/docs/headless/source-api/source#multiple-sources) in Fumadocs: ```ts title="lib/source.ts" import { loader } from 'fumadocs-core/source'; import { docs } from 'collections/server'; import * as MyWorkspace from 'collections/my-workspace/server'; export const source = loader( { root: docs.toFumadocsSource(), 'my-workspace': MyWorkspace.docs.toFumadocsSource(), }, { baseUrl: '/docs', }, ); ``` ## When to Use [#when-to-use] In some setups, you might have multiple Fumadocs MDX configs with their own content directory. With workspaces, you can integrate them into one Fumadocs MDX config, and access all collections of each workspace. This is crucial for use cases like storing content across multiple repos, a simplified setup would be: - let your main docs repo be $A$, and other repos be $T_n$ - for each repo $T_n$: - $T_n$ has $A$ as a git submodule. - $T_n$ defines its own config `source.config.ts` and work independently. - when a commit is made to the content in $T_n$, it triggers a GitHub action (or CI), which creates a new deployment on $A$. - when a deployment is triggered on $A$: - Fumadocs MDX handles each $T_n$ as a workspace. - each workspace generates its own collection entries, e.g. `collections/{repo}/server`. - Fumadocs `loader()` integrate multiple sources into one. # Fumadocs (Framework Mode): Scalar Example URL: /docs/openapi Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/openapi/index.mdx View the Scalar Galaxy example OpenAPI schema. - [Get all planets get](/docs/openapi/planets/getAllData): It's easy to say you know them all, but do you really? Retrieve all the planets and check whether you missed one. - [Create a planet post](/docs/openapi/planets/createPlanet): Time to play god and create a new planet. What do you think? Ah, don't think too much. What could go wrong anyway? - [Get a planet get](/docs/openapi/planets/getPlanet): You'll better learn a little bit more about the planets. It might come in handy once space travel is available for everyone. - [Delete a planet delete](/docs/openapi/planets/deletePlanet): This endpoint was used to delete planets. Unfortunately, that caused a lot of trouble for planets with life. So, this endpoint is now deprecated and should not be used anymore. - [Update a planet put](/docs/openapi/planets/updatePlanet): Sometimes you make mistakes, that's fine. No worries, you can update all planets. - [Upload an image to a planet post](/docs/openapi/planets/uploadImage): Got a crazy good photo of a planet? Share it with the world! - [New Planet Webhook](/docs/openapi/planets/newplanet) - [Create a celestial body post](/docs/openapi/celestial-bodies/createCelestialBody): Stars, moons, comets, the occasional rogue asteroid — if it glows or drifts through the void, you can add it here. - [Create a user post](/docs/openapi/authentication/createUser): Time to create a user account, eh? - [Get a token post](/docs/openapi/authentication/getToken): Yeah, this is the boring security stuff. Just get your super secret token and move on. - [Get authenticated user get](/docs/openapi/authentication/getMe): Find yourself they say. That's what you can do here. # Fumadocs UI (the default theme of Fumadocs): Component Library URL: /docs/ui/component-library Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/component-library.mdx The underlying headless component library. ## Overview [#overview] Fumadocs UI maintains support for both [Base UI](https://base-ui.com) and [Radix UI](https://radix-ui.com/primitives), while it uses Base UI by default. The configuration may be different if you use Fumadocs CLI for customising components. ### Base UI [#base-ui] Base UI is the default component library. If you install manually, alias `fumadocs-ui` to the `@fumadocs/base-ui` package: ```json title="package.json" { "dependencies": { "fumadocs-ui": "npm:@fumadocs/base-ui@latest", // make sure Base UI is already installed "@base-ui/react": "..." } } ``` For Fumadocs CLI, this is the default `uiLibrary` value: ```json title="cli.json" { "uiLibrary": "base-ui" } ``` ### Radix UI [#radix-ui] You can opt-in to use Radix UI by installing the `fumadocs-ui` package directly: ```json title="package.json" { "dependencies": { "fumadocs-ui": "latest" } } ``` For Fumadocs CLI, configure it in your `cli.json` config: ```json title="cli.json" { "uiLibrary": "radix-ui" } ``` # Fumadocs UI (the default theme of Fumadocs): Accordion URL: /docs/ui/components/accordion Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/accordion.mdx Add Accordions to your documentation Install to your codebase: ```bash npx @fumadocs/cli@latest add accordion ``` ## Usage [#usage] Based on [Base UI Accordion](https://base-ui.com/react/components/accordion), useful for FAQ sections. > For the Radix UI package, this is based on [Radix UI Accordion](https://www.radix-ui.com/primitives/docs/components/accordion) instead. Use it in MDX files or as a normal React component. ```mdx tab="MDX" --- title: Hello World --- import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; My Content ``` ```tsx tab="React.js" import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; export default function Page() { return ( My Content ); } ``` ### Accordions [#accordions] ### AccordionsProps | Prop | Type | Description | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `render?` | `ComponentRenderFn> \| React.ReactElement> \| undefined` | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. | | `disabled?` | `boolean \| undefined` | Whether the component should ignore user interaction. Default: `false` | | `hiddenUntilFound?` | `boolean \| undefined` | Allows the browser's built-in page search to find and expand the panel contents. Overrides the `keepMounted` prop and uses `hidden="until-found"` to hide the element without removing it from the DOM. Default: `false` | | `keepMounted?` | `boolean \| undefined` | Whether to keep the element in the DOM while the panel is closed. This prop is ignored when `hiddenUntilFound` is used. Default: `false` | | `loopFocus?` | `boolean \| undefined` | **Deprecated.** Deprecated following the [APG guidance update](https://github.com/w3c/aria-practices/pull/3434) to remove roving focus. This prop no longer affects keyboard focus behavior. | | `multiple?` | `boolean \| undefined` | Whether multiple items can be open at the same time. Default: `false` | | `orientation?` | `Orientation \| undefined` | **Deprecated.** Deprecated following the [APG guidance update](https://github.com/w3c/aria-practices/pull/3434) to remove roving focus. This prop no longer affects keyboard focus behavior. Default: `'vertical'` | ### Accordion [#accordion] ### AccordionProps | Prop | Type | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `render?` | `ComponentRenderFn \| React.ReactElement> \| undefined` | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. | | `disabled?` | `boolean \| undefined` | Whether the component should ignore user interaction. Default: `false` | | `onOpenChange?` | `((open: boolean, eventDetails: AccordionItem.ChangeEventDetails) => void) \| undefined` | Event handler called when the panel is opened or closed. | | `value?` | `string \| undefined` | | ### Linking to Accordion [#linking-to-accordion] You can specify an `id` for accordion. The accordion will automatically open when the user is navigating to the page with the specified `id` in hash parameter. ```mdx My Content ``` > The value of accordion is same as title by default. When an id presents, it will be used as the value instead. # Fumadocs UI (the default theme of Fumadocs): Auto Type Table URL: /docs/ui/components/auto-type-table Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/auto-type-table.mdx Auto-generated type table ### AutoTypeTableExample | Prop | Type | Description | | ---------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `name` | `boolean \| null` | Markdown syntax like links, `code` are supported. See https://fumadocs.dev/docs/ui/components/type-table | | `fn` | `(name: string, allowNull?: boolean) => string` | | | `options?` | `Partial<{ a: unknown; }> \| undefined` | We love Shiki. ```ts console.log("Hello World, powered by Shiki"); ``` Default: `{ a: "test" }` | You cannot use this in a client component, instead, try the [build-time MDX integration](/docs/next/markdown/typescript#mdx-integration) instead. It generates a table for your docs based on TypeScript definitions. ## Usage [#usage] ```npm npm i fumadocs-typescript ``` Initialize the TypeScript compiler and add it as a MDX component. ```tsx title="components/mdx.tsx" import defaultComponents from 'fumadocs-ui/mdx'; import type { MDXComponents } from 'mdx/types'; import { createGenerator, createFileSystemGeneratorCache } from 'fumadocs-typescript'; import { AutoTypeTable, type AutoTypeTableProps } from 'fumadocs-typescript/ui'; const generator = createGenerator({ // set a cache, necessary for serverless platform like Vercel cache: createFileSystemGeneratorCache('.next/fumadocs-typescript'), }); export function getMDXComponents(components?: MDXComponents) { return { ...defaultComponents, // [!code ++] AutoTypeTable: (props: Partial) => ( ), ...components, } satisfies MDXComponents; } ``` You can now reference `` in your MDX content. See [TypeScript DocGen](/docs/next/markdown/typescript) for more usages. ### From File [#from-file] It accepts a `path` prop that points to a typescript file, and `name` for the exported type name. ```ts title="path/to/file.ts" export interface MyInterface { name: string; } ``` ```mdx title="content.mdx" ``` The path is relative to your project directory (`cwd`), because `AutoTypeTable` is a React Server Component, it cannot access build-time information like MDX file path. ### From Type [#from-type] You can specify the type to generate, without an actual TypeScript file. ```mdx title="content.mdx" ``` When a `path` is given, it shares the same context as the TypeScript file. ```ts title="file.ts" export type A = { hello: string }; ``` ```mdx title="content.mdx" ``` When `type` has multiple lines, the export statement and `name` prop are required. ```mdx title="content.mdx" ``` ### Functions [#functions] Notice that only object type is allowed. For functions, you should wrap them into an object instead. ```ts export interface MyInterface { myFn: (input: string) => void; } ``` ## TypeScript Compiler [#typescript-compiler] Under the hood, it uses the [Typescript Compiler API](https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API) to extract type information. Your `tsconfig.json` file in the current working directory will be loaded. You can change the compiler settings from [`createGenerator()`](/docs/next/markdown/typescript). ```ts import { createGenerator, createFileSystemGeneratorCache } from 'fumadocs-typescript'; const generator = createGenerator({ tsconfigPath: './tsconfig.json', // where to resolve relative paths (normally cwd) basePath: './', // other options... }); ``` ### File System [#file-system] It relies on the file system, hence, the page referencing this component must be built in **build time**. Rendering the component on serverless runtime may cause problems. ## References [#references] ### AutoTypeTableProps | Prop | Type | Description | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `path?` | `string \| undefined` | The path to source TypeScript file. | | `name?` | `string \| undefined` | Exported type name to generate from. | | `type?` | `string \| undefined` | Set the type to generate from. When used with `name`, it generates the type with `name` as export name. ```ts export const myName = MyType; ``` When `type` contains multiple lines, `export const` is not added. You need to export it manually, and specify the type name with `name`. ```tsx ``` | | `generator` | `{ generateDocumentation(file: { path: string; content?: string; }, name: string \| undefined, options?: GenerateOptions): Promise; generateTypeTable(props: BaseTypeTableProps, options?: GenerateTypeTableOptions): Promise; }` | | | `shiki?` | `ShikiOptions \| undefined` | **Deprecated.** | | `highlighter?` | `Highlighter \| undefined` | highlight code with your own highlighter when using default `renderMarkdown` & `renderType` | | `options?` | `GenerateTypeTableOptions \| undefined` | | | `renderMarkdown?` | `((md: string) => Promise) \| undefined` | | | `renderType?` | `((type: string) => Promise) \| undefined` | | # Fumadocs UI (the default theme of Fumadocs): Banner URL: /docs/ui/components/banner Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/banner.mdx Add a banner to your site Install to your codebase: ```bash npx @fumadocs/cli@latest add banner ``` ## Usage [#usage] Put the element at the top of your root layout, you can use it for displaying announcements. ```tsx import { Banner } from 'fumadocs-ui/components/banner'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {/* [!code ++] */} Hello World {children} ); } ``` ### Variant [#variant] Change the default variant. ```tsx import { Banner } from 'fumadocs-ui/components/banner'; Hello World; // customize colors Hello World ; ``` ### Change Layout [#change-layout] By default, the banner uses a `style` tag to modify Fumadocs layouts (e.g. reduce the sidebar height). You can disable it with: ```tsx import { Banner } from 'fumadocs-ui/components/banner'; Hello World; ``` ### Close [#close] To allow users to close the banner, give the banner an ID. ```tsx import { Banner } from 'fumadocs-ui/components/banner'; Hello World; ``` The state will be automatically persisted. # Fumadocs UI (the default theme of Fumadocs): Code Block URL: /docs/ui/components/codeblock Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/codeblock.mdx Displaying Shiki highlighted code blocks
```js title="config.js" import createMDX from 'fumadocs-mdx/config'; const withMDX = createMDX(); // [!code word:config] /** @type {import('next').NextConfig} */ const config = { // [!code highlight] reactStrictMode: true, // [!code highlight] }; // [!code highlight] export default withMDX(config); ```
Install to your codebase: ```bash npx @fumadocs/cli@latest add codeblock ``` This is a **MDX component** meant to be used with [Rehype Code](/docs/headless/mdx/rehype-code) to display highlighted codeblocks. You can refer to [Markdown](/docs/next/markdown#code-blocks) for the syntax of writing codeblocks. Supported features: - Copy button - Custom titles and icons > If you're looking for an equivalent with runtime syntax highlighting, see [Dynamic Code Block](/docs/ui/components/dynamic-codeblock). ## Usage [#usage] Wrap the pre element in ``, which acts as the wrapper of code block. ```tsx title="components/mdx.tsx" import defaultComponents from 'fumadocs-ui/mdx'; import type { MDXComponents } from 'mdx/types'; import { CodeBlock, Pre } from 'fumadocs-ui/components/codeblock'; export function getMDXComponents(components?: MDXComponents) { return { ...defaultComponents, // HTML `ref` attribute conflicts with `forwardRef` pre: ({ ref: _ref, ...props }) => (
{props.children}
{/* [!code highlight] */}
), ...components, } satisfies MDXComponents; } ``` ### Keep Background [#keep-background] Use the background color generated by Shiki. ```tsx import { Pre, CodeBlock } from 'fumadocs-ui/components/codeblock';
{props.children}
; ``` ### Icons [#icons] Specify a custom icon by passing an `icon` prop to `CodeBlock` component. By default, the icon will be injected by the custom Shiki transformer. ```js title="config.js" console.log('js'); ``` # Fumadocs UI (the default theme of Fumadocs): Code Block (Dynamic) URL: /docs/ui/components/dynamic-codeblock Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/dynamic-codeblock.mdx A codeblock that also highlights code ## Usage [#usage] ### Client Component [#client-component] ```tsx import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock'; export function MyComp() { const code = `console.log("Hello World")`; return ; } ``` Unlike the MDX [`CodeBlock`](/docs/ui/components/codeblock) component, this is a client component that can be used without MDX. It highlights the code with Shiki and use the default component to render it. Features: - using React.js 19 Suspense. - can be pre-rendered on server. - load languages and themes on browser lazily. #### Options [#options] ```tsx import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock'; ; ``` ### Server Component [#server-component] For a server component equivalent, you can use the RSC version: ```tsx import { ServerCodeBlock } from 'fumadocs-ui/components/codeblock.rsc'; ; ``` To highlight with your own highlighter, see [Highlighter](/docs/headless/utils/shiki#usage). # Fumadocs UI (the default theme of Fumadocs): Files URL: /docs/ui/components/files Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/files.mdx Display file structure in your documentation Install to your codebase: ```bash npx @fumadocs/cli@latest add files ``` ## Usage [#usage] Wrap file components in `Files`, you can use it in your MDX content, or as a normal React.js component. ```mdx title="content.mdx" import { File, Folder, Files } from 'fumadocs-ui/components/files'; ``` ### File [#file] ### FileProps | Prop | Type | Description | | ------- | ----------------- | ----------- | | `name` | `string` | | | `icon?` | `React.ReactNode` | | ### Folder [#folder] ### FolderProps | Prop | Type | Description | | -------------- | ---------------------- | --------------------------------------- | | `name` | `string` | | | `disabled?` | `boolean \| undefined` | | | `defaultOpen?` | `boolean \| undefined` | Open folder by default Default: `false` | ## Remark Plugin [#remark-plugin] [`remark-mdx-files`](/docs/headless/mdx/remark-mdx-files) is a remark plugin for additional features and syntax. ```ts tab="unified" title="source.config.ts" import { remarkMdxFiles } from 'fumadocs-core/mdx-plugins/remark-mdx-files'; import { defineConfig } from 'fumadocs-mdx/config'; export default defineConfig({ mdxOptions: { // [!code ++] remarkPlugins: [remarkMdxFiles], }, }); ``` ```ts tab="Sätteri" title="source.config.ts" import { remarkMdxFiles } from '@fumadocs/satteri/remark-mdx-files'; import { defineConfig, defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { compiler: 'satteri', }, }); export default defineConfig({ satteriOptions: { // [!code ++] mdastPlugins: [remarkMdxFiles()], }, }); ``` ### CodeBlock Syntax [#codeblock-syntax] It will convert `files` codeblocks into `` component, like: ````md title="content.md" ```files project ├── src │ ├── index.js │ └── utils │ └── helper.js ├── package.json ``` ```` ### `` [#auto-files] Generate `` component from glob. ```mdx title="content.mdx" ``` Do not pass untrusted values to `dir`, it can list files in any directory on your machine. # Fumadocs UI (the default theme of Fumadocs): GitHub Info URL: /docs/ui/components/github-info Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/github-info.mdx Display your GitHub repository information Install to your codebase: ```bash npx @fumadocs/cli@latest add github-info ``` ## Usage [#usage] ```tsx import { GithubInfo } from 'fumadocs-ui/components/github-info'; export function MyComp() { return ( ); } ``` It's recommended to add it to your docs layout with `links` option: ```tsx title="app/docs/layout.tsx" import { DocsLayout, type DocsLayoutProps } from 'fumadocs-ui/layouts/notebook'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import { GithubInfo } from 'fumadocs-ui/components/github-info'; function docsOptions(): DocsLayoutProps { return { ...baseOptions(), tree: source.getPageTree(), links: [ { type: 'custom', children: , }, ], }; } export default function Layout({ children }: { children: React.ReactNode }) { return {children}; } ``` # Fumadocs UI (the default theme of Fumadocs): Graph View URL: /docs/ui/components/graph-view Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/graph-view.mdx A graph of all pages. ## Installation [#installation] You can install this from CLI: ```npm npx @fumadocs/cli add graph-view ``` For TypeScript, also install its types: ```npm npm i -D @types/d3-force ``` Enable `extractLinkReferences` on your content source. ```ts title="source.config.ts" import { defineDocs } from 'fumadocs-mdx/config'; export const docs = defineDocs({ docs: { postprocess: { // [!code ++] extractLinkReferences: true, }, }, }); ``` ## Usage [#usage] You can use it in MDX files or the layout components (e.g. in `page.tsx`): ```tsx title="page.tsx" import { GraphView } from '@/components/graph-view'; import { buildGraph } from '@/lib/build-graph'; export function PageBody() { return (
{/* ... */}
); } ``` # Fumadocs UI (the default theme of Fumadocs): Zoomable Image URL: /docs/ui/components/image-zoom Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/image-zoom.mdx Allow zoom-in images in your documentation Install to your codebase: ```bash npx @fumadocs/cli@latest add image-zoom ``` ## Usage [#usage] Replace `img` with `ImageZoom` in your MDX components. ```tsx title="components/mdx.tsx" import { ImageZoom } from 'fumadocs-ui/components/image-zoom'; import defaultComponents from 'fumadocs-ui/mdx'; import type { MDXComponents } from 'mdx/types'; export function getMDXComponents(components?: MDXComponents) { return { ...defaultComponents, // [!code ++] img: (props) => , ...components, } satisfies MDXComponents; } ``` Now image zoom will be automatically enabled on all images. ```mdx ![Test](/banner.png) ``` ### Image Optimization [#image-optimization] On Next.js, a default [`sizes` property](https://nextjs.org/docs/app/api-reference/components/image#sizes) will be defined for `` component if not specified. ## Lightbox [#lightbox] Zoomable images inside `` open in one viewer, browse them with arrow keys, swipes or the side buttons.
Wrap your page content to browse every image of the page: ```tsx title="app/docs/[[...slug]]/page.tsx" import { Lightbox } from 'fumadocs-ui/components/image-zoom'; {/* [!code ++] */} {/* [!code ++] */} ; ``` ### Caption [#caption] The image title is shown as caption. ```mdx ![Notebook Layout](/notebook.png 'Tab mode: navbar') ``` Pass `caption` for rich content like links. ```tsx See
Notebook Layout } /> ``` ### Gallery [#gallery] To browse a set of images on its own, wrap them in another ``, for example as a grid: ```mdx
![Light Mode](/light.png) ![Dark Mode](/dark.png)
``` # Fumadocs UI (the default theme of Fumadocs): Components URL: /docs/ui/components Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/index.mdx Additional components to improve your docs ## Overview [#overview] Additional components that you can use: - [Accordion](/docs/ui/components/accordion): Add Accordions to your documentation - [Auto Type Table](/docs/ui/components/auto-type-table): Auto-generated type table - [Banner](/docs/ui/components/banner): Add a banner to your site - [Code Block](/docs/ui/components/codeblock): Displaying Shiki highlighted code blocks - [Code Block (Dynamic)](/docs/ui/components/dynamic-codeblock): A codeblock that also highlights code - [Files](/docs/ui/components/files): Display file structure in your documentation - [GitHub Info](/docs/ui/components/github-info): Display your GitHub repository information - [Graph View](/docs/ui/components/graph-view): A graph of all pages. - [Zoomable Image](/docs/ui/components/image-zoom): Allow zoom-in images in your documentation - [Inline TOC](/docs/ui/components/inline-toc): Add Inline TOC into your documentation - [Steps](/docs/ui/components/steps): Adding steps to your docs - [Tabs](/docs/ui/components/tabs): A Tabs component built with Base UI, with additional features such as persistent and shared value. - [Type Table](/docs/ui/components/type-table): A table for documenting types ### MDX Components [#mdx-components] The default MDX components include Cards, Callouts, Code Blocks and Headings. ```ts import defaultMdxComponents from 'fumadocs-ui/mdx'; ``` ### Relative Link [#relative-link] Server Component only. To support links with relative file path in `href`, override the default `a` component with: ```tsx title="app/docs/[[...slug]]/page.tsx" import { createRelativeLink } from 'fumadocs-ui/mdx'; import { source } from '@/lib/source'; import { getMDXComponents } from '@/components/mdx'; const page = source.getPage(['...']); return ( ); ``` On Astro, pass it to ``, which renders it like Astro MDX: ```astro title="src/pages/docs/[...slug].astro" ``` ```mdx [My Link](./file.mdx) ``` Example: [`../../(integrations)/feedback.mdx`](<../../(integrations)/feedback.mdx>) # Fumadocs UI (the default theme of Fumadocs): Inline TOC URL: /docs/ui/components/inline-toc Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/inline-toc.mdx Add Inline TOC into your documentation Install to your codebase: ```bash npx @fumadocs/cli@latest add inline-toc ``` ## Usage [#usage] You can use it in your MDX content. In an MDX file of Fumadocs MDX, the `toc` export is a function of the props of the page: ```mdx title="content.mdx" import { InlineTOC } from 'fumadocs-ui/components/inline-toc'; Table of Contents ``` Or adding it to every page. ```tsx title="page.tsx" import { DocsPage } from 'fumadocs-ui/layouts/docs/page'; import { InlineTOC } from 'fumadocs-ui/components/inline-toc'; export default function Page() { // ... return ( {/* [!code ++] */} Table of Contents ); } ``` ## Reference [#reference] ### InlineTOCProps | Prop | Type | Description | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `render?` | `ComponentRenderFn \| React.ReactElement> \| undefined` | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. | | `open?` | `boolean \| undefined` | Whether the collapsible panel is currently open. To render an uncontrolled collapsible, use the `defaultOpen` prop instead. | | `defaultOpen?` | `boolean \| undefined` | Whether the collapsible panel is initially open. To render a controlled collapsible, use the `open` prop instead. Default: `false` | | `onOpenChange?` | `((open: boolean, eventDetails: CollapsibleRootChangeEventDetails) => void) \| undefined` | Event handler called when the panel is opened or closed. | | `disabled?` | `boolean \| undefined` | Whether the component should ignore user interaction. Default: `false` | | `items` | `TOCItemType[]` | | # Fumadocs UI (the default theme of Fumadocs): Steps URL: /docs/ui/components/steps Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/steps.mdx Adding steps to your docs Install to your codebase: ```bash npx @fumadocs/cli@latest add steps ``` ## Usage [#usage] Put your steps into the `Steps` container. ```mdx title="content.mdx" import { Step, Steps } from 'fumadocs-ui/components/steps'; ### Hello World ### Hello World ``` ### Without imports [#without-imports] You can use the Tailwind CSS utilities without importing it. ```mdx
``` It supports adding step styles to only headings with arbitrary variants. ```mdx
### Hello World
```
### Hello World [#hello-world] Rendered without the `` component.
# Fumadocs UI (the default theme of Fumadocs): Tabs URL: /docs/ui/components/tabs Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/tabs.mdx A Tabs component built with Base UI, with additional features such as persistent and shared value. Install to your codebase: ```bash npx @fumadocs/cli@latest add tabs ``` ## Usage [#usage] Add MDX components. ```tsx title="components/mdx.tsx" import defaultMdxComponents from 'fumadocs-ui/mdx'; import * as TabsComponents from 'fumadocs-ui/components/tabs'; import type { MDXComponents } from 'mdx/types'; export function getMDXComponents(components?: MDXComponents) { return { ...defaultMdxComponents, ...TabsComponents, // [!code ++] ...components, } satisfies MDXComponents; } ``` And use it in your MDX content: ```mdx title="content.mdx" Javascript is weird Rust is fast ``` Javascript is weird Rust is fast ### Without `value` [#without-value] Without a `value`, it detects from the children index. Note that it might cause errors on re-renders, it's not encouraged if the tabs might change. ```mdx import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; Javascript is weird Rust is fast ``` Javascript is weird Rust is fast ### Shared Value [#shared-value] By passing an `groupId` property, you can share a value across all tabs with the same id. ```mdx Javascript is weird Rust is fast ``` ### Persistent [#persistent] When `groupId` is specified, their value will be temporarily stored in `sessionStorage`. To persist the value, you can specify a `persist` prop. The value will be stored in `localStorage`, with its group ID as storage key. ```mdx Javascript is weird Rust is fast ``` ### Default Value [#default-value] Set a default value by passing `defaultIndex`. ```mdx Javascript is weird Rust is fast ``` ### Link to Tab [#link-to-tab] Use HTML `id` attribute to link to a specific tab. ```mdx Javascript is weird Rust is fast `Hello World` ``` You can add the hash `#tab-cpp` to your URL and reload, the C++ tab will be activated. Javascript is weird Rust is fast `Hello World` Additionally, the `updateAnchor` property can be set to `true` in the `Tabs` component to automatically update the URL hash whenever time a new tab is selected: ```mdx Javascript is weird Rust is fast `Hello World` ``` Hello! World! ## Advanced Usage [#advanced-usage] Use it in the primitive way: ```mdx npm Hello World ``` npm npm Hello World # Fumadocs UI (the default theme of Fumadocs): Type Table URL: /docs/ui/components/type-table Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/components/type-table.mdx A table for documenting types Install to your codebase: ```bash npx @fumadocs/cli@latest add type-table ``` ## Usage [#usage] It accepts a `type` property. ```mdx import { TypeTable } from 'fumadocs-ui/components/type-table'; ``` ## References [#references] ### Type Table [#type-table] ### TypeTableProps | Prop | Type | Description | | ------ | -------------------------- | ----------- | | `type` | `Record` | | ### Object Type [#object-type] ### ObjectTypeProps | Prop | Type | Description | | ---------------------- | ------------------------------ | ---------------------------------------------------- | | `description?` | `React.ReactNode` | Additional description of the field | | `type` | `React.ReactNode` | type signature (short) | | `typeDescription?` | `React.ReactNode` | type signature (full) | | `typeDescriptionLink?` | `string \| undefined` | Optional `href` for the type | | `default?` | `React.ReactNode` | | | `required?` | `boolean \| undefined` | | | `deprecated?` | `boolean \| undefined` | | | `parameters?` | `ParameterNode[] \| undefined` | a list of parameters info if the type is a function. | | `returns?` | `React.ReactNode` | | # Fumadocs UI (the default theme of Fumadocs): Overview URL: /docs/ui Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/index.mdx The default theme of Fumadocs **Fumadocs UI** offers a beautifully designed theme for documentation sites. It is bundled with many interactive components & layouts for docs sites, allowing low maintenance cost of code while receiving regular UI improvements. You can also use [Fumadocs CLI](/docs/cli) to install the components locally and have full control. ## Learn More [#learn-more] - [Component Library](/docs/ui/component-library): The underlying headless component library. - [Themes](/docs/ui/theme): Add Theme to Fumadocs UI - [Search UI](/docs/ui/search): The UI for document search - [Translations](/docs/ui/translations): Adding Translations to UI - [Components](/docs/ui/components): Additional components to improve your docs - [Layouts](/docs/ui/layouts): A list of layout components. # Fumadocs UI (the default theme of Fumadocs): Docs Layout URL: /docs/ui/layouts/docs Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/docs.mdx The layout of documentation The layout of documentation pages, it includes a sidebar and **mobile-only** navbar/header. For advanced customization that supported options cannot suffice, install via Fumadocs CLI: ```bash npx @fumadocs/cli@latest customize ``` ## Usage [#usage] Pass your page tree to the component. ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import { baseOptions } from '@/lib/layout.shared'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` See detailed docs for [`links`](/docs/ui/layouts/links) and [`nav`](/docs/ui/layouts/nav) options. ### References [#references] | Prop | Type | Description | | ----------------- | ----------------------------------------------------------- | ----------------- | | `githubUrl?` | `string \| undefined` | GitHub url | | `links?` | `LinkItemType[] \| undefined` | | | `nav?` | `NavOptions \| undefined` | navigation config | | `themeSwitch?` | `ThemeSwitchOptions \| undefined` | | | `searchToggle?` | `SearchToggleOptions \| undefined` | | | `i18n?` | `boolean \| I18nConfig \| undefined` | **Deprecated.** | | `tree` | `Root` | | | `sidebar?` | `SidebarOptions \| undefined` | | | `tabMode?` | `"auto" \| "top" \| undefined` | | | `tabs?` | `false \| LayoutTab[] \| GetLayoutTabsOptions \| undefined` | | | `containerProps?` | `React.HTMLAttributes \| undefined` | | | `aiChat?` | `AIChatOptions \| undefined` | | | `slots?` | `Partial \| undefined` | | ## Sidebar [#sidebar] ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; ; ``` ### Sidebar Items [#sidebar-items] Customize sidebar navigation links.
![Sidebar](/docs/sidebar.png)
Sidebar items are rendered from the page tree you passed to ``. For page tree from [`loader()`](/docs/headless/source-api), it generates the tree from your file structure, see [available patterns](/docs/next/page-conventions). ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` You may hardcode it too: ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ### Layout Tabs (Dropdown) [#layout-tabs] Layout Tabs are folders with tab-like behaviours, only the content of opened tab will be visible.
![Layout Tabs](/docs/sidebar-tabs.png)
By default, the tab trigger will be displayed as a **Dropdown** component (hidden unless one of its items is active). Tabs are generated from the page tree, you can mark folders as [Root Folders](/docs/next/page-conventions#root-folder) by creating a `meta.json` file in the folder: ```json title="content/docs/my-folder/meta.json" { "title": "Name of Folder", "description": "The description of root folder (optional)", "root": true } ``` Or specify them explicitly: ```tsx title="/app/docs/layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; ; ``` Set it to `false` to disable: ```tsx import { DocsLayout } from 'fumadocs-ui/layouts/docs'; ; ``` You can specify a `banner` to the [Docs Layout](/docs/ui/layouts/docs) component. ```tsx import { DocsLayout, type DocsLayoutProps } from 'fumadocs-ui/layouts/docs'; import type { ReactNode } from 'react'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; export default function Layout({ children }: { children: ReactNode }) { return ( Hello World
, }} > {children} ); } ``` #### Decoration [#decoration] Change the icon/styles of layout tabs. ```tsx import { DocsLayout } from 'fumadocs-ui/layouts/docs'; ({ ...option, icon: , }), }} />; ``` ### Tabs Groups [#tabs-groups] Tabs are grouped by [root type](/docs/next/page-conventions#root-type), with a dropdown for each root folder on the current page's path. On `v2/framework/quickstart.mdx`, the sidebar shows a dropdown for the version and another for the section:
![Tabs Groups](/docs/sidebar-tabs-groups.png)
Selecting an option navigates to the same page in that root folder, or its index page when the page doesn't exist there. See [Versioning](/docs/next/navigation#versioning) for a complete example. ### Sidebar Components [#sidebar-components] You can replace certain components for rendering page tree. ```tsx tab="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import { SidebarSeparator } from './layout.client'; ; ``` ```tsx tab="layout.client.tsx" 'use client'; import * as Base from 'fumadocs-ui/components/sidebar/base'; export function SidebarSeparator({ className, style, children, ...props }: ComponentProps<'p'>) { const depth = Base.useFolderDepth(); return ( {children} ); } ``` ### References [#references-1] ### SidebarProps | Prop | Type | Description | | ------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `defaultOpenLevel?` | `number \| undefined` | Open folders by default if their level is lower or equal to a specific level (Starting from 1) Default: `0` | | `prefetch?` | `boolean \| undefined` | Prefetch links, default behaviour depends on your React.js framework. | | `components?` | `Partial \| undefined` | | | `banner?` | `React.ReactNode` | | | `footer?` | `React.ReactNode` | | | `collapsible?` | `boolean \| undefined` | Support collapsing the sidebar on desktop mode Default: `true` | | `enabled?` | `boolean \| undefined` | | | `component?` | `React.ReactNode` | **Deprecated.** | | `tabMode?` | `"auto" \| "top" \| undefined` | **Deprecated.** | | `tabs?` | `false \| LayoutTab[] \| GetLayoutTabsOptions \| undefined` | **Deprecated.** | ## AI Chat [#ai-chat] Pass your chat panel to `aiChat` with its open state, the layout places it beside the page on wide screens, and floats it over the page on smaller ones. ```tsx , trigger: true }} /> ``` The layout has no Ask AI button of its own: `trigger` adds a floating one. See [Ask AI](/docs/next/integrations/llms#ask-ai) for a pre-built chat. ## Advanced [#advanced] ### Prefetching [#prefetching] Fumadocs use the `` component of your React framework, and keep their default prefetch behaviours. On Vercel, prefetch requests may cause a higher usage of serverless functions and Data Cache. It can also hit the limits of some other hosting platforms. You can disable prefetching to reduce the amount of prefetch requests, or enable explicitly: ```tsx import { DocsLayout } from 'fumadocs-ui/layouts/docs'; ; ``` ### The Layout System [#the-layout-system] Handling layout is challenging, Fumadocs UI needed an approach that is: - **Composable:** Layout components should manage their position and size effortlessly, ideally in place. - **Flexible:** The system should avoid reliance on fixed values or heights, enabling seamless integration of external components, such as AI chat interfaces. - **Cohesive:** Components should respond to changes in others, for instance, by animating sidebar collapses. - **Predictable:** Layout properties should remain centralized, allowing the final result to be readily anticipated from the source code. - **Compatible:** The solution should work on older browsers by leveraging only Baseline Widely Available CSS features. Fumadocs UI does this with a grid system: ```css #nd-docs-layout { grid-template: 'sidebar header toc' 'sidebar toc-popover toc' 'sidebar main toc' 1fr / minmax(var(--fd-sidebar-col), 1fr) minmax(0, var(--fd-page-col)) minmax(min-content, 1fr); --fd-docs-row-1: var(--fd-banner-height, 0px); --fd-docs-row-2: calc(var(--fd-docs-row-1) + var(--fd-header-height)); --fd-docs-row-3: calc(var(--fd-docs-row-2) + var(--fd-toc-popover-height)); --fd-sidebar-col: var(--fd-sidebar-width); --fd-page-col: calc( var(--fd-layout-width, 97rem) - var(--fd-sidebar-width) - var(--fd-toc-width) ); --fd-sidebar-width: 0px; --fd-toc-width: 0px; --fd-header-height: 0px; --fd-toc-popover-height: 0px; } ``` - The layout container uses grid layout, `grid-template` is set to produce predictable result. - `--fd-docs-row-*` define the top offset of each row, allowing elements with `position: sticky` to hook a correct top offset. - `--fd-*-width` and `--fd-*-height` are set by layout components using CSS, they are essential to maintain the grid structure, or calculating `--fd-docs-row-*`. - `--fd-*-col` are dynamic values, updated as state changes (e.g. `--fd-sidebar-col` becomes `0px` when the sidebar is collapsed). Both default and the notebook layout utilize this system. # Fumadocs UI (the default theme of Fumadocs): Flux Layout URL: /docs/ui/layouts/flux Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/flux.mdx An aggressively minimal layout for docs A docs layout that impractically minimal & clean, originally made for experimental purpose. For advanced customization that supported options cannot suffice, install via Fumadocs CLI: ```bash npx @fumadocs/cli@latest customize ``` ## Usage [#usage] Enable the Flux layout with `fumadocs-ui/layouts/flux`. ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/flux'; // [!code highlight] import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` Make sure to update your page import too: ```tsx title="page.tsx" import { ... } from 'fumadocs-ui/layouts/docs/page'; // [!code --] import { ... } from 'fumadocs-ui/layouts/flux/page'; // [!code ++] ``` - It is best to be paired with [static/local search](/docs/next/search/orama#static), the navigation is more efficient using document search. - It prioritizes subjective aesthetics over user experience. - It is opinionated, use Fumadocs CLI for customization instead. ## Configurations [#configurations] The options are inherited from [Docs Layout](/docs/ui/layouts/docs), with minor differences: - Flux layout is a client component, you cannot pass unserializable props from a server component. - A `renderNavigationPanel` prop to customize the bottom navigation panel. - There is no `tocPopover` options. # Fumadocs UI (the default theme of Fumadocs): Glass Layout URL: /docs/ui/layouts/glass Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/glass.mdx A docs layout with a floating, translucent sidebar and header A docs layout built around floating, translucent (glass-like) panels: the sidebar and header sit on top of the content as rounded, blurred surfaces rather than fixed columns. For advanced customization that supported options cannot suffice, install via Fumadocs CLI: ```bash npx @fumadocs/cli@latest customize ``` ## Usage [#usage] Enable the Glass layout with `fumadocs-ui/layouts/glass`. ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/glass'; // [!code highlight] import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` Make sure to update your page import too: ```tsx title="page.tsx" import { ... } from 'fumadocs-ui/layouts/docs/page'; // [!code --] import { ... } from 'fumadocs-ui/layouts/glass/page'; // [!code ++] ``` ### Styles [#styles] Unlike other layouts, Glass layout styles are **not** bundled into the CSS preset, so you don't pay for them unless you use the layout. Import them in your Tailwind CSS file: ```css title="Tailwind CSS" @import 'tailwindcss'; /* [!code ++] */ @import 'fumadocs-ui/css/generated/glass.css'; @import 'fumadocs-ui/css/neutral.css'; @import 'fumadocs-ui/css/preset.css'; ``` - Glass layout is a **client component**, you cannot pass unserializable props from a server component. - It is opinionated: the sidebar and header are more fixed than the default layout, use Fumadocs CLI or the `slots` option for customization. ## Configurations [#configurations] The options are inherited from [Docs Layout](/docs/ui/layouts/docs), with minor differences: - there is no `sidebar` option, Glass layout is more opinionated than the default one. - additional options (see below). ### Layout Tabs [#layout-tabs] Configure [Layout Tabs](/docs/ui/layouts/docs#layout-tabs) with the `tabs` prop, see the linked docs for how to add them. Tabs are shown as a dropdown in the sidebar. ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/glass'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ### AI Chat [#ai-chat] The floating header can render an **Ask AI** button. Pass an `aiChat` object with the open state and a change handler to control your AI search dialog, the layout places your chat `panel` beside the page on wide screens, and floats it over the page on smaller ones. ```tsx title="layout.tsx" 'use client'; import { DocsLayout } from 'fumadocs-ui/layouts/glass'; import { useState } from 'react'; export function Layout({ children }) { const [open, setOpen] = useState(false); return ( }} // [!code ++] // ... > {children} ); } ``` ### Slots [#slots] Like other layouts, Glass layout exposes a `slots` option to override the built-in `header`, `sidebar`, and `sidebarDrawer` (mobile) components, in addition to the shared slots (`navTitle`, `themeSwitch`, `searchTrigger`, `languageSelect`). ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/glass'; ; ``` # Fumadocs UI (the default theme of Fumadocs): Home Layout URL: /docs/ui/layouts/home-layout Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/home-layout.mdx Shared layout for other pages A layout with only navbar. For advanced customization that supported options cannot suffice, install via Fumadocs CLI: ```bash npx @fumadocs/cli@latest customize ``` ## Usage [#usage] Add a navbar and search dialog across other pages. ```tsx title="/app/(home)/layout.tsx" import { HomeLayout } from 'fumadocs-ui/layouts/home'; import { baseOptions } from '@/lib/layout.shared'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return {children}; } ``` See detailed docs for [`links`](/docs/ui/layouts/links) and [`nav`](/docs/ui/layouts/nav) options. # Fumadocs UI (the default theme of Fumadocs): Layouts URL: /docs/ui/layouts Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/index.mdx A list of layout components. ## Overview [#overview] Fumadocs UI provides essential layouts to display content. - [Layout Links](/docs/ui/layouts/links): Navigation configurations on all layouts. - [Navbar](/docs/ui/layouts/nav): Navbar/header configurations. - [Docs Layout](/docs/ui/layouts/docs): The layout of documentation - [Flux Layout](/docs/ui/layouts/flux): An aggressively minimal layout for docs - [Glass Layout](/docs/ui/layouts/glass): A docs layout with a floating, translucent sidebar and header - [Home Layout](/docs/ui/layouts/home-layout): Shared layout for other pages - [Notebook Layout](/docs/ui/layouts/notebook): A compact version of Docs Layout - [Spacious Layout](/docs/ui/layouts/spacious): A less compact version of Docs Layout - [Docs Page](/docs/ui/layouts/page): A page in your documentation - [Root Provider](/docs/ui/layouts/root-provider): The context provider of Fumadocs UI. ### Configurations [#configurations] Each layout supports a shared set of options. It is recommended to store these options into a file, and pass them to the layouts. ```tsx tab="Shared Options" title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { nav: { title: 'My App', }, }; } ``` ```tsx tab="Docs Layout" title="app/docs/layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ```tsx tab="Home Layout" title="app/(home)/layout.tsx" import { HomeLayout } from 'fumadocs-ui/layouts/home'; import { baseOptions } from '@/lib/layout.shared'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` See detailed docs for [`links`](/docs/ui/layouts/links) and [`nav`](/docs/ui/layouts/nav) options. ### BaseLayoutProps | Prop | Type | Description | | --------------- | -------------------------------------------- | ----------------- | | `githubUrl?` | `string \| undefined` | GitHub url | | `links?` | `LinkItemType[] \| undefined` | | | `nav?` | `NavOptions \| undefined` | navigation config | | `slots?` | `Partial \| undefined` | | | `children?` | `ReactNode` | | | `themeSwitch?` | `ThemeSwitchOptions \| undefined` | | | `searchToggle?` | `SearchToggleOptions \| undefined` | | | `i18n?` | `boolean \| I18nConfig \| undefined` | **Deprecated.** | # Fumadocs UI (the default theme of Fumadocs): Layout Links URL: /docs/ui/layouts/links Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/links.mdx Navigation configurations on all layouts. ## Overview [#overview] Fumadocs allows adding navigation links to your layouts with a `links` prop, like linking to your "showcase" page.
<>![Nav](/docs/nav-layout-home.png) <>![Nav](/docs/nav-layout-docs.png)
```tsx tab="All" title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { links: [], // [!code ++] }; } ``` ```tsx tab="Docs Layout" title="app/docs/layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ```tsx tab="Home Layout" title="app/(home)/layout.tsx" import { HomeLayout } from 'fumadocs-ui/layouts/home'; import { baseOptions } from '@/lib/layout.shared'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` You can see all supported items below: ### Link Item [#link-item] A link to navigate to a URL/href, can be external. ```tsx title="lib/layout.shared.tsx" import { BookIcon } from 'lucide-react'; import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { links: [ { icon: , text: 'Blog', url: '/blog', // secondary items will be displayed differently on navbar secondary: false, }, ], }; } ``` #### Active Mode [#active-mode] The conditions to be marked as active. | Mode | Description | | ------------ | ----------------------------------------------------------- | | `url` | When browsing the specified url | | `nested-url` | When browsing the url and its child pages like `/blog/post` | | `none` | Never be active | ```tsx title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { links: [ { text: 'Blog', url: '/blog', active: 'nested-url', }, ], }; } ``` ### Icon Item [#icon-item] Same as link item, but is shown as an icon button. Icon items are secondary by default. ```tsx title="lib/layout.shared.tsx" import { BookIcon } from 'lucide-react'; import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { links: [ { type: 'icon', label: 'Visit Blog', // `aria-label` icon: , text: 'Blog', url: '/blog', }, ], }; } ``` ### Custom Item [#custom-item] Display a custom component. ```tsx title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { links: [ { type: 'custom', children: , secondary: true, }, ], }; } ``` ### GitHub URL [#github-url] There's also a shortcut for adding GitHub repository link item. ```tsx twoslash title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { githubUrl: 'https://github.com', }; } ``` ### Normal Menu [#normal-menu] A menu containing multiple link items. ```tsx title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { links: [ { type: 'menu', text: 'Guide', items: [ { text: 'Getting Started', description: 'Learn to use Fumadocs', url: '/docs', }, ], }, ], }; } ``` ### Navigation Menu [#navigation-menu] In Home Layout, you can add navigation menu (fully animated) to the navbar. ![Nav](/docs/nav-layout-menu.png) ```tsx title="app/(home)/layout.tsx" import { baseOptions } from '@/lib/layout.shared'; import type { ReactNode } from 'react'; import { HomeLayout } from 'fumadocs-ui/layouts/home'; import { NavbarMenu, NavbarMenuContent, NavbarMenuLink, NavbarMenuTrigger, } from 'fumadocs-ui/layouts/home/navbar'; export default function Layout({ children }: { children: ReactNode }) { return ( Documentation Hello World ), }, // other items ]} > {children} ); } ``` # Fumadocs UI (the default theme of Fumadocs): Navbar URL: /docs/ui/layouts/nav Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/nav.mdx Navbar/header configurations. ## Configurations [#configurations] Options for navbar (header). | Prop | Type | Description | | ------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------ | | `enabled?` | `boolean \| undefined` | | | `title?` | `React.FC, HTMLAnchorElement>> \| React.ReactNode` | | | `url?` | `string \| undefined` | Redirect url of title Default: `'/'` | | `transparentMode?` | `"always" \| "none" \| "top" \| undefined` | Use transparent background Default: `none` | | `component?` | `React.ReactNode` | **Deprecated.** | ### Transparent Mode [#transparent-mode] To make the navbar background transparent, you can configure transparent mode. ```tsx tab="All" title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { nav: { title: 'My App', // [!code ++] transparentMode: 'top', }, }; } ``` ```tsx tab="Home Layout" import { baseOptions } from '@/lib/layout.shared'; import { HomeLayout } from 'fumadocs-ui/layouts/home'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { const base = baseOptions(); return ( {children} ); } ``` ```tsx tab="Docs Layout" import { baseOptions } from '@/lib/layout.shared'; import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { const base = baseOptions(); return ( {children} ); } ``` | Mode | Description | | -------- | ---------------------------------------- | | `always` | Always use a transparent background | | `top` | When at the top of page | | `none` | Disable transparent background (default) | ### Replace Navbar [#replace-navbar] To replace the navbar in different layouts, set `nav.component` to your own component. ```tsx tab="All" title="lib/layout.shared.tsx" import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; export function baseOptions(): BaseLayoutProps { return { nav: { // [!code ++] component: , }, }; } ``` ```tsx tab="Home Layout" import { baseOptions } from '@/lib/layout.shared'; import { HomeLayout } from 'fumadocs-ui/layouts/home'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { const base = baseOptions(); return ( , }} > {children} ); } ``` ```tsx tab="Docs Layout" import { baseOptions } from '@/lib/layout.shared'; import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { const base = baseOptions(); return ( , }} > {children} ); } ``` Fumadocs uses **CSS Variables** to share the size of layout components, and fit each layout component into appropriate position. You need to override `--fd-nav-height` to the exact height of your custom navbar, this can be done with a CSS stylesheet (e.g. in `global.css`): ```css :root { --fd-nav-height: 80px !important; } ``` # Fumadocs UI (the default theme of Fumadocs): Notebook Layout URL: /docs/ui/layouts/notebook Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/notebook.mdx A compact version of Docs Layout A compact version of [``](/docs/ui/layouts/docs). For advanced customization that supported options cannot suffice, install via Fumadocs CLI: ```bash npx @fumadocs/cli@latest customize ``` ## Usage [#usage] Enable the notebook layout with `fumadocs-ui/layouts/notebook`. ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/notebook'; // [!code highlight] import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` Make sure to update your page import too: ```tsx title="page.tsx" import { ... } from 'fumadocs-ui/layouts/docs/page'; // [!code --] import { ... } from 'fumadocs-ui/layouts/notebook/page'; // [!code ++] ``` ## Configurations [#configurations] The options are inherited from [Docs Layout](/docs/ui/layouts/docs), with minor differences: - sidebar/navbar cannot be replaced, Notebook layout is more opinionated than the default one. - additional options (see below). ### Tab Mode [#tab-mode] Configure the style of [Layout Tabs](/docs/ui/layouts/docs#layout-tabs), see the linked docs for how to add layout tabs. ![Notebook](/docs/notebook-tab-mode.png) ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/notebook'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ### Nav Mode [#nav-mode] Configure the style of navbar. Below is an example using [tab mode](#tab-mode) `navbar` & nav mode `top`: ![Notebook](/docs/notebook-nav-mode.png) ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/notebook'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { const { nav, ...base } = baseOptions(); return ( {children} ); } ``` ### AI Chat [#ai-chat] Same as [Docs Layout](/docs/ui/layouts/docs#ai-chat). # Fumadocs UI (the default theme of Fumadocs): Docs Page URL: /docs/ui/layouts/page Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/page.mdx A page in your documentation Page is the base element of a documentation, it includes Table of contents, Footer, and Breadcrumb. For advanced customization that supported options cannot suffice, install via Fumadocs CLI: ```bash npx @fumadocs/cli@latest customize ``` ## Usage [#usage] Import it according to your layout. ```tsx title="page.tsx" tab="Docs Layout" import { DocsPage, DocsDescription, DocsTitle, DocsBody } from 'fumadocs-ui/layouts/docs/page'; title description

This heading looks good!

It applies the Typography styles, wrap your content here.
; ``` ```tsx title="page.tsx" tab="Notebook Layout" import { DocsPage, DocsDescription, DocsTitle, DocsBody } from 'fumadocs-ui/layouts/notebook/page'; title description

This heading looks good!

It applies the Typography styles, wrap your content here.
; ``` Instead of rendering the title with `DocsTitle` in `page.tsx`, you can put the title into MDX file. This will render the title in the MDX body. ### Page Actions [#page-actions] Show GitHub link, and shortcut links for AIs. ```tsx import { DocsPage, ViewOptionsPopover } from 'fumadocs-ui/layouts//page'; const githubUrl = `https://github.com/fuma-nama/fumadocs/blob/main/content/docs/${encodeURI(page.path)}` ; ``` ### Last Updated Time [#last-updated-time] Display last updated time of the page. ```tsx import { DocsPage, PageLastUpdate } from 'fumadocs-ui/layouts//page'; const lastModifiedTime: Date | undefined; {/* Other content */} {lastModifiedTime && } ; ``` For `lastModifiedTime`, you can possibly use different version controls like Github or a CMS. You can enable [`lastModified`](/docs/mdx/last-modified). ```tsx import { source } from '@/lib/source'; const page = source.getPage(['...']); const lastModifiedTime = page.data.lastModified; ``` For Github hosted documents, you can use the [`getGithubLastEdit`](/docs/headless/utils/git-last-edit) utility. ```tsx import { getGithubLastEdit } from 'fumadocs-core/content/github'; const lastModifiedTime = await getGithubLastEdit({ owner: 'fuma-nama', repo: 'fumadocs', // file path in Git path: `content/docs/${page.path}`, }); ``` ## Configurations [#configurations] ### Full Mode [#full-mode] To extend the page to fill up all available space, pass `full` to the page component. This will force TOC to be shown as a popover. ```tsx import { DocsPage } from 'fumadocs-ui/layouts//page'; ...; ``` ### Table of Contents [#table-of-contents] An overview of all the headings in your article, it requires an array of headings. For Markdown and MDX documents, You can obtain it using the [TOC Utility](/docs/headless/utils/get-toc). Content sources like Fumadocs MDX offer this out-of-the-box. ```tsx import { DocsPage } from 'fumadocs-ui/layouts//page'; ...; ``` You can customize it with `tableOfContent`, or with `tableOfContentPopover` on smaller devices. ```tsx title="page.tsx" import { DocsPage } from 'fumadocs-ui/layouts//page'; return ( ... ); ``` | Prop | Type | Description | | ------------ | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `container?` | `React.DetailedHTMLProps, HTMLDivElement> \| undefined` | | | `header?` | `React.ReactNode` | Custom content in TOC container, before the main TOC | | `footer?` | `React.ReactNode` | Custom content in TOC container, after the main TOC | | `style?` | `"block" \| "clerk" \| "normal" \| undefined` | | | `list?` | `TOCItemsProps \| React.DetailedHTMLProps, HTMLDivElement> \| undefined` | | #### Style [#style] Choose another style for the TOC: A track line with a thumb on active headings (default). A track line following heading depth, inspired by [Clerk](https://clerk.com). No track line, a block slides behind active headings. ```tsx import { DocsPage } from 'fumadocs-ui/layouts//page'; ... ; ``` #### Replace TOC [#replace-toc] To replace the component: ```tsx tab="page.tsx" import { TOCProvider, TOC, TOCPopover } from './my-toc'; return ( ... ); ``` ```tsx tab="my-toc.tsx" 'use client'; import type { TOCProps, TOCPopoverProps, TOCProviderProps, } from 'fumadocs-ui/layouts//page/slots/toc'; export function TOCProvider({ toc, children }: TOCProviderProps) { // receive TOC items, you can pass it down via React contexts console.log(toc); return children; } export function TOC(props: TOCProps) { return
Hello World
; } export function TOCPopover(props: TOCPopoverProps) { return
Popover
; } ``` You can start from the default implementation with Fumadocs CLI: ```bash tab="Docs Layout" npx @fumadocs/cli add slots/docs/page/toc ``` ```bash tab="Notebook Layout" npx @fumadocs/cli add slots/notebook/page/toc ``` ```bash tab="Flux Layout" npx @fumadocs/cli add slots/flux/page/toc ``` ### Footer [#footer] Footer is a navigation element that has two buttons to jump to the next and previous pages. When not specified, it shows the neighbour pages found from page tree. Customize the footer with the `footer` prop: ```tsx import { DocsPage } from 'fumadocs-ui/layouts//page'; ...; ``` | Prop | Type | Description | | -------- | ------------------------------------------------ | ---------------------------------------------------------- | | `items?` | `{ previous?: Item; next?: Item; } \| undefined` | Items including information for the next and previous page | #### Replace Footer [#replace-footer] To replace the component: ```tsx tab="page.tsx" import { DocsPage } from 'fumadocs-ui/layouts//page'; import { Footer } from './my-footer'; ; ``` ```tsx tab="my-footer.tsx" 'use client'; import type { FooterProps } from 'fumadocs-ui/layouts//page/slots/footer'; export function Footer(props: FooterProps) { return
Hello World
; } ``` You can start from the default implementation with Fumadocs CLI: ```bash tab="Docs Layout" npx @fumadocs/cli add slots/docs/page/footer ``` ```bash tab="Notebook Layout" npx @fumadocs/cli add slots/notebook/page/footer ``` ```bash tab="Flux Layout" npx @fumadocs/cli add slots/flux/page/footer ``` ### Breadcrumb [#breadcrumb] A navigation element, shown only when user is navigating in folders. Customize the breadcrumb with the `breadcrumb` option: ```tsx import { DocsPage } from 'fumadocs-ui/layouts//page'; ...; ``` | Prop | Type | Description | | ------------------- | ------------------------------------------ | ------------------------------------------------------------------------ | | `includeRoot?` | `boolean \| { url: string; } \| undefined` | Include the root folders in the breadcrumb items array. Default: `false` | | `includePage?` | `boolean \| undefined` | Include the page itself in the breadcrumb items array Default: `false` | | `includeSeparator?` | `boolean \| undefined` | Count separator as an item Default: `false` | #### Replace Breadcrumb [#replace-breadcrumb] To replace the component: ```tsx tab="page.tsx" import { DocsPage } from 'fumadocs-ui/layouts//page'; import { Breadcrumb } from './my-breadcrumb'; ; ``` ```tsx tab="my-breadcrumb.tsx" 'use client'; import type { BreadcrumbProps } from 'fumadocs-ui/layouts//page/slots/breadcrumb'; export function Breadcrumb(props: BreadcrumbProps) { return
Hello World
; } ``` You can start from the default implementation with Fumadocs CLI: ```bash tab="Docs Layout" npx @fumadocs/cli add slots/docs/page/breadcrumb ``` ```bash tab="Notebook Layout" npx @fumadocs/cli add slots/notebook/page/breadcrumb ``` ```bash tab="Flux Layout" npx @fumadocs/cli add slots/flux/page/breadcrumb ``` ### Container [#container] Container controls the article wrapper around breadcrumb, body, and footer. To replace the page container: ```tsx tab="page.tsx" import { DocsPage } from 'fumadocs-ui/layouts//page'; import { Container } from './my-container'; ; ``` ```tsx tab="my-container.tsx" 'use client'; export function Container(props: React.ComponentProps<'article'>) { return
; } ``` You can start from the default implementation with Fumadocs CLI: ```bash tab="Docs Layout" npx @fumadocs/cli add slots/docs/page/container ``` ```bash tab="Notebook Layout" npx @fumadocs/cli add slots/notebook/page/container ``` ```bash tab="Flux Layout" npx @fumadocs/cli add slots/flux/page/container ``` # Fumadocs UI (the default theme of Fumadocs): Root Provider URL: /docs/ui/layouts/root-provider Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/root-provider.mdx The context provider of Fumadocs UI. The context provider of all the components, including `next-themes` and [``](/docs/headless#installation). It should be located at the root layout. ## Usage [#usage] Import it according to your React.js framework: ```jsx tab="Next.js" import { RootProvider } from 'fumadocs-ui/provider/next'; export default function Layout({ children }) { return ( {children} ); } ``` ```jsx tab="React Router" import { RootProvider } from 'fumadocs-ui/provider/react-router'; export function Layout({ children }) { return ( {children} ); } ``` ```jsx tab="TanStack Start" import { HeadContent, Scripts, } from '@tanstack/react-router'; import { RootProvider } from 'fumadocs-ui/provider/tanstack'; function RootDocument({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` ```jsx tab="Waku" import { RootProvider } from 'fumadocs-ui/provider/waku'; export default function Layout({ children }) { return ( {children} ); } ``` ```jsx tab="Astro" import { navigate } from 'astro:transitions/client'; import { RootProvider } from 'fumadocs-ui/provider/astro'; // Rendered inside a React island, pass pathname and params from the Astro page. export function Provider({ pathname, params, children }) { return ( {children} ); } ``` ### Search Dialog [#search-dialog] Customize or disable the search dialog with `search` option. ```jsx {children} ``` Learn more from [Search](/docs/ui/search). ### Theme Provider [#theme-provider] Fumadocs supports light/dark modes with [`next-themes`](https://github.com/pacocoursey/next-themes). Customize or disable it with `theme` option. ```jsx {children} ``` You can also install & reference `next-themes` in your code for managing themes. #### Hotkey [#hotkey] Pressing D toggles between light and dark mode. It is ignored while you are typing in an editable element (such as ``), or when a dialog like the search dialog is opened. Pass another key to `theme.hotKey`, or `false` to disable it. ```jsx {children} ``` A function is also accepted for full control over the matched key combination. ```jsx e.shiftKey && e.key === 'D', }} > {children} ``` # Fumadocs UI (the default theme of Fumadocs): Spacious Layout URL: /docs/ui/layouts/spacious Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/layouts/spacious.mdx A less compact version of Docs Layout A less compact version of [``](/docs/ui/layouts/docs), the page sits in an inset panel beside the sidebar, with page-level actions at the top of the panel. Spacious layout is only available in the Base UI version of Fumadocs UI (`@fumadocs/base-ui`). For advanced customization that supported options cannot suffice, install via Fumadocs CLI: ```bash npx @fumadocs/cli@latest customize ``` ## Usage [#usage] Enable the Spacious layout with `fumadocs-ui/layouts/spacious`. ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/spacious'; // [!code highlight] import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` Make sure to update your page import too: ```tsx title="page.tsx" import { ... } from 'fumadocs-ui/layouts/docs/page'; // [!code --] import { ... } from 'fumadocs-ui/layouts/spacious/page'; // [!code ++] ``` ### Styles [#styles] Like Glass layout, Spacious layout styles are **not** bundled into the CSS preset, so you don't pay for them unless you use the layout. Import them in your Tailwind CSS file: ```css title="Tailwind CSS" @import 'tailwindcss'; /* [!code ++] */ @import 'fumadocs-ui/css/generated/spacious.css'; @import 'fumadocs-ui/css/neutral.css'; @import 'fumadocs-ui/css/preset.css'; ``` - Spacious layout is a **client component**, you cannot pass unserializable props from a server component. - On desktop, the page scrolls inside the panel instead of the window. ## Configurations [#configurations] The options are inherited from [Docs Layout](/docs/ui/layouts/docs), with minor differences: - the `sidebar` option only accepts `defaultOpenLevel` and `prefetch`, the sidebar is always collapsible. - additional options (see below). ### Layout Tabs [#layout-tabs] Configure [Layout Tabs](/docs/ui/layouts/docs#layout-tabs) with the `tabs` prop, see the linked docs for how to add them. Tabs are shown as a dropdown at the top of sidebar. ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/spacious'; import { baseOptions } from '@/lib/layout.shared'; import { source } from '@/lib/source'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ### AI Chat [#ai-chat] Pass an `aiChat` object with the open state and a change handler to show **Ask AI** in the layout. With the `panel` option, the layout renders your chat panel for you: it's docked beside the page on wide screens (the table of contents moves into the page header), and floats over the page on smaller screens. ```tsx title="layout.tsx" 'use client'; import { DocsLayout } from 'fumadocs-ui/layouts/spacious'; import { useState } from 'react'; export function Layout({ children }) { const [open, setOpen] = useState(false); return ( , }} // ... > {children} ); } ``` ### Slots [#slots] Spacious layout exposes a `slots` option to override its parts, in addition to the shared slots (`navTitle`, `themeSwitch`, `searchTrigger`, `languageSelect`). | Slot | Description | | --------- | ---------------------------------------------------------------------------------- | | `header` | The navbar on mobile. | | `sidebar` | The sidebar system: `provider`, `main` (desktop) and `drawer` (mobile). | | `actions` | The actions at the top right of page, like the language switcher and options menu. | ```tsx title="layout.tsx" import { DocsLayout } from 'fumadocs-ui/layouts/spacious'; ; ``` ## Docs Page [#docs-page] The page component is similar to [Docs Page](/docs/ui/layouts/page), with a few differences: - The table of contents uses the `block` style by default. - `tableOfContentPopover` configures the table of contents dropdown in page header, and the table of contents bar on mobile. - `slots.toc` accepts a `dropdown` component for the dropdown in page header. - There is no `container` slot. # Fumadocs UI (the default theme of Fumadocs): Search UI URL: /docs/ui/search Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/search.mdx The UI for document search ## Overview [#overview] You can customize Search UI from [``](/docs/ui/layouts/root-provider). ```tsx title="app/layout.tsx" import { RootProvider } from 'fumadocs-ui/provider/'; import type { ReactNode } from 'react'; import { SearchDialog } from '@/components/my-search-dialog'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ### Hot Keys [#hot-keys] Customize the hot keys to trigger search dialog, by default it's ⌘ K or Ctrl K. ```tsx import { RootProvider } from 'fumadocs-ui/provider/'; {children} ; ``` ### References [#references] A full list of options. ### SearchProps | Prop | Type | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `preload?` | `boolean \| undefined` | **Deprecated.** Preload search dialog before opening it Default: `` `true` `` | | `links?` | `SearchLink[] \| undefined` | Custom links to be displayed if search is empty | | `hotKey?` | `HotKey[] \| undefined` | Hotkeys for triggering search dialog Default: `Meta/Ctrl + K` | | `SearchDialog?` | `React.ComponentType \| undefined` | Replace default search dialog, allowing you to use other solutions such as Algolia Search It receives the `open` and `onOpenChange` prop, can be lazy loaded with `React.lazy()` | | `options?` | `Partial \| undefined` | Additional props to the dialog | | `enabled?` | `boolean \| undefined` | Enable search functionality Default: `` `true` `` | ## Custom UI [#custom-ui] Fumadocs UI also exposes a lower level `` component for advanced use, you can create your own search dialog to replace the default one. ```tsx twoslash 'use client'; import React from 'react'; import { useFetchSearch } from 'fumadocs-core/search/client'; import { SearchDialog, SearchDialogClose, SearchDialogContent, SearchDialogHeader, SearchDialogFooter, SearchDialogIcon, SearchDialogInput, SearchDialogList, SearchDialogOverlay, type SharedProps, } from 'fumadocs-ui/components/dialog/search'; import { useI18n } from 'fumadocs-ui/contexts/i18n'; export default function DefaultSearchDialog(props: SharedProps) { const { locale } = useI18n(); // (optional) for i18n const search = useFetchSearch({ locale, }); return ( {/* footer items */} ); } ``` ### Content Renderer [#content-renderer] To render the Markdown content of search items on your own instead, pass `renderMarkdown`. ```tsx title="components/search.tsx" ( { // ... }} /> )} /> ``` ### Tables [#tables] Customize how tables in results are rendered. A custom `Table` renders the rows on its own: ```tsx title="components/search.tsx" table.rows.map((row) => ( {Item({ item: row, onClick: () => onSelect(row) })} )) } /> ``` ### Highlights [#highlights] Matches of the search query are highlighted with the [CSS Custom Highlight API](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API), style them with `::highlight(fd-search)`. ```css title="global.css" ::highlight(fd-search) { color: var(--color-fd-primary-foreground); background-color: var(--color-fd-primary); } ``` `` highlights the query of `data` from ``, or the search input without it. When rendering results on your own, highlight them with `useHighlightQuery()`. ```tsx title="components/search-result.tsx" 'use client'; import { useHighlightQuery } from 'fumadocs-core/search/client'; import type { ReactNode } from 'react'; export function SearchResult({ query, children }: { query: string; children: ReactNode }) { const ref = useHighlightQuery(query); return
{children}
; } ``` Text inside elements with `data-highlight-ignore` is not highlighted, like the badges of components. # Fumadocs UI (the default theme of Fumadocs): Themes URL: /docs/ui/theme Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/theme.mdx Add Theme to Fumadocs UI ## Overview [#overview] Fumadocs UI adds its own colors, animations, and utilities with Tailwind CSS preset. ### Setup [#setup] Only Tailwind CSS v4 is supported, the preset will also include source to Fumadocs UI itself: ```css title="Tailwind CSS" @import 'tailwindcss'; @import 'fumadocs-ui/css/neutral.css'; @import 'fumadocs-ui/css/preset.css'; ``` For **Shadcn UI**, you can use the `shadcn` preset instead. Fumadocs UI will adopt colors from your Shadcn UI theme. ```css @import 'tailwindcss'; @import 'fumadocs-ui/css/shadcn.css'; @import 'fumadocs-ui/css/preset.css'; ``` See [Colors](#colors) for details. ### Preflight Changes [#preflight-changes] By using the Tailwind CSS plugin, or the pre-built stylesheet, your default border, text and background colors will be changed. ### Light/Dark Modes [#lightdark-modes] Fumadocs supports light/dark modes with [`next-themes`](https://github.com/pacocoursey/next-themes), it is included in Root Provider. See [Root Provider](/docs/ui/layouts/root-provider#theme-provider) to learn more. ### RTL Layout [#rtl-layout] RTL (Right-to-left) layout is supported. To enable RTL, set the `dir` prop to `rtl` in body and root provider. ```tsx import { RootProvider } from 'fumadocs-ui/provider/'; import type { ReactNode } from 'react'; export default function RootLayout({ children }: { children: ReactNode }) { return ( {children} ); } ``` ### Layout Width [#layout-width] Customize the max width of docs layout with CSS Variables. ```css :root { --fd-layout-width: 1400px; } ``` ### Colors [#colors] It comes with many presets out-of-the-box, you can pick one you prefer. ```css @import 'fumadocs-ui/css/.css'; @import 'fumadocs-ui/css/preset.css'; ``` ![Neutral](/themes/neutral.png) ![Black](/themes/black.png) ![Vitepress](/themes/vitepress.png) ![Dusk](/themes/dusk.png) ![Catppuccin](/themes/catppuccin.png) ![Ocean](/themes/ocean.png) ![Purple](/themes/purple.png) ![Solar](/themes/solar.png) ![Emerald](/themes/emerald.png) ![Ruby](/themes/ruby.png) ![Aspen](/themes/aspen.png) The design system was inspired by [Shadcn UI](https://ui.shadcn.com), you can also customize the colors using [CSS/Theme variables](https://tailwindcss.com/docs/theme). ```css title="global.css" @theme { --color-fd-background: hsl(0, 0%, 96%); --color-fd-foreground: hsl(0, 0%, 3.9%); --color-fd-muted: hsl(0, 0%, 96.1%); --color-fd-muted-foreground: hsl(0, 0%, 45.1%); --color-fd-popover: hsl(0, 0%, 98%); --color-fd-popover-foreground: hsl(0, 0%, 15.1%); --color-fd-card: hsl(0, 0%, 94.7%); --color-fd-card-foreground: hsl(0, 0%, 3.9%); --color-fd-border: hsla(0, 0%, 80%, 50%); --color-fd-primary: hsl(0, 0%, 9%); --color-fd-primary-foreground: hsl(0, 0%, 98%); --color-fd-secondary: hsl(0, 0%, 93.1%); --color-fd-secondary-foreground: hsl(0, 0%, 9%); --color-fd-accent: hsla(0, 0%, 82%, 50%); --color-fd-accent-foreground: hsl(0, 0%, 9%); --color-fd-ring: hsl(0, 0%, 63.9%); } .dark { --color-fd-background: hsl(0, 0%, 7.04%); --color-fd-foreground: hsl(0, 0%, 92%); --color-fd-muted: hsl(0, 0%, 12.9%); --color-fd-muted-foreground: hsla(0, 0%, 70%, 0.8); --color-fd-popover: hsl(0, 0%, 11.6%); --color-fd-popover-foreground: hsl(0, 0%, 86.9%); --color-fd-card: hsl(0, 0%, 9.8%); --color-fd-card-foreground: hsl(0, 0%, 98%); --color-fd-border: hsla(0, 0%, 40%, 20%); --color-fd-primary: hsl(0, 0%, 98%); --color-fd-primary-foreground: hsl(0, 0%, 9%); --color-fd-secondary: hsl(0, 0%, 12.9%); --color-fd-secondary-foreground: hsl(0, 0%, 92%); --color-fd-accent: hsla(0, 0%, 40.9%, 30%); --color-fd-accent-foreground: hsl(0, 0%, 90%); --color-fd-ring: hsl(0, 0%, 54.9%); } ``` ### Typography [#typography] We have a built-in plugin forked from [Tailwind CSS Typography](https://tailwindcss.com/docs/typography-plugin). The plugin adds a `prose` class and variants to customize it. ```tsx

Good Heading

``` Use `prose-sm` or `prose-xs` alongside `prose` for the font size and line height of `text-sm` or `text-xs`, with an optically adjusted font weight: ```tsx
...
``` > The plugin is supposed to work with Fumadocs UI's MDX components, it may conflict with `@tailwindcss/typography`. > > If you need to use `@tailwindcss/typography` over the default plugin, [set a `className` option](https://github.com/tailwindlabs/tailwindcss-typography/blob/main/README.md#changing-the-default-class-name) to avoid conflicts. > > ```sass > @import 'tailwindcss'; > @plugin "@tailwindcss/typography" { > className: wysiwyg; > } > ``` # Fumadocs UI (the default theme of Fumadocs): Translations URL: /docs/ui/translations Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/ui/translations.mdx Adding Translations to UI ## Overview [#overview] All official Fumadocs packages use English by default, you can add translations for other languages. > This page mainly covers details for adding UI translations, you may be interested in the full [Internationalization](/docs/next/internationalization) guide instead. ### Singular [#singular] **Singular** refers to adding translations for only one language: ```ts title="lib/layout.shared.tsx" import { defineTranslations } from 'fumadocs-core/i18n'; import { uiTranslations } from 'fumadocs-ui/i18n'; export const translations = defineTranslations().extend(uiTranslations()).add({ // [label]: [translation] 'Search(search trigger)': '搜尋文檔', }); ``` > `.add()` should only be called **after** all `.extend()` calls. Pass the translations to ``. ```tsx import { RootProvider } from 'fumadocs-ui/provider/'; import { i18nProvider } from 'fumadocs-ui/i18n'; import { translations } from '@/lib/layout.shared'; export function Layout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` ### Multilingual [#multilingual] Define translations for multiple languages, this requires a standard [i18n](/docs/next/internationalization) setup. ```ts title="lib/layout.shared.tsx" import { defineTranslations } from 'fumadocs-core/i18n'; import { uiTranslations } from 'fumadocs-ui/i18n'; import { i18n } from '@/lib/i18n'; export const translations = i18n .translations() .extend(uiTranslations()) .add({ // [locale code]: [translations] cn: { // [label]: [translation] 'Search(search trigger)': '搜尋文檔', }, }); ``` Pass the translations to ``. ```tsx import { RootProvider } from 'fumadocs-ui/provider/'; import { i18nProvider } from 'fumadocs-ui/i18n'; import { translations } from '@/lib/layout.shared'; export function Layout({ locale, children }: { locale: string; children: React.ReactNode }) { return ( {children} ); } ``` ## Language Packs [#language-packs] Language packs provide translations for `fumadocs-ui` and several other integrations like Fumadocs OpenAPI. ```npm npm i @fumadocs/language ``` > If your desired language is missing in the official language packs, we welcome contributions to [our repository](https://github.com/fuma-nama/fumadocs). Use `preset()` to consume language packs: ```ts tab="Singular" import { defineTranslations } from 'fumadocs-core/i18n'; import { openapiTranslations } from 'fumadocs-openapi/i18n'; import { uiTranslations } from 'fumadocs-ui/i18n'; import { zhTW } from '@fumadocs/language/zh-tw'; export const translations = defineTranslations() .extend(uiTranslations()) // add extensions according to the integrations you configured, e.g. Fumadocs OpenAPI: .extend(openapiTranslations()) // Traditional Chinese .preset(zhTW()); ``` ```ts tab="Multilingual" import { defineTranslations } from 'fumadocs-core/i18n'; import { openapiTranslations } from 'fumadocs-openapi/i18n'; import { uiTranslations } from 'fumadocs-ui/i18n'; import { zhTW } from '@fumadocs/language/zh-tw'; import { i18n } from '@/lib/i18n'; export const translations = i18n .translations() .extend(uiTranslations()) // add extensions according to the integrations you configured, e.g. Fumadocs OpenAPI: .extend(openapiTranslations()) // add Traditional Chinese translations to the "cn" locale code .preset('cn', zhTW()); ``` ### Custom Packs [#custom-packs] You can also create & publish your own language packs. For example, the structure of `zh-TW` language pack looks like: ```ts twoslash import type { TranslationPreset } from 'fumadocs-core/i18n'; import * as OpenAPI from 'fumadocs-openapi/i18n'; import * as UI from 'fumadocs-ui/i18n'; import * as Story from '@fumadocs/story/i18n'; const translations = { displayName: '繁體中文', 'Server URL(playground server select)': '伺服器 URL', 'Variant(story controls)': '變體', // ... } satisfies Partial; export function zhTW(): TranslationPreset { return { name: 'zh-TW', value: translations, }; } ``` ## Extensions [#extensions] Extensions declare the available labels for translations, only registered labels will be sent to client payload. ### Custom Extension [#custom-extension] If you are building community packages for Fumadocs, you can create extensions to register your own translations. To begin, install the translations toolkit Fumadocs use: ```npm npm i @fuma-translate/react ``` ```ts tab="i18n.ts" twoslash import type { TranslationExtension } from 'fumadocs-core/i18n'; const keys = [ // key format: "your label(additional context)" 'Hello {user}(welcome screen)', ] as const; export function myTranslations(): TranslationExtension<(typeof keys)[number]> { return { keys }; } ``` ```tsx tab="Reference" 'use client'; import { useTranslations } from '@fuma-translate/react'; export function Comp() { const t = useTranslations(); return (
{t('Hello {user}', { note: 'welcome screen', variables: { user: '...', }, })}
); } ``` > While skipped for simplicity, you can see the docs of [Fuma Translate](https://fuma-translate.vercel.app) to learn how to compile translation keys & types, rather than hardcoding it. Consumers can use your extension like: ```ts import { defineTranslations } from 'fumadocs-core/i18n'; import { myTranslations } from 'my-package/i18n'; export const translations = defineTranslations() // [!code ++] .extend(myTranslations()) .add({ 'Hello {user}(welcome screen)': '你好 {user}', }); ``` # Fumadocs (Framework Mode, Next.js): Asyntai AI Chatbot URL: /docs/next/community/asyntai Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/[framework]/community/asyntai.mdx Let readers ask questions and get answers from your docs. > This is a community-maintained integration. Readers often cannot find the page they need, or they have a question that the search box does not answer. They leave, or they open a support ticket. [Asyntai](https://asyntai.com/documentation/integrations/nextjs/) adds an AI chat assistant to your Fumadocs site. It reads your published pages and answers readers from them, in more than 80 languages. The [`nextjs-ai-chatbot`](https://www.npmjs.com/package/nextjs-ai-chatbot) package adds the chat widget with one component. There is a free plan. ## Setup [#setup] You need an Asyntai widget ID. It starts with `asyntai_`, and you find it on the **Install** page of your Asyntai dashboard. ### 1. Install the package [#install-the-package] ```package-install nextjs-ai-chatbot ``` ### 2. Add the component [#add-the-component] Put `` at the end of the `` in your root layout. It works in Server Components. Keep the rest of your layout as it is. ```tsx title="app/layout.tsx" import { RootProvider } from 'fumadocs-ui/provider/next'; import { AsyntaiChatbot } from 'nextjs-ai-chatbot'; import type { ReactNode } from 'react'; export default function Layout({ children }: { children: ReactNode }) { return ( {children} ); } ``` The widget loads after the page's `load` event, so your docs always render first. Fumadocs changes pages without a full reload, and the chat stays on screen while the reader moves through your docs. ### 3. Add your docs in the dashboard [#add-your-docs-in-the-dashboard] Add the URL of your docs site in the Asyntai dashboard. The assistant then answers from the same pages the widget sits on. ## Widget ID from an environment variable [#widget-id-from-an-environment-variable] You can leave `widgetId` out and set it in `.env` instead: ```bash title=".env" NEXT_PUBLIC_ASYNTAI_WIDGET_ID=asyntai_YOURWIDGETID ``` Set it where you run `next build`, because Next.js reads `NEXT_PUBLIC_` values at build time. ## Without the package [#without-the-package] You can add the widget by hand with `next/script`: ```tsx title="app/layout.tsx" import Script from 'next/script';