Using Docusaurus to Build A Modern Documentation Website

Semaphore
21 min readJul 17, 2024

--

When building a software product, whether a framework, library or any interesting piece of technology, having a well-designed documentation website that provides a great user experience is non-negotiable. No matter how exceptional the product itself may be, if the documentation falls short, it can severely impact the adoption and usability of that product. Too often, users complain about wasting time searching for answers, resorting to external resources, or expressing frustration over the minimal effort put into official documentation.

For developers or organizations who have invested countless hours into building a product, such critiques can be disheartening, but they highlight an important reality: if your documentation website is poorly built, it creates a bad impression of the product’s quality.

However, building a software documentation website from scratch can be daunting. It requires great effort and keen attention to detail. Using general-purpose tools like Next.js is certainly a viable option, but it necessitates manually handling aspects such as content management, SEO, accessibility, versioning, and other technical complexities. Dealing with these complexities can divert attention from the core goal of creating comprehensive software documentation.

Over the years, several specialized tools have emerged to address these challenges. One such tool that has gained popularity is Docusaurus. Docusaurus makes building software documentation extremely easy by handling the technical heavy lifting, allowing you to focus more on creating high-quality content instead of worrying about the underlying infrastructure. In this article, we will learn how to use Docusaurus to build visually appealing documentation that is not only functional but also a pleasure to use.

What is Docusaurus?

Docusaurus is an open-source tool for building documentation websites. It was created by engineers at Meta to make creating and maintaining documentation a delightful experience. The idea behind Docusaurus is to allow you to write documentation using Markdown and React-based MDX. This combination makes it easy to create both regular documentation pages and interactive content. One of the biggest advantages of Docusaurus is that it is built on top of React, which means you can leverage your existing React knowledge and write custom React components. Many popular companies, such as Algolia, Redis Labs Developer Site, Atlas, Jest, and React Native, to mention just a few, have adopted Docusaurus for their documentation due to the excellent developer experience it provides.

Why Choose Docusaurus? A Comparison with Alternatives

Docusaurus is often the popular choice for building documentation websites, but it’s not the only option available. Let’s compare Docusaurus with some popular alternatives:

FeatureDocusaurusGitBookMkDocsVuePressJekyllSphinxBase TechnologyReactJavaScriptPythonVueRubyPythonCustomizationHighModerateModerateHighHighHighLearning CurveModerateLowLowModerateModerateSteepVersioningBuilt-inLimitedPluginPluginPluginBuilt-inInternationalizationBuilt-inBuilt-inPluginPluginPluginBuilt-inPerformanceHighModerateHighHighModerateHighMDX SupportYesNoNoNoNoNoSearchBuilt-inBuilt-inPluginPluginPluginBuilt-inOutput FormatsWebWeb, PDFWebWebWebWeb, PDF, ePubBest ForLarge web docs, React devsQuick setup, non-devsSmall to medium projectsVue devsStatic sitesPython projects

Each tool has its strengths, but Docusaurus shines when you need a modern, customizable documentation website with out-of-the-box features like versioning and internationalization. Its React foundation makes it particularly appealing for teams already working with React-based projects.

Prerequisites

To ensure you can follow along effectively, this tutorial assumes you have the following:

  • Node.js installed
  • Basic knowledge of React
  • Basic understanding of Markdown syntax

Getting Started

Docusaurus streamlines the process of setting up a documentation website, which allows you to go from concept to deployment quickly. In this section, we will initialize a new Docusaurus project, explore its structure, and get it running locally.

Installing Docusaurus

Docusaurus provides a useful CLI tool that scaffolds a new project with sensible defaults. To initialize a new project, open your terminal and run:

npx create-docusaurus@latest my-docs classic

This will create a new Docusaurus project named my-docs, but you can use any name you prefer. The classic flag specifies that this project will use the classic template, which includes essential features and configurations for a documentation site. During setup, you will be prompted to choose:

  • Javascript or Typescript (I’ll be using Javascript for the purposes of this tutorial)
  • Optional GitLab/GitHub repository creation

Alternatively, you can use any package manager of your choice like npm, yarn, or pnpm straight from the get-go:

npm init docusaurus
# or
yarn init docusaurus
# or
pnpm init docusaurus

Project Structure

Let’s navigate into the newly created Docusaurus project and get familiarised with its structure:

cd my-docs

You will see something like:

my-docs
├── blog
├── docs
│ ├── intro.md
│ └── tutorial-basics
│ ├── congratulations.md
│ ├── create-a-blog-post.md
│ ├── create-a-document.md
│ ├── create-a-page.md
│ ├── deploy-your-site.md
│ ├── markdown-features.md
│ └── thank-you.md
├── package.json
├── src
│ ├── components
│ ├── css
│ └── pages
├── static
├── .gitignore
├── barbel.config.js
├── package.json
├── package-lock.json
└── docusaurus.config.js

Key directories:

  • blog/: This directory contains blog posts written in Markdown or mdx.
  • docs/: This is where you we will place your documentation files in Markdown or mdx format.
  • src/: Here, you can create pages and customize components, layouts, and other React-related code for your site.
  • static/: This directory is for static assets like images, fonts, etc.
  • docusaurus.config.js: This is the main configuration file for your Docusaurus site.
  • sidebars.js: This file is responsible for auto-generating and customizing the sidebar.

Running Locally

First, run npm install to install all the required dependencies, and then start your development server:

npm run start

This will compile all the Markdown and React files, start a local development server (typically at http://localhost:3000), and enable hot reloading for instant updates. You should see the default Docusaurus site running in your browser.

Understanding the Config File

We will begin by exploring the docusaurus.config.js. This file acts as a control center for your Docusaurus project where you can tweak the site’s behavior, appearance, and functionality. Let’s dissect this config file and understand how each part shapes your documentation’s identity and user experience.

Open docusaurus.config.js in your editor. You will see a structure like this:

const config = {
title: "My Site",
tagline: "Dinosaurs are cool",
favicon: "img/favicon.ico",
url: "https://your-docusaurus-site.example.com",
baseUrl: "/",
organizationName: "facebook",
projectName: "docusaurus",
onBrokenLinks: "throw",
onBrokenMarkdownLinks: "warn",
i18n: {
defaultLocale: "en",
locales: ["en"],
},
//...
};
export default config;

Core Fields:

  • title: The title of your Docusaurus site.
  • tagline: A short tagline or description for your site.
  • favicon: The path to the favicon icon for your site.
  • url: The URL where your site will be hosted.
  • baseUrl: The base URL path for your site (typically /).
  • organizationName and projectName: These are used for certain Docusaurus features like the edit button.
  • onBrokenLinks and onBrokenMarkdownLinks: These control how Docusaurus handles broken links.
  • i18n: This object configures internationalization (i18n) settings like the default locale and supported locales.

Theme Configuration

The themeConfig object is where you define your site’s look and feel:

const config = {
//...
themeConfig: {
image: "img/docusaurus-social-card.jpg",
navbar: {
title: "My Site",
logo: {
alt: "My Site Logo",
src: "img/logo.svg",
},
items: [
{
type: "docSidebar",
sidebarId: "tutorialSidebar",
position: "left",
label: "Tutorial",
},
{ to: "/blog", label: "Blog", position: "left" },
{
href: "https://github.com/facebook/docusaurus",
label: "GitHub",
position: "right",
},
],
},
footer: {
style: "dark",
links: [
{
title: "Docs",
items: [
{
label: "Tutorial",
to: "/docs/intro",
},
],
},
{
title: "Community",
items: [
{
label: "Stack Overflow",
href: "https://stackoverflow.com/questions/tagged/docusaurus",
},
{
label: "Discord",
href: "https://discordapp.com/invite/docusaurus",
},
{
label: "Twitter",
href: "https://twitter.com/docusaurus",
},
],
},
{
title: "More",
items: [
{
label: "Blog",
to: "/blog",
},
{
label: "GitHub",
href: "https://github.com/facebook/docusaurus",
},
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} My Project, Inc. Built with Docusaurus.`,
},
prism: {
theme: prismThemes.github,
darkTheme: prismThemes.dracula,
},
},
//...
};
  • navbar: Define logo, title, and navigation items.
  • footer: Set style, links, and copyright notice.
  • prism: Choose a syntax highlighting theme.

Presets and Themes

Docusaurus uses presets to bundle plugins and themes:

const config = {
//...
presets: [
[
"classic",
{
docs: {
sidebarPath: "./sidebars.js",
editUrl: "link/to/edit/page",
},
blog: {
showReadingTime: true,
editUrl: "link/to/edit/page",
},
theme: {
customCss: "./src/css/custom.css",
},
},
],
],
//...
};
  • docs: Set path and sidebar configuration.
  • blog: Configure blog features.
  • theme: Apply custom CSS for fine-tuned styling.

This is a quick rundown of the docusaurus.config.js file. The great thing about this file is that you can customize various aspects of your documentation by modifying it, without needing to touch other files or write additional code. For example, If you change the title and tagline to something else, it will update the homepage and other parts where these values are used. The following example demonstrates this:

const config = {
title: "Semaphore",
tagline: "Build, Test, Deploy - At Lightning Speed",
//...
};

This will update the homepage title and tagline without having to touch src/pages/index.js directly.

Creating Pages

Docusaurus allows you to create standalone pages in the src/pages directory. These pages are different from documentation pages and can be used for custom content such as a homepage, about page, or any other static content you need. To create a new page, navigate to the src/pages folder. If you need to create an about page, for example, you would create about.jsx file inside that folder:

touch src/pages/about.jsx

Add content to about.jsx file:

import React from "react";
import Layout from "@theme/Layout";
function About() {
return (
<Layout title="About Us">
<div style={{ padding: "20px" }}>
<h1>About Us</h1>
<p>
Semaphore CI is a cloud-based continuous integration and delivery platform that accelerates software development. We help teams build test, and deploy code faster and more reliably.
</p>
</div>
</Layout>
);
}
export default About;

Now visit: http://localhost:3000/about

This code defines a simple React component for the about page. The layout component from Docusaurus provides the site’s header, footer, and other layout features. While it is convenient to use Javascript/JSX to create pages, you also have the option to use Markdown or React MDX.

Add the Page to the Navbar

To make about page accessible via the navigation bar, you need to update the docusaurus.config.js file in the root directory.

const config = {
//...
themeConfig: {
image: "img/docusaurus-social-card.jpg",
navbar: {
title: "My Site",
logo: {
alt: "My Site Logo",
src: "img/logo.svg",
},
items: [
{
type: "docSidebar",
sidebarId: "tutorialSidebar",
position: "left",
label: "Tutorial",
},
{ to: "/blog",
label: "Blog", position: "left" },
// Add new Navlink here
{ to: "about", label: "About", position: "left" },
{
href: "https://github.com/facebook/docusaurus",
label: "GitHub",
position: "right",
},
],
},
//...
},
//...
};

This configuration adds a link to the About page in the navigation bar. Check the browser to see the change.

Creating documentation page

The documentation content in Docusaurus is typically located in the docs directory of your project. Let’s start fresh by deleting the default files in the docs folder. Next, we will rename the Tutorial navbar item to Docs to better represent a real documentation website. Open the docusaurus.config.js file and locate the themeConfig.navbar.items section. Update the label field of the docSidebar item from Tutorial to Docs:

const config = {
themeConfig: {
navbar: {
items: [
// ...
{
type: "docSidebar",
sidebarId: "tutorialSidebar",
position: "left",
label: "Docs",
},
// ...
],
},
},
};

To create a new documentation page, make sure you are in docs folder. Create a new Markdown or React MDX file. For this example, let’s create a file named welcome.mdx:

touch docs/welcome.mdx

Open welcome.mdx in your text editor and add the following content:

---
id: welcome
title: Welcome
description: This is a description for the welcome page
slug: /welcome
---
# Welcome to my DocThis is my first documentation page in Docusaurus.

The new welcome page link would appear in the documentation sidebar. You can also navigate to localhost:3000/docs/welcome in the browser to access the page.

Understanding the structure of a Documentation Page

Docusaurus documentation pages consist of two main parts:

  • Front Matter: The top section enclosed in triple dashes (---). It contains metadata like the unique id, title, description, slug, and other details about the page. This metadata guides how Docusaurus generates the sidebar, page titles, URLs, and more. Think of it like the <head> section in HTML. The metadata is not visible in the rendered documentation page but is used by Docusaurus to generate the sidebar navigation, page titles, URLs, and other features.
  • Main Content: This is where you write the actual documentation using Markdown syntax. Here, you can structure the content with headings, code blocks, images, and take advantage of the full expressiveness of Markdown.

Customizing the Documentation Page

You can customize the behavior and appearance of your documentation pages using various front-matter fields. For example, to change the order of a page in the sidebar, you can use the sidebar_position field:

---
id: welcome
title: Welcome
description: This is a description for the welcome page
slug: /welcome
sidebar_position: 1
---
# Your Markdown content goes here

Setting sidebar_position: 1 will move the page to the first position in the sidebar. Other accepted front matter fields include:

  • sidebar_label: The label displayed in the sidebar navigation for this document.
  • hide_title: A boolean flag to hide the title at the top of the document page.
  • pagination_label: A label for the pagination navigation at the bottom of the document page.
  • custom_edit_url: A custom URL for the “Edit this page” link.
  • keywords: An array of keywords related to the document, used for search engine optimization.
  • image: A relative path or URL to an image that can be used as a preview or social media thumbnail for the document.
  • hide_table_of_contents: A boolean flag to hide the table of contents for the document.
  • toc_min_heading_level: An integer value (1-6) that specifies the minimum heading level to be included in the table of contents.
  • toc_max_heading_level: An integer value (1-6) that specifies the maximum heading level to be included in the table of contents.
  • pagination_next: A label for the “Next” pagination link.
  • pagination_prev: A label for the “Previous” pagination link.

Grouping Documentation Pages

You can group pages in Docusaurus by creating a subfolder inside the docs directory. Let’s say you want to create a “Getting Started” category with pages for “Installation” and “Integration”. First, create the subfolder inside docs directory:

mkdir docs/getting-started

Inside the getting-started folder, create a JSON file named _category_.json. This file defines the sidebar navigation structure for the category. Add the following:

{
"label": "Getting Started",
"position": 1,
"link": {
"type": "generated-index"
}
}

The label specifies the category name, and position determines its order in the sidebar. The link field creates an index page for the category, listing all its pages.

Adding Pages to the Category

Next, create the pages for the category:

touch docs/getting-started/installation.md docs/getting-started/integration.md

Add content to installation.md page with appropriate front matter:

---
id: installation
title: Installation
sidebar_position: 1
---
# InstallationLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Add content to integration.md:

---
id: integration
title: Integration
sidebar_position: 2
---
# IntegrationLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Now, these pages will be grouped under the “Getting Started” category in the sidebar, with the index page listing them.

Using React in Docusaurus

Docusaurus allows you to embed React components directly in your documentation pages, giving you the flexibility to create interactive and dynamic content. This is possible thanks to MDX (Markdown with JSX), which allows you to use JSX within your Markdown files. This feature is particularly useful when you want to showcase live examples, abstract away repetitive code, or add complex interactivity to your docs. To use React components in your documentation pages, ensure your documentation file format is .mdx instead of .md. For this example, we are going to create a basic component named ColorBox. In your project’s root directory, navigate to the src/componentsfolder (create it if it doesn’t exist) and create a .js or .jsx component:

mkdir -p src/components
touch src/components/ColorBox.jsx

Add content to the file:

import React from 'react';
const ColorBox = ({ color }) => (
<div
style={{
backgroundColor: color,
width: '100px',
height: '100px',
display: 'inline-block',
margin: '10px'
}}
/>
);
export default ColorBox;

You can then use this component in your MDX file. This example uses the previously created welcome.mdx file for demonstration:

---
id: welcome
title: Welcome
description: This is a description for the welcome page
slug: /welcome
---
import ColorBox from '@site/src/components/ColorBox';# Welcome to my Doc
This is my first documentation page in Docusaurus.
<ColorBox color="red" />
<ColorBox color="blue" />
<ColorBox color="green" />

Note: The @site alias in the import statement is a special path alias in Docusaurus that points to your project’s root directory.

In the browser, you should see the custom component render along with Markdown content:

This approach allows you to create rich and interactive documentation that goes beyond static text and images. You can embed live code editors, interactive diagrams, or even small applications directly in your documentation pages.

Pro Tip: Although React components can greatly enhance your documentation, use them judiciously. For simple content, plain Markdown is often more maintainable and performs better. Reserve React components for interactive elements or complex visualizations that can’t be achieved with standard Markdown.

Versioning Documentation

Docusaurus has built-in support for versioning documentation which allows you to maintain multiple versions of your documentation and provide version-specific content to your users. To enable versioning, you first need to configure your Docusaurus project to support it.

Open docusaurus.config.js and update it to include versioning settings. Add the following to the docs field in the config file:

const config = {
//...
presets: [
[
"classic",
{
docs: {
// ....
lastVersion: "current",
versions: {
current: {
label: "Next",
path: "next",
},
},
},
//...
},
],
],
//...
};

This configuration sets up versioning with a Next version, which is the default label for the current version of your documentation.

To create an initial version of your documentation, run the following command:

npm run docusaurus docs:version 1.0.0

This will create a version-1.0.0 directory inside the new versioned_docs directory and a versions.json file in the project directory. You sould have folder structure like this:

my-docs/
├── docs/
│ └── ... # Current documentation files
├── versioned_docs/
│ └── version-1.0.0/
│ └── ... # Copied documentation files for version 1.0.0
├── versions.json # Metadata file for versioning
├── ...

Creating New Versions

To add more versions of your documentation, run the docs:version command with the new version number:

npm run docusaurus docs:version 1.1.0

This will create a new directory version-1.1.0 inside the versioned_docs folder, and the documentation files from the docs directory will be copied into it. The new version will also be added to the versions.json file. After creating a new version, you should have an updated folder structure like this:

my-docs/
├── docs/
│ └── ... # Current documentation files
├── versioned_docs/
│ ├── version-1.0.0/
│ │ └── ... # Documentation files for version 1.0.0
│ └── version-1.1.0/
│ └── ... # Documentation files for version 1.1.0
├── versions.json
├── ...

You can continue updating the documentation files in the docs directory, and when you are ready to create a new version, simply run the docusaurus docs:version command again with the new version number.

Managing Versions

The versions.json file in the root directory contains metadata about the different versions of your documentation. It looks like this:

["1.0.0", "1.1.0"]

You can manually edit this file to add or remove versions as needed.

Adding Version Dropdown to Navbar

After setting up versioning, you can update the navbar in docusaurus.config.js to display a version dropdown menu. Open the config file, in config.themeConfig.items, add the following:

const config = {
//...
themeConfig: {
//...
items: [
// ...
{
type: "docsVersionDropdown",
position: "right",
},
],
},
//...
};

This will show a version dropdown menu in the navigation bar.

Pro Tip: If your documentation changes infrequently, versioning may introduce unnecessary complexity. In most cases, maintaining a single, up-to-date version of your documentation is simpler and more effective.

Exploring Plugins

Docusaurus has a thriving ecosystem of plugins that can extend the functionality of your documentation site. Let’s look at an example of integrating Translation and Internationalization plugins in Docusaurus.

Translation and Internationalization

Docusaurus has built-in support for internationalization (i18n) that allows you to create a multi-language documentation website. This feature enables you to reach a global audience by providing translated content in multiple languages. Let’s set up and manage translations in Docusaurus project.

Configuring Locales

The first step is to configure the locales (languages) you want to support in your documentation site. Open the docusaurus.config.js file and locate the i18n object. By default, it should look like this:

i18n: {
defaultLocale: 'en',
locales: ['en'],
},

To add a new locale, for example, French (fr), update the locales array:

i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
},

Translating Content

After configuring the locales, you can start translating your content. Docusaurus expects translations to be placed in a specific directory structure within the project-root/i18n folder. Create a directory named i18n in the root folder:

mkdir -p i18n

Docusaurus provides a CLI that you can use to manage translations. To extract the translatable content from your Markdown and React components, run the following command

npm run write-translations

This command, by default, will generate only the English (en) locale directory along with translatable JSON files inside the i18n directory. To instruct the command to generate a French locale or your desired locale, you will have to specify it by providing the --locale flag. For example, to generate the French (fr) locale, run:

npm run write-translations -- --locale fr

This will generate the fr locale directory containing translatable files inside the i18n directory. You should have a folder structure like this:

my-docs/
└── i18n
├── en
│ ├── code.json
│ ├── docusaurus-plugin-content-blog
│ │ └── options.json
│ ├── docusaurus-plugin-content-docs
│ │ ├── current.json
│ │ ├── version-1.0.0.json
│ │ └── version-1.1.0.json
│ └── docusaurus-theme-classic
│ ├── footer.json
│ └── navbar.json
├── fr
│ ├── code.json
│ ├── docusaurus-plugin-content-blog
│ │ └── options.json
│ ├── docusaurus-plugin-content-docs
│ │ ├── current
│ │ │ ├── version-1.0.0
│ │ ├── current.json
│ │ ├── version-1.0.0.json
│ │ └── version-1.1.0.json
│ └── docusaurus-theme-classic
│ ├── footer.json
│ └── navbar.json
//....

Every JSON file in the locale represents a specific aspect of your documentation where you can manually translate the content. For instance, current.json is responsible for translating general text content and UI elements like the site title, description, and theme labels. The navbar.json and footer.json in the i18n/fr/docusaurus-theme-classic directory are where you translate the navbarand footer content to French, respectively. You can explore all the JSON files and translate as many aspects as you want to create a fully localized documentation website.

To translate your documentation content, you have to copy your documentation content from the docs files to i18n/fr/docusaurus-plugin-content-docs/current/. Copy all the files inside the docs directory:

mkdir -p i18n/fr/docusaurus-plugin-content-docs/current
cp -r docs/* i18n/fr/docusaurus-plugin-content-docs/current/

After copying, you have to manually translate the content to your desired language, which in this case is French. The structure for the multilingual setup should look like this:

my-docs/
└── i18n
├── en
│ ├── code.json
│ ├── docusaurus-plugin-content-blog
│ │ └── options.json
│ ├── docusaurus-plugin-content-docs
│ │ ├── current.json
│ │ ├── version-1.0.0.json
│ │ └── version-1.1.0.json
│ └── docusaurus-theme-classic
│ ├── footer.json
│ └── navbar.json
├── fr
│ ├── code.json
│ ├── docusaurus-plugin-content-blog
│ │ └── options.json
│ ├── docusaurus-plugin-content-docs
│ │ ├── current
│ │ │ ├── getting-started
│ │ │ │ ├── installation.md
│ │ │ │ ├── integration.md
│ │ │ ├── welcome.mdx
│ │ │ ├── version-1.0.0
│ │ ├── current.json
│ │ ├── version-1.0.0.json
│ │ └── version-1.1.0.json
│ └── docusaurus-theme-classic
│ ├── footer.json
│ └── navbar.json

For transaltion to take effect, you will need to restart your server and add the --locale flag.

npm run start -- --locale fr

Now, when you refresh the browser, you should see something like this when you visit localhost:3000/fr/docs/next/welcome:

Enabling the Language Dropdown

After configuring the locales and providing translations, you can enable a language dropdown in your site’s navigation bar. Open docusaurus.config.js file and locate the themeConfig.navbar.items array. Add the following item:

const config = {
themeConfig: {
navbar: {
items: [
// ...
{
type: "localeDropdown",
position: "right",
},
],
},
},
};

This will add a language dropdown to the right side of the navigation bar, allowing users to switch between the configured locales.

Routing and URL Structure

Note: Internationalization works a little differently in the dev environment compared to production. In production, you can seamlessly switch between the provided languages without any issues. However, in the development environment, you need to specify the locale when starting the server, and it only supports one language at a time. This means if you start your dev server in the French locale and switch to, say, English, you will get a 404 error. In production, this will not be an issue as Docusaurus automatically handles the routing and URL structure for your translated content. When a user selects a different locale from the language dropdown, Docusaurus will load the corresponding translated content and update the URL to reflect the selected locale. For example, if a user visits the /docs/welcome URL on the English (en) site, and then switches to the French (fr) locale, Docusaurus will load the French translation of the welcome.mdxfile and update the URL to /fr/docs/welcome.

More about about Plugins

Earlier, we learned how to leverage the localization plugin, but that is just a small taste of what plugins can do for your Docusaurus site. There are tons of useful plugins that make things easier. Let’s say you need to integrate Google Analytics into your project. Here is how:

Install the Plugin

First, install the required plugin by running this command:

npm install --save @docusaurus/plugin-google-gtag

With the plugin installed, you can configure it in your docusaurus.config.js file. Look for the presets array and find the presets entry. Then add this gtag config inside it:

const config = {
//...
presets: [
[
'classic',
/** @type {import('@docusaurus/preset-classic').Options} */

({
gtag: {
trackingID: 'G-999X9XX9XX',
anonymizeIP: true,
},
docs: {
sidebarPath: './sidebars.js',
lastVersion: 'current',
versions: {
current: {
label: 'Next',
path: 'next',
},
},
},
//...
}),
],
],
//...
};

Make sure to swap out G-999X9XX9XX with your actual Google Analytics tracking ID. The anonymizeIP option helps with privacy by anonymizing visitor IP addresses before sending data. Google Tag is disabled in the development environment. This behavior is intentional to prevent unnecessary analytics data from being sent while you’re developing and testing your site locally. Google Tag will be enabled in the production environment and your site should be able to collect analytics data. You can use tagassistant.google to confirm if your Google Analytics implementation is working correctly using your production link.

You can explore more plugins from Docusaurus official website to extend the capabilities and functionality of your documentation website.

Deploying Your Docusaurus Website

After building your documentation website, there is nothing more satisfying than seeing it live and running. Docusaurus provides a CLI to streamline deployment, making the process straightforward. You can also deploy your site to cloud services like Vercel or Netlify, which offer additional features and ease of use.

Using Docusaurus CLI for Deployment

Docusaurus includes a built-in command-line tool that simplifies the deployment process. To deploy your site using the Docusaurus CLI:

Ensure that your site is built and ready for deployment. Run the following command to create a production-ready build:

npm run build

This will generate static files in the build directory, which can be served by any static site hosting service.

To ensure everything works as intended, test your build locally by running the following command:

npm run serve

This will start a local server and you can view your site by navigating to the provided URL. Make sure to check all pages and features to verify that they are functioning correctly.

Deploying to Cloud Services

For more flexibility, deploy your Docusaurus site to cloud services like Vercel or Netlify, which offer seamless integration with Git and automated deployment workflows. Follow their setup guides:

Pro Tip: Fix broken links in your Docusaurus project to prevent deployment failures.

Earlier in this tutorial, we deleted all default files and folders in the docs directory. This may have created broken links, particularly references to docs/intro. To ensure smooth deployment:

  1. Open docusaurus.config.js
  2. Navigate to config.themeConfig.footer.links.items
  3. Delete or Replace /docs/intro with a working link or use the relative path /.
const config = {
//...
themeConfig: {
footer: {
style: "dark",
links: [
{
title: "Docs",
items: [
{
label: "Tutorial",
to: "/docs/intro", // Resolve this broken link
},
],
},
//...
],
},
},
//...
};

Repeat this process for src/pages/index.js, updating any similar references.

Wrapping Up

We have covered a lot of ground in this guide. We touched on key concepts such as initializing a new Docusaurus project, creating documentation, versioning, integrating plugins, deploying a Docusaurus website, and more. Building a documentation website is not a simple task, but tools like Docusaurus take a lot of that complexity out of the equation by providing streamlined workflows and essential features out of the box. While this guide aims to provide a solid foundation, there is still much more to explore with Docusaurus. There are limitless possibilities for customization through Docusaurus’ extensive ecosystem of plugins and themes.

Feel free to clone my working repository in parallel to the fresh, walk-thru provided here. Please do reach out to me for any questions/clarifications or bugfixes!

Originally published at https://semaphoreci.com on July 17, 2024.

--

--

Semaphore

Supporting developers with insights and tutorials on delivering good software. · https://semaphoreci.com