Back to blog

How to Add Comments to Docusaurus: A Step-by-Step Guide

Enhance your documentation or blog by learning how to add comments to Docusaurus. We compare top tools and walk you through the entire integration process. How to Add Comments to Docusaurus: A Step-by-Step Guide is an EchoThread guide for site owners evaluating privacy-first comments, moderation, migration, performance, and reader engagement. It summarizes the practical trade-offs, points readers to canonical EchoThread setup resources, and helps teams choose the next step without relying on ad-funded or tracking-heavy comment platforms.

Docusaurus has established itself as one of the most powerful and popular static site generators for technical documentation, product wikis, and developer blogs. Its speed, React-based architecture, and out-of-the-box Markdown support make it an exceptional choice for publishing content. However, static sites are inherently one-way communication channels. To turn your documentation or blog into a dynamic, interactive space, you need to add comments to Docusaurus.

Adding a discussion layer allows readers to point out outdated code, ask clarifying questions, and share their own implementations. In this comprehensive guide, we will walk through the architecture of Docusaurus, explore how to safely inject custom code using "swizzling," and compare modern commenting options to help you choose and implement the perfect docusaurus comment system for your site.

---

Why Add Comments to Docusaurus?

For many open-source projects, startups, and technical writers, documentation is not just a manual—it is the heart of their community. When you allow users to leave comments directly on your docs and blog posts, you unlock several powerful benefits:

1. Real-Time Feedback and Crowdsourced Accuracy

No matter how rigorous your editorial process is, technical documentation can fall out of date. APIs change, dependencies update, and edge cases emerge. By adding a comment system, you give your power users a direct line to point out issues, suggest corrections, or provide alternative code snippets. This crowdsourced feedback loop significantly reduces the maintenance burden on your core engineering or documentation team.

2. Significant SEO Advantages

Search engines love fresh, relevant content. When users discuss your articles, they naturally use long-tail keywords, error codes, and specific technical queries that you might not have included in the original text. This user-generated content (UGC) is indexed by search engines, boosting your visibility. To understand this dynamic deeper, you can explore how blog comments provide substantial SEO benefits by continually updating static pages with relevant keyword-rich text.

3. Reduced Support Ticket Volume

When developers encounter a bug or configuration error, their first instinct is often to search your documentation. If they find a comment thread where another developer encountered the exact same issue and solved it, they get their answer instantly. This self-service resolution prevents repetitive support tickets, GitHub issues, and Discord inquiries from overwhelming your team.

---

Understanding Docusaurus Architecture: Swizzling and Custom Components

Before writing code, it is essential to understand how Docusaurus handles customization. Because Docusaurus compiles your Markdown into a highly optimized, single-page React application, you cannot simply paste an arbitrary HTML script tag into your Markdown files and expect it to work seamlessly across page transitions.

Instead, Docusaurus uses a mechanism called Swizzling.

In the context of Docusaurus, "swizzling" allows you to customize a theme component by bringing it into your own site's source directory (typically src/theme/). Once swizzled, Docusaurus will prioritize your custom version of the component over the default one provided by the theme package (such as @docusaurus/theme-classic). For a complete overview of the swizzling CLI and its configurations, refer to the Docusaurus Swizzling Documentation.

Wrapping vs. Ejecting Components

When you swizzle a component, the Docusaurus CLI gives you two choices:

  • Wrapping: This creates a wrapper around the original theme component. It imports the original component and allows you to render extra markup or logic before or after it. Wrapping is highly recommended because it is safe and upgrade-friendly; if the underlying theme component is updated in a future Docusaurus release, your site will receive those updates automatically.
  • Ejecting: This copies the entire source code of the theme component into your project. While this gives you absolute control to rewrite the component from scratch, it makes upgrading Docusaurus difficult, as your ejected component will not receive upstream bug fixes or enhancements.

Identifying the Target Components

To implement a commenting system, you must target the specific components where discussions belong:

  • BlogPostItem: The component responsible for rendering individual blog posts. Wrapping this component allows you to append comments to the bottom of every blog post automatically.
  • DocItem: The component that renders standard documentation pages. If you want to allow discussions on your API guides or tutorials, you will wrap this component.
---

How to Add Comments to Docusaurus Using a Modern Commenting System

Let's walk through the exact, step-by-step process to safely add comments to Docusaurus by wrapping the BlogPostItem component. This workflow applies to almost any modern, React-compatible commenting system.

Step 1: Swizzle the BlogPostItem Component

Open your terminal, navigate to your Docusaurus project root, and run the following command to wrap the classic theme's blog post item:

npm run swizzle @docusaurus/theme-classic BlogPostItem -- --wrap

If you are using Yarn or pnpm, run:

yarn swizzle @docusaurus/theme-classic BlogPostItem --wrap
# or
pnpm swizzle @docusaurus/theme-classic BlogPostItem --wrap

The CLI will create a new file in your project directory: src/theme/BlogPostItem/index.js (or .tsx if your project uses TypeScript). The generated code will look similar to this:

import React from 'react';
import BlogPostItem from '@theme-original/BlogPostItem';

export default function BlogPostItemWrapper(props) {
  return (
    <>
      <BlogPostItem {...props} />
    </>
  );
}

Step 2: Create a Custom Comments React Component

Instead of bloating your swizzled theme file with inline scripts, it is best practice to isolate your commenting widget logic in its own component. Create a new file at src/components/Comments.js:

import React, { useEffect, useRef } from 'react';
import { useColorMode } from '@docusaurus/theme-common';

export default function Comments() {
  const containerRef = useRef(null);
  const { colorMode } = useColorMode();

  useEffect(() => {
    // Logic to load your commenting script goes here
    // We will dynamically create a script tag or load an iframe
  }, [colorMode]); // Re-run when light/dark mode changes

  return <div ref={containerRef} className="comment-container" style={{ marginTop: '3rem' }} />;
}

Step 3: Securely Configure Environment Variables

Most modern commenting platforms require a Site ID or API key. Rather than hardcoding these sensitive values into your repository, store them in your environment variables. Create a .env file in your root folder:

DOCUSAURUS_COMMENT_SITE_ID=your_actual_site_id_here

In your docusaurus.config.js, expose this variable via the customFields property so it can be accessed within your React frontend:

module.exports = {
  // ... other configs
  customFields: {
    commentSiteId: process.env.DOCUSAURUS_COMMENT_SITE_ID,
  },
};

You can then access this in your React components using the useDocusaurusContext hook:

import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

const { siteConfig } = useDocusaurusContext();
const siteId = siteConfig.customFields.commentSiteId;

Step 4: Verify Your Installation Locally

Import your custom Comments component into your swizzled BlogPostItem wrapper. Ensure comments only render on individual blog post pages (and not on the main blog list page) by checking the isBlogPostPage metadata:

import React from 'react';
import BlogPostItem from '@theme-original/BlogPostItem';
import { useBlogPost } from '@docusaurus/theme-common/internal';
import Comments from '@site/src/components/Comments';

export default function BlogPostItemWrapper(props) {
  const { isBlogPostPage } = useBlogPost();

  return (
    <>
      <BlogPostItem {...props} />
      {isBlogPostPage && <Comments />}
    </>
  );
}

Run npm run start to spin up your local development server. Navigate to an individual blog post and verify that the commenting container mounts correctly at the bottom of the page.

---

Step-by-Step Guide: Integrating Giscus as a Docusaurus Comment System

One popular open-source option for developer-centric sites is Giscus. The docusaurus giscus integration leverages GitHub Discussions as a backend database, allowing developers to comment on your site using their GitHub accounts.

How Giscus Works

When a user visits a page on your site, Giscus searches for a GitHub Discussion mapped to that page's URL or title. If it doesn't find one, it creates a new discussion automatically when the first comment is submitted. The comments are loaded directly from GitHub via a secure iframe, keeping your database hosting costs at zero.

Prerequisites for Giscus

Before writing code, you must configure your GitHub repository to support the Giscus App:

  1. Ensure your repository is public (Giscus cannot read discussions on private repositories).
  2. Enable Discussions in your repository settings (under the "Features" section).
  3. Install the Giscus GitHub App and grant it access to your public repository.
  4. Create a specific Discussion Category (e.g., "Announcements" or "Comments") that allows open replies.

Configuring Giscus in Docusaurus

Once your repository is configured, you can build your Giscus component. First, install the official React wrapper for Giscus:

npm install @giscus/react

Next, implement the component in your src/components/Comments.js file:

import React from 'react';
import Giscus from '@giscus/react';
import { useColorMode } from '@docusaurus/theme-common';

export default function Comments() {
  const { colorMode } = useColorMode();

  return (
    <div style={{ marginTop: '3rem' }}>
      <Giscus
        id="comments"
        repo="your-github-username/your-repo-name"
        repoId="R_kgDOHxxxxx"
        category="Comments"
        categoryId="DIC_kwDOHxxxxx"
        mapping="pathname"
        term="Welcome to my Docusaurus comments!"
        reactionsEnabled="1"
        emitMetadata="0"
        inputPosition="top"
        theme={colorMode === 'dark' ? 'dark' : 'light'}
        lang="en"
        loading="lazy"
      />
    </div>
  );
}

Pros and Cons of Giscus

While Giscus is an excellent choice for some sites, it comes with distinct tradeoffs:

Pros Cons
100% free with no ads or tracking scripts. Strict GitHub Requirement: Users must have a GitHub account to comment. This alienates non-technical readers.
Supports rich Markdown, code blocks, and emoji reactions natively. GitHub API Limits: Under heavy traffic, API rate limits can occasionally cause comments to load slowly or fail to render.
Data is stored safely on GitHub, eliminating database maintenance. No custom moderation: You are tied to GitHub's default moderation tools, which lack advanced spam filtering for blog platforms.
---

Why Look for a Docusaurus Disqus Alternative?

Historically, Disqus was the default recommendation for adding comments to static sites. However, modern web standards and privacy regulations have driven developers to seek a modern docusaurus disqus alternative.

The Drawbacks of Legacy Commenting Systems

Legacy platforms often inject significant JavaScript payloads, third-party trackers, and programmatic ad auctions onto your page. When you embed these scripts on your site, you introduce several critical issues:

  • Severe Performance Bloat: These scripts can drastically increase your Time to Interactive (TTI) and degrade your Google Lighthouse scores.
  • Privacy and GDPR Violations: Legacy systems frequently drop tracking cookies on your visitors' browsers to build advertising profiles. This forces you to add complex cookie consent banners to your site to avoid heavy regulatory fines, in accordance with GDPR cookie compliance guidelines. You can read more about how to stay compliant in our guide to choosing a GDPR-compliant commenting system.
  • Intrusive, Unaligned Advertising: The ads injected by legacy systems are often low-quality, distracting, and completely unaligned with your content, hurting your brand authority. If you want to maintain a clean aesthetic, you need a Disqus alternative without ads.

Criteria for a Great Modern Commenting System

To keep your Docusaurus site lightning-fast and trustworthy, your commenting system should ideally meet these criteria:

  1. Ad-Free Experience: The system should avoid displaying intrusive banners or monetizing user data through third-party tracking.
  2. Privacy-First Architecture: It should operate without relying on non-essential tracking cookies, helping you maintain compliance with global privacy regulations like GDPR and CCPA.
  3. Lightweight Payload: The script bundle should be highly optimized and minimal to ensure your Core Web Vitals and page load speeds remain pristine.
  4. Seamless React/Docusaurus Integration: It should dynamically adapt to your light/dark mode transitions and work flawlessly with single-page application routing.
---

Why EchoThread is the Perfect Way to Add Comments to Docusaurus

If you need a professional, lightning-fast, and privacy-respecting way to add comments to Docusaurus, EchoThread is the ideal solution. Built specifically for modern static site generators and Jamstack architectures, EchoThread provides the perfect bridge between developer-friendly integration and a smooth, frictionless experience for non-technical users.

Key Features of EchoThread

  • Privacy-First & GDPR Compliant: We do not track users, sell personal data, or drop intrusive tracking cookies. Your site remains compliant without annoying cookie banners.
  • Blazing Fast Performance: Our optimized, lightweight script is designed to be highly efficient, helping ensure your Lighthouse scores remain strong.
  • Robust Moderation Tools: Access automated spam filtering, word blacklists, and manual approval queues to keep your discussions healthy and constructive.
  • Native Dark Mode Support: EchoThread automatically detects and matches your Docusaurus theme transitions.

How to Integrate EchoThread into Docusaurus

Integrating EchoThread into your swizzled Docusaurus component is incredibly straightforward. First, sign up for an EchoThread account and retrieve your Site ID from your dashboard. Then, update your src/components/Comments.js file with the following clean React implementation:

import React, { useEffect } from 'react';
import { useColorMode } from '@docusaurus/theme-common';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

export default function Comments() {
  const { colorMode } = useColorMode();
  const { siteConfig } = useDocusaurusContext();
  const siteId = siteConfig.customFields.commentSiteId || "YOUR_ECHOTHREAD_SITE_ID";

  useEffect(() => {
    // Prevent script duplication
    if (document.getElementById('echothread-script')) {
      if (window.EchoThread) {
        window.EchoThread.setTheme(colorMode);
      }
      return;
    }

    const script = document.createElement('script');
    script.id = 'echothread-script';
    script.src = 'https://cdn.echothread.io/client/embed.js';
    script.async = true;
    script.setAttribute('data-site-id', siteId);
    script.setAttribute('data-theme', colorMode);

    document.body.appendChild(script);

    return () => {
      // Clean up script on component unmount to prevent memory leaks
      const existingScript = document.getElementById('echothread-script');
      if (existingScript) {
        existingScript.remove();
      }
    };
  }, [colorMode, siteId]);

  return (
    <div style={{ marginTop: '3rem', width: '100%' }}>
      <div id="echothread-comments" />
    </div>
  );
}

With this simple integration, EchoThread will automatically render a beautiful, responsive comment thread at the bottom of your blog posts or documentation pages. To see how EchoThread compares to other tools, check out our comparative analysis on EchoThread vs Disqus.

---

Best Practices for Moderating and Managing Your New Comments

Once you successfully configure your docusaurus comment system, you must actively manage the discussions. An unmoderated comment section can quickly degrade into a space for spam, self-promotion, and toxic behavior.

1. Establish a Clear Comment Policy

Set clear community expectations from day one. Publish a dedicated comment policy page detailing what behavior is acceptable (e.g., constructive criticism, helpful answers) and what will result in immediate banishment (e.g., personal attacks, affiliate link spam). You can download and adapt our blog comment policy template to establish clear guidelines for your readers.

2. Deploy Robust Automated Spam Protection

Static sites are prime targets for automated spam bots trying to build backlinks. Ensure your commenting system uses modern, server-side spam prevention. EchoThread, for example, utilizes advanced heuristics to identify and quarantine spam before it ever hits your public pages. Learn more about how to protect your site dynamically in our deep dive on stopping blog comment spam effectively.

3. Support Markdown and Code Blocks

Because Docusaurus is primarily used for technical writing, your readers will inevitably want to share terminal commands, code snippets, or logs. Make sure your commenting system supports Markdown rendering and syntax highlighting inside comment inputs, allowing developers to share code cleanly without unreadable formatting issues.

---

Frequently Asked Questions

Can I add comments to both Docusaurus docs and blog posts?

Yes. Because of Docusaurus's modular architecture, you can add comments to any page type. To add comments to blog posts, swizzle and wrap the BlogPostItem component. To add comments to documentation pages, swizzle and wrap the DocItem component. The integration process is identical for both.

Does adding a comment system slow down my Docusaurus site?

It depends entirely on the system you choose. Legacy platforms like Disqus load dozens of tracking scripts and ads, which will severely impact your performance. However, modern, lightweight systems like EchoThread are highly optimized, loading minimal payloads asynchronously so your core page content loads instantly without blocking the main thread.

How do I prevent spam in my Docusaurus comments?

The most effective way to prevent spam is to use a commenting platform with built-in, automated spam detection. Additionally, you should enable manual moderation queues for comments containing external links, establish keyword blacklists, and require user authentication (social login or verified email) to prevent anonymous bot submissions.

Is there a GDPR-compliant docusaurus comment system?

Yes.

---

Ready to build a thriving community around your Docusaurus site without sacrificing speed or privacy? Try EchoThread today and experience a modern, lightweight commenting system built for the static web.

Ready to try EchoThread?

Free for your first site. Set up in under a minute.

Create free account