Plugins

Extend DocuBook with hooks for sitemaps, analytics, custom transforms, and more

DocuBook's plugin system extends the build pipeline and dev server without forking internals. Plugins are optional - zero plugins = zero behavior change.

Configuration

Add a plugins array to docu.json:

json
{
  "plugins": [
    "@docubook/plugin-sitemap",
    ["@docubook/plugin-analytics", { "id": "G-XXXXXXX" }],
    "./plugins/reading-time"
  ]
}
FormatDescription
"string"Plugin name, npm package, or relative path
["string", { ... }]Plugin name + factory options

Resolution: relative path (starts with .) → project root, absolute → as-is, else → npm package.

Creating a Plugin

  1. Step 1: Project Setup

    Create a plugin file in your project directory, for example plugins/reading-time.ts:

    text
    project-root/
    ├── docs/
    ├── docu.json
    ├── plugins/
    │   ├── reading-time.ts
    │   └── sitemap.ts
    └── package.json
    

    A plugin can be stored as a local file in your plugins/ folder, or published as a separate package on npm under @docubook/plugin-* or docubook-plugin-*.

  2. Step 2: Basic Plugin Structure

    Every plugin must have a unique name and a setup(build) function:

    typescript
    // plugins/reading-time.ts
    import type { DocuBookPlugin } from "@docubook/flame";
    
    const plugin: DocuBookPlugin = {
      name: "reading-time",
      setup(build) {
        // Register hooks here
        build.onStart((config) => {
          console.log(`[${plugin.name}] Build started`);
        });
      },
    };
    
    export default plugin;
    
  3. Step 3: Using Factory Options

    If your plugin needs configuration via docu.json, use a factory function:

    typescript
    // plugins/analytics.ts
    import type { DocuBookPlugin } from "@docubook/flame";
    
    interface AnalyticsOptions {
      id: string;
      domain?: string;
    }
    
    export default function pluginAnalytics(
      opts?: AnalyticsOptions
    ): DocuBookPlugin {
      // Throw early if required option is missing
      if (!opts?.id) {
        throw new Error(
          "[plugin:analytics] `id` is required. " +
          'Example: ["@docubook/plugin-analytics", { id: "G-XXXXXXX" }]'
        );
      }
    
      // Options are inserted into HTML and JavaScript: encode them for each
      const id = encodeURIComponent(opts.id);
      const idJs = JSON.stringify(opts.id).replace(/</g, "\\u003c");
    
      return {
        name: "analytics",
        setup(build) {
          build.injectHead((ctx) => {
            return `
    <script async src="https://www.googletagmanager.com/gtag/js?id=${id}"></script>
    <script nonce="${ctx.nonce}">
      window.dataLayer = window.dataLayer || [];
      function gtag(){ dataLayer.push(arguments); }
      gtag('js', new Date());
      gtag('config', ${idJs});
    </script>`;
          });
        },
      };
    }
    

    The inline <script> carries the page's CSP nonce (ctx.nonce) and runs. The gtag.js file from googletagmanager.com is blocked by the CSP: see Scripts and the Content Security Policy.

    Then register it in docu.json:

    json
    {
      "plugins": [
        ["./plugins/analytics", { "id": "G-12345678" }]
      ]
    }
    
  4. Step 4: Managing Plugin State

    Plugins can maintain internal state using the setup() closure:

    typescript
    export default function pluginCounter(): DocuBookPlugin {
      // Internal state - persists across build/dev session
      let pageCount = 0;
      const startTime = Date.now();
    
      return {
        name: "counter",
        setup(build) {
          build.onEnd((_config, pages) => {
            pageCount = pages.length;
            const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
            console.log(`[counter] Built ${pageCount} pages in ${elapsed}s`);
          });
    
          build.onStart(() => {
            pageCount = 0;
          });
        },
      };
    }
    
  5. Step 5: Error Handling

    Don't throw raw errors - use clear messages with a [plugin:name] prefix. Check required options in the factory or in setup(): an error thrown there stops both flame build and flame dev. An error thrown inside a hook such as onStart fails flame build, but flame dev only logs it and runs without the check.

    typescript
    export default function pluginValidator(): DocuBookPlugin {
      return {
        name: "validator",
        setup(build) {
          const { config } = build;
          if (!config.meta?.baseURL) {
            throw new Error(
              "[plugin:validator] `meta.baseURL` is required in docu.json"
            );
          }
          // Validate URL
          try {
            new URL(config.meta.baseURL);
          } catch {
            throw new Error(
              "[plugin:validator] `meta.baseURL` is not a valid URL: " +
              config.meta.baseURL
            );
          }
    
          build.onLoad({ filter: /\.mdx$/ }, ({ path, content }) => {
            if (!content.trim()) {
              // Just a warning, don't throw
              console.warn(`[plugin:validator] Empty file: ${path}`);
            }
          });
        },
      };
    }
    

    See Error Handling for how errors behave in each hook.

  6. Step 6: Testing Plugins

    Use the available test helpers:

    typescript
    // plugins/__tests__/reading-time.test.ts
    import { describe, it, expect, beforeEach } from "vitest";
    import { BuildPluginBuilder } from "@docubook/flame/.docu/node/plugin-builder";
    import readingTimePlugin from "../reading-time";
    
    // Create a minimal config for testing
    function createTestConfig() {
      return {
        meta: { title: "Test", description: "", baseURL: "https://test.dev" },
        navbar: { logoText: "Test", menu: [] },
        footer: { social: [] },
        repo: { url: "", path: "", edit: false },
        routes: [],
      };
    }
    
    describe("reading-time plugin", () => {
      let builder: BuildPluginBuilder;
    
      beforeEach(() => {
        builder = new BuildPluginBuilder(createTestConfig() as any);
        readingTimePlugin.setup(builder);
      });
    
      it("adds readingTime to frontmatter", async () => {
        const result = await builder.runTransformFrontmatterChain(
          {},
          { slug: "test", filePath: "test.mdx", content: "a ".repeat(400) }
        );
        expect(result).toHaveProperty("readingTime");
        expect(result.readingTime).toMatch(/\d+ min read/);
      });
    
      it("does not modify title when content is empty", async () => {
        const result = await builder.runTransformFrontmatterChain(
          { title: "Test" },
          { slug: "test", filePath: "test.mdx", content: "" }
        );
        expect(result).toHaveProperty("title", "Test");
        expect(result).toHaveProperty("readingTime");
      });
    });
    

    Run the tests:

    bash
    npx vitest run plugins/__tests__/
    
  7. Step 7: Using Multiple Hooks

    A single plugin can register multiple hooks at once:

    typescript
    export default function pluginComplete(): DocuBookPlugin {
      return {
        name: "complete",
        setup(build) {
          build.onStart((config) => {
            console.log(`Building for ${config.meta.title}`);
          });
    
          build.onLoad({ filter: /\.md$/ }, ({ content }) => {
            // Convert .md to custom MDX format
            const enhanced = `import { CustomComponent } from "./components";\n\n${content}`;
            return { contents: enhanced, loader: "mdx" };
          });
    
          build.transformFrontmatter((fm) => ({
            ...fm,
            processed: true,
            generatedAt: new Date().toISOString(),
          }));
    
          build.remarkPlugins(() => [remarkCustomId]);
    
          build.injectHead(() => `<meta name="generator" content="docubook-flame">`);
    
          build.transformHtml((html) => html.replace(/\bTODO\b/g, ""));
    
          build.onEnd((_config, pages) => {
            console.log(`Done: ${pages.length} pages`);
          });
        },
      };
    }
    
  8. Step 8: Publishing a Plugin

    To publish a plugin to npm, choose a namespace — @docubook/plugin-* for official plugins or docubook-plugin-* for community ones. The entry point must export a default DocuBookPlugin or factory function. Add @docubook/flame as a peer dependency and include a README with a docu.json configuration example.

    json
    // package.json for npm plugin
    {
      "name": "@docubook/plugin-sitemap",
      "version": "1.0.0",
      "type": "module",
      "main": "./dist/index.js",
      "types": "./dist/index.d.ts",
      "peerDependencies": {
        "@docubook/flame": "^2.0.0-beta.5"
      },
      "files": ["dist"]
    }
    

    For the full implementation example, see the sitemap example below.

Error Handling

When a hook throws, flame build fails, so a site never ships without a hook's work. flame dev logs the error and carries on, so one broken plugin does not stop the server while you fix it.

Hookflame buildflame dev
onStartFails before any page is writtenLog + continue to next callback
onLoadFails before any page is written. For the docs index, only that page is not written, exit code 1Log + try next matching handler
transformFrontmatterFails: that docs page is not written, the others are, exit code 1Log + frontmatter unchanged
transformHtmlFails. On a docs page, that page is not written, exit code 1. On the landing or 404 page, the build stops: later pages, the search index, the build cache and onEnd are skippedLog + HTML unchanged
onEndFails: pages are written, the search index and build cache are not— (not run)
handleRequest— (not run)Log + continue to next handler
injectHead / injectBody / remark / rehypeThrow - developer errorThrow - developer error
Plugin factory / setup()Throw - stops the buildThrow - stops the server

The error names the hook, and for page hooks the source file:

text
[plugin] onLoad handler for filter /\.mdx$/ on docs/guide/intro.mdx error: Something went wrong

Check required options in the factory or setup(): an error there stops both flame build and flame dev, while a hook error only stops the build.

typescript
// Example: a failing hook - flame build exits with code 1, flame dev logs it
build.onLoad({ filter: /\.mdx$/ }, () => {
  throw new Error("Something went wrong");
});

Hook Reference

onStart(config)

Called once before the build. Use for resource initialization, such as fetching remote data. An error thrown here fails flame build, but flame dev only logs it; check required options in setup(), which stops both.

typescript
build.onStart(async (config) => {
  if (!config.meta.baseURL) console.warn("[plugin:sitemap] `meta.baseURL` is not set, URLs stay relative");
});

onEnd(config, pages, context)

Called after all page HTML has been written. Generate sitemaps, RSS feeds, or other output using the final output directory and page-specific asset manifest.

typescript
import { join } from "node:path";

build.onEnd((config, pages, { outDir, assetsDir, assetManifest }) => {
  // pages: { slug, title, filePath, outputPath }[]
  console.log(`Built ${pages.length} pages to ${outDir}`);
  console.log(`Docs CSS: ${join(assetsDir, assetManifest.docs.css)}`);
});
FieldDescription
outDirAbsolute output directory (.docu/dist).
assetsDirAbsolute directory of the hashed bundles, manifest.json and search-index.json. It is outDir/assets by default and outDir/<basePath>/_flame with experimental.pages. Resolve manifest entries against it rather than a hard-coded assets/.
assetManifestHashed file names per page family (docs, home, notFound), relative to assetsDir. home is absent with experimental.pages.

onLoad({ filter }, callback)

Transform raw file content before MDX compilation. Bun's build.onLoad() convention.

typescript
build.onLoad({ filter: /\.md$/ }, ({ path, content }) => {
  return { contents: `<!-- auto-generated -->\n\n${content}` };
});

transformFrontmatter(fm, ctx)

Mutate frontmatter before MDX compilation. Return a new object or void.

typescript
build.transformFrontmatter((fm, ctx) => {
  const minutes = Math.max(1, Math.ceil((ctx.content ?? "").split(/\s+/).length / 200));
  return { ...fm, readingTime: `${minutes} min read` };
});

remarkPlugins() / rehypePlugins()

Add remark or rehype plugins to the MDX pipeline. Merged after the default set.

typescript
build.remarkPlugins(() => [require("remark-custom-heading-id")]);
build.rehypePlugins(() => [require("rehype-autolink-headings")]);

injectHead(ctx)

Return HTML strings to inject inside <head>. Results from all plugins are merged and deduplicated. This hook runs for docs, home, and standalone 404 pages.

typescript
build.injectHead((ctx) =>
  `<meta name="docubook-page-type" content="${ctx.pageType}">`
);

injectBody(ctx)

Return HTML strings to inject before </body>. Check ctx.assets.js before generating markup that depends on a client bundle because JavaScript is optional, including on the standalone 404 page.

typescript
build.injectBody((ctx) =>
  ctx.assets.js ? `<script nonce="${ctx.nonce}">console.log("Client bundle loaded")</script>` : []
);

Scripts and the Content Security Policy

Every page carries a Content Security Policy that runs a script only when it comes from the site's own origin or carries the page's nonce.

  • Inline <script> runs only with the page's nonce. Write it yourself from ctx.nonce: <script nonce="${ctx.nonce}">. It then runs in flame dev, flame preview, and on the deployed site.
  • Flame never adds the nonce to plugin output. A <script> that reaches your HTML through an unescaped value, such as a frontmatter title, stays blocked. Still escape every value you insert.
  • <script src> runs without a nonce when the file comes from the site's own origin. Ship the file with the site: copy it into assetsDir in onEnd, serve it from assetsPath in handleRequest for flame dev, and point src at the bundle directory.
  • Scripts from another host, such as googletagmanager.com, are blocked. Flame has no option yet to add a host to the policy. Giving such a <script src> the nonce makes it run, but it then runs with full control of the page, and scripts it loads from other hosts are still blocked.

transformHtml(html, ctx)

Transform the final HTML string for docs, home, and standalone 404 pages. It is the last page hook before writing HTML to disk.

typescript
build.transformHtml((html, ctx) =>
  html.replace("</body>", `<!-- ${ctx.pageType} -->\n</body>`)
);

Page context and assets

injectHead, injectBody, and transformHtml receive a PageContext:

FieldDescription
pageType"docs", "home", or "notFound"
assetsHashed { css, js? } entry used by this page
slugDocs slug, an empty string for home, or "404"
filePathSource or framework page path
frontmatterDocs frontmatter, site metadata for home, or an empty object for 404
contentRaw MDX/Markdown content when available
configResolved DocuBook configuration
nonceThe page's CSP nonce, for inline <script> tags (see Scripts and the Content Security Policy)

The final asset manifest uses the same page families:

typescript
{
  docs: { css: "docs-HASH.css", js: "client-HASH.js" },
  home: { css: "site-HASH.css", js: "home-client-HASH.js" },
  notFound: { css: "site-HASH.css" }
}

Do not parse manifest.json as a single { js, css } bundle. Read the entry for the current pageType, and treat every js field as optional.

handleRequest(req, ctx)

Intercept incoming dev server requests. First plugin to return a Response short-circuits. The context contains port, hostname, the current page-specific assetManifest, including updates from dev rebuilds, and assetsPath: the URL path the dev server serves the bundles from (/assets, or <basePath>/_flame with experimental.pages). A plugin that writes files into assetsDir in onEnd can serve the same files under assetsPath during flame dev.

typescript
build.handleRequest((req, ctx) => {
  const url = new URL(req.url);
  if (url.pathname === "/api/status") {
    return Response.json({
      ok: true,
      docsCss: ctx.assetManifest.docs.css,
    });
  }
});

Search providers

A plugin can replace the built-in search dialog while Flame keeps its search bar, the ⌘ K shortcut and the mobile search icon. The Algolia plugin works this way.

  1. Declare the provider on docs pages

    Inject a JSON block with the id docubook-search-provider. module is the path of your browser module relative to the bundle directory. askAi: true also shows Flame's Ask AI buttons (Sparkles beside the sidebar search bar, a row in the mobile drawer, and ⌘ I).

    typescript
    build.injectHead((ctx) =>
      ctx.pageType === "docs"
        ? `<script type="application/json" id="docubook-search-provider">${JSON.stringify({
            module: "my-search/client.js",
            askAi: false,
            // ...anything else your module needs
          }).replace(/</g, "\\u003c")}</script>`
        : []
    );
    
  2. Ship the module beside the bundles

    Copy it into assetsDir in onEnd and serve it under assetsPath in handleRequest, so it resolves in both flame build and flame dev, under a subpath deployment and with experimental.pages.

  3. Export a provider factory

    Flame imports the module the first time the reader hovers, focuses or opens search, and calls its default export with the parsed JSON:

    typescript
    import type { SearchProviderFactory } from "@docubook/flame";
    
    const createProvider: SearchProviderFactory = (config) => ({
      open() {
        // open your search UI
      },
      askAi() {
        // open your Ask AI UI, or close it when it is open
      },
    });
    
    export default createProvider;
    

The module path must stay inside the bundle directory: Flame refuses absolute, remote and .. paths and keeps the built-in search when the declaration is invalid.

Lifecycle

text
build()
├─ loadPlugins → plugin.setup(build)        ← validate, register hooks
├─ onStart(config)                          ← initialize
├─ for each MDX file: onLoad({filter})     ← transform raw content (client bundle)
├─ for each MDX file not in the build cache:
│   ├── onLoad({filter})                    ← transform raw content
│   ├── compileMdx() ← remark / rehype      ← MDX pipeline
│   ├── transformFrontmatter()              ← mutate frontmatter (before SEO tags)
│   ├── injectHead() / injectBody()         ← docs context
│   ├── transformHtml()                     ← final docs transform
│   └── write docs HTML
├─ render home → page hooks → write HTML
├─ render standalone 404 → page hooks → write HTML
└─ onEnd(config, pages, context)             ← final output metadata

flame build skips docs pages whose source, docu.json and plugins are unchanged since the last build, so the per-page hooks from transformFrontmatter to transformHtml run only for pages it renders again. A plugin package counts as changed when its version or built dist/ changes, and a local plugin when its own file changes. onEnd still receives every page. Run flame build --force to render every page, for example after editing a file that a local plugin imports.

Execution is sequential (waterfall). Plugins run in docu.json order and handleRequest is first-wins. Execution-hook errors fail flame build and are logged by flame dev; collection hooks such as injectHead and injectBody throw developer errors.

Example Plugins

Plugin hooks run on Bun, Node, and Deno. For a plugin that works everywhere, use node: APIs (e.g. node:fs/promises). If you want Bun's faster Bun.write when it is available, guard it behind a typeof Bun !== "undefined" check and fall back to writeFile on Node and Deno — the sitemap plugin below does exactly that. Plugins that will only ever run in a Bun-only project can call Bun.write directly.

typescript
// plugins/reading-time.ts
import type { DocuBookPlugin } from "@docubook/flame";

export default {
  name: "reading-time",
  setup(build) {
    build.transformFrontmatter((fm, ctx) => {
      const minutes = Math.ceil((ctx.content ?? "").split(/\s+/).length / 200);
      return { ...fm, readingTime: `${minutes} min read` };
    });
  },
} satisfies DocuBookPlugin;
typescript
// plugins/sitemap.ts
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { DocuBookPlugin } from "@docubook/flame";

export default function pluginSitemap(opts?: { hostname?: string }): DocuBookPlugin {
  return {
    name: "sitemap",
    setup(build) {
      build.onEnd(async (config, pages, { outDir }) => {
        const host = opts?.hostname || config.meta.baseURL;
        const urls = pages.map(
          (p) => `<url><loc>${host}/docs/${p.slug}</loc></url>`
        );
        const xml = `<?xml version="1.0"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join("\n")}\n</urlset>`;
        const out = join(outDir, "sitemap.xml");
        // Bun.write on Bun for speed, writeFile on Node/Deno
        await (typeof Bun !== "undefined"
          ? Bun.write(out, xml)
          : writeFile(out, xml));
      });
    },
  };
}
typescript
// plugins/analytics.ts
import type { DocuBookPlugin } from "@docubook/flame";

export default function pluginAnalytics(opts: { id: string }): DocuBookPlugin {
  const id = encodeURIComponent(opts.id);
  const idJs = JSON.stringify(opts.id).replace(/</g, "\\u003c");
  return {
    name: "analytics",
    setup(build) {
      // Blocked by the CSP until flame can add a host to it
      build.injectHead(() =>
        `<script async src="https://www.googletagmanager.com/gtag/js?id=${id}"></script>`
      );
      // Runs: carries the page's nonce
      build.injectBody((ctx) =>
        `<script nonce="${ctx.nonce}">window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag('js',new Date());gtag('config',${idJs});</script>`
      );
    },
  };
}

Security & Trust Model

Plugin hooks run with full system privileges - same as the user running bun dev.

Plugin SourceRisk LevelNotes
Official @docubook/plugin-*LowPublished and maintained by DocuBook team
Third-party npm packageHighArbitrary code execution at build/dev time. Vet before installing.
Local path (./plugins/...)MediumRequires write access to project; review code in PR

Path Resolution Security

text
./plugins/my-plugin.ts     ✅ Allowed (within project root)
../malicious.js            ❌ Blocked (path traversal guard)
/usr/lib/evil.mjs          ❌ Blocked (outside project root)
@docubook/plugin-sitemap   ✅ Allowed (npm package, bypasses guard)

The plugin loader rejects any specifier that resolves outside the project root. Absolute paths and .. traversal are blocked at load time.

Best Practices

  • Pin plugin versions in package.json - never use ranges for plugins
  • Review plugin source before adding to docu.json
  • Official plugins use the @docubook/plugin-* namespace - verify the package owner on npm
  • Run bun dev with least privilege - avoid running as root
  • CI/CD - validate docu.json against unexpected plugin entries

Plugins have the same trust model as devDependencies. Only install plugins from sources you trust, same as you would with any npm package.

TypeScript Types

typescript
import type {
  DocuBookPlugin,
  PluginBuilder,
  PageContext,
  PageMeta,
  PageType,
  AssetEntry,
  AssetManifest,
  DevServerContext,
  BuildEndContext,
  PluginEntry,
  SearchProvider,
  SearchProviderConfig,
  SearchProviderFactory,
} from "@docubook/flame";

All types are exported from the @docubook/flame package entry point.

Last updated Nov 6, 2026