Plugins and Themes

A Docusaurus site is assembled from packages that the configuration file lists. Content plugins own a source folder and emit routes. Themes own the React components and the styling that render those routes. Everything else — search, analytics, diagrams, live examples — is delivered the same way, as a plugin or a theme you add to the configuration. That uniformity is the point: there is no privileged “core” that you cannot reach, and the difference between changing a colour and adding a whole new content type is only the size of the package you write.

Plugins are Node modules that export a function. The function receives the build context and the options you passed in the configuration, and returns an object of lifecycle hooks. The hooks are called in a fixed order during the build, and each one has a single job:

HookWhen it runsWhat it is for
nameAlwaysIdentifies the plugin in logs and in error messages
validateOptionsBefore the buildValidates and normalises the options from the configuration file
loadContentAfter validationReads the source folder and returns the content it found
contentLoadedAfter all content is loadedRegisters routes, global data, and additional plugins
configureWebpackBefore bundlingAdjusts the webpack configuration
configurePostCssBefore bundlingAdjusts the PostCSS pipeline
getPathsToWatchDuring devDeclares extra files that should restart the dev server
extendCliAt startupRegisters extra CLI commands
getThemePathAlwaysPoints at the folder that contains the theme components
getClientModulesDuring bundlingRegisters extra client-side modules
injectHtmlTagsDuring buildAdds tags to the generated HTML head

The plugins that ship with the tool cover the standard site:

PluginResponsibility
docusaurus-plugin-content-docsReads docs/, builds the documentation routes and the sidebar
docusaurus-plugin-content-blogReads blog/, builds the list, tag, and author pages
docusaurus-plugin-content-pagesReads src/pages/ and builds standalone routes
docusaurus-plugin-sitemapEmits the sitemap from the routes that were built
docusaurus-plugin-google-gtagInjects a Google Analytics or tag manager snippet
docusaurus-plugin-client-redirectsEmits redirect entries for renamed pages
docusaurus-plugin-debugWrites build information to disk during development

The classic theme provides the navbar, the footer, the documentation layout, the blog layouts, the search box, and the dark mode switcher. The configuration file passes it a single themeConfig object, and that object is where most visual decisions are made:

// docusaurus.config.js
module.exports = {
  themeConfig: {
    navbar: {
      title: 'Acme',
      logo: { alt: 'Acme', src: 'img/logo.svg' },
      items: [
        { type: 'docSidebar', sidebarId: 'docs', position: 'left', label: 'Docs' },
        { to: '/blog', label: 'Blog', position: 'left' },
        { type: 'docsVersionDropdown', position: 'right' },
        { type: 'search', position: 'right' },
      ],
    },
    footer: { style: 'dark', links: [], copyright: 'Acme' },
    colorMode: { defaultMode: 'light', respectPrefersColorScheme: true },
    tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 },
    prism: { additionalLanguages: ['bash', 'diff'] },
    algolia: {
      appId: 'ACME',
      apiKey: 'search-key',
      indexName: 'acme-docs',
    },
  },
};

Notice that themeConfig is flat and declarative. It is the cheapest place to change anything, and it should be exhausted before you reach for a more invasive technique.

The classic theme is built on Infima, a small CSS framework whose entire visual language is expressed as custom properties. That is why retheming a Docusaurus site is usually a single stylesheet rather than a fork. The generated src/css/custom.css is imported by the theme and can override any of those variables:

/* src/css/custom.css */
:root {
  --ifm-color-primary: #2f6f4f;
  --ifm-color-primary-dark: #296447;
  --ifm-color-primary-darker: #275f43;
  --ifm-color-primary-darkest: #214e38;
  --ifm-color-primary-light: #357a57;
  --ifm-color-primary-lighter: #38805a;
  --ifm-color-primary-lightest: #408f66;
  --ifm-font-family-base: system-ui, -apple-system, 'Segoe UI', sans-serif;
  --ifm-code-font-size: 92%;
}

[data-theme='dark'] {
  --ifm-color-primary: #6fcf97;
}

For changes that CSS variables cannot express, Docusaurus offers swizzling, which copies a theme component into src/theme/ so you can edit it:

npm run swizzle @docusaurus/theme-classic Navbar --wrap
npm run swizzle @docusaurus/theme-classic DocItem/Content --eject

--wrap generates a file that renders your component around the original one, which is the safe option when you only need to add something. --eject copies the original implementation into your project so you own it, which is the right choice when you need to change behaviour, and the one that costs you automatic upstream fixes.

When neither a theme option nor a swizzled component is enough, you write a plugin. The skeleton is short:

// docusaurus-plugin-acme-report/index.js
module.exports = function acmeReportPlugin(context, options) {
  return {
    name: 'docusaurus-plugin-acme-report',

    validateOptions({ options: pluginOptions }) {
      if (typeof pluginOptions.outputFile !== 'string') {
        throw new Error('acme-report: `outputFile` is required');
      }
      return pluginOptions;
    },

    async contentLoaded({ actions, allContent }) {
      const { createData } = actions;
      const pages = Object.keys(allContent);
      await createData('acme-report.json', JSON.stringify({ pages }, null, 2));
    },
  };
};

A theme is the same idea with a different emphasis: it is a plugin that points at a folder of React components and optionally registers extra client modules.

// docusaurus-theme-acme/index.js
const path = require('path');

module.exports = function acmeTheme(context, options) {
  return {
    name: 'docusaurus-theme-acme',
    getThemePath: () => path.resolve(__dirname, './theme'),
    getTypeScriptThemePath: () => path.resolve(__dirname, './src'),
    getClientModules: () => [require.resolve('./client/index.js')],
  };
};

Choosing between these mechanisms is mostly a matter of finding the least invasive one that does the job:

GoalApproachCost
Change colours, fonts, spacingCSS variables in src/css/custom.cssMinutes
Change navigation or footer itemsthemeConfig in the configuration fileMinutes
Add a section around an existing componentSwizzle with --wrapAn hour
Change what a component rendersSwizzle with --ejectA day, and you own it afterwards
Add a new kind of contentWrite a content pluginA week or more
Change how the bundle is producedWrite a plugin with configureWebpackA week or more
Publish a reusable look and feelWrite a theme packageA week or more

Two habits keep this from becoming a maintenance problem. First, resist writing a plugin for anything the configuration file already expresses; the option surface of a theme is wide, and most customisation requests are a matter of finding the right key. Second, when you do eject a component, record why in a comment at the top of the file, because the next person to read it will otherwise assume the difference was accidental and try to undo it. A documentation site that is easy to update after a year of internal changes is worth more than one that is perfect on the day it ships.

Found an issue with this content?

Tell us what could be improved.