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.
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:
If your plugin needs configuration via docu.json, use a factory function:
typescript
// plugins/analytics.tsimporttype{ DocuBookPlugin }from"@docubook/flame";interfaceAnalyticsOptions{ id:string; domain?:string;}exportdefaultfunctionpluginAnalytics( opts?: AnalyticsOptions
): DocuBookPlugin {// Throw early if required option is missingif(!opts?.id){thrownewError("[plugin:analytics] `id` is required. "+'Example: ["@docubook/plugin-analytics", { id: "G-XXXXXXX" }]');}// Options are inserted into HTML and JavaScript: encode them for eachconst 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.
Plugins can maintain internal state using the setup() closure:
typescript
exportdefaultfunctionpluginCounter(): DocuBookPlugin {// Internal state - persists across build/dev sessionlet 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
exportdefaultfunctionpluginValidator(): DocuBookPlugin {return{ name:"validator",setup(build){const{ config }= build;if(!config.meta?.baseURL){thrownewError("[plugin:validator] `meta.baseURL` is required in docu.json");}// Validate URLtry{newURL(config.meta.baseURL);}catch{thrownewError("[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 throwconsole.warn(`[plugin:validator] Empty file: ${path}`);}});},};}
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.
Hook
flame build
flame dev
onStart
Fails before any page is written
Log + continue to next callback
onLoad
Fails before any page is written. For the docs index, only that page is not written, exit code 1
Log + try next matching handler
transformFrontmatter
Fails: that docs page is not written, the others are, exit code 1
Log + frontmatter unchanged
transformHtml
Fails. 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 skipped
Log + HTML unchanged
onEnd
Fails: pages are written, the search index and build cache are not
— (not run)
handleRequest
— (not run)
Log + continue to next handler
injectHead / injectBody / remark / rehype
Throw - developer error
Throw - developer error
Plugin factory / setup()
Throw - stops the build
Throw - 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 itbuild.onLoad({ filter:/\.mdx$/},()=>{thrownewError("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.
Absolute 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/.
assetManifest
Hashed 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.
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.
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.
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.
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.
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).
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
importtype{ 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},});exportdefault 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.
// plugins/sitemap.tsimport{ writeFile }from"node:fs/promises";import{ join }from"node:path";importtype{ DocuBookPlugin }from"@docubook/flame";exportdefaultfunctionpluginSitemap(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/Denoawait(typeof Bun !=="undefined"? Bun.write(out, xml):writeFile(out, xml));});},};}
typescript
// plugins/analytics.tsimporttype{ DocuBookPlugin }from"@docubook/flame";exportdefaultfunctionpluginAnalytics(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 Source
Risk Level
Notes
Official @docubook/plugin-*
Low
Published and maintained by DocuBook team
Third-party npm package
High
Arbitrary code execution at build/dev time. Vet before installing.
Local path (./plugins/...)
Medium
Requires write access to project; review code in PR