DEV Community

Cover image for How to add Giscus comments to Docusaurus
m19v
m19v

Posted on • Edited on

How to add Giscus comments to Docusaurus

Goal

This post is a step-by-step description of how to add Giscus, a commenting system powered by GitHub Discussions, to a static website generated by Docusaurus.

Setup Giscus

Follow the steps in the sections of the current chapter to set up Giscus and connect it to the GitHub discussions.

Enable GitHub discussion

  • Create Github repository in your Github account where comments are stored in Discussion section.
  • In the main page of created repository go to Settings.
  • Under "Features" section, click "Set up discussions".
  • Edit the template in "Start a new discussion" and click "Start discussion".

Enable Giscus

  • Configure giscus in your GitHub account.
  • In Section "Repository access" add only created repository from previous step to be accessed by giscus and click "Save".

Get repository API key

  • Login with GitHub account in GraphQL API Explorer.
  • Use following query to fetch the id of created repository, discussion categories with its details (e.g. id and name). Note! Replace owner and name with your GitHub account name and name of repository you created.
query { 
  repository(owner: "nameOfYourGitHubAccount", name:"nameOfCreatedRepository"){
    id
    discussionCategories(first:10) {
      edges {
        node {
          id
          name
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The result json object will be similar to:

{
  "data": {
    "repository": {
      "id": "R_kgDOIVqhTg",
      "discussionCategories": {
        "edges": [
          {
            "node": {
              "id": "DIC_kwDOIVqhTs4CSSES",
              "name": "Announcements"
            }
          },
          {
            "node": {
              "id": "DIC_kwDOIVqhTs4CSSET",
              "name": "General"
            }
          },
          {
            "node": {
              "id": "DIC_kwDOIVqhTs4CSSEV",
              "name": "Ideas"
            }
          },
          {
            "node": {
              "id": "DIC_kwDOIVqhTs4CSSEX",
              "name": "Polls"
            }
          },
          {
            "node": {
              "id": "DIC_kwDOIVqhTs4CSSEU",
              "name": "Q&A"
            }
          },
          {
            "node": {
              "id": "DIC_kwDOIVqhTs4CSSEW",
              "name": "Show and tell"
            }
          }
        ]
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Create Giscus component

  • Install @giscus/react package
npm i @giscus/react
Enter fullscreen mode Exit fullscreen mode
  • Create Giscus Component, e.g. under /src/components/GiscusComponent as follows:
import React from 'react';
import Giscus from "@giscus/react";
import { useColorMode } from '@docusaurus/theme-common';

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

  return (
    <Giscus    
      repo="nameOfYourGitHubAccount/nameOfCreatedRepository"
      repoId="idOfCreatedRepo"
      category="General"
      categoryId="IdOfDiscussionCategory"  // E.g. id of "General"
      mapping="url"                        // Important! To map comments to URL
      term="Welcome to @giscus/react component!"
      strict="0"
      reactionsEnabled="1"
      emitMetadata="1"
      inputPosition="top"
      theme={colorMode}
      lang="en"
      loading="lazy"
      crossorigin="anonymous"
      async
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Create BlogPostItem component

  • Create BlogPostItem component to wrap blog posts with Giscus commenting system as follows:
npm run swizzle [theme name] [component name] -- --wrap

# Example:
npm run swizzle @docusaurus/theme-classic BlogPostItem -- --wrap
Enter fullscreen mode Exit fullscreen mode

This will create a BlogPostItem component under
src/theme. Edit index.js as follows:

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

export default function BlogPostItemWrapper(props) {
  const { metadata, isBlogPostPage } = useBlogPost()
  const isBrowser = useIsBrowser();

  const { frontMatter, slug, title } = metadata
  const { enableComments } = frontMatter

  return (
    <>
      <BlogPostItem {...props} />
      {(enableComments && isBlogPostPage) && (
        <GiscusComponent />
      )}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Note that the useBlogPost() Hook is used in BlogPostItem component to make activation of comments per blog post configurable. The key value enableComments: true must be added to your blog post md file in order to activate commenting for it. E.g.:

---
title: "Title of blog post"
authors: author
tags: [keywordOne, keywordTwo]
enableComments: true # for Gisqus
---
Enter fullscreen mode Exit fullscreen mode

I have enabled the comment function of current post in my page, which can be used as a demo. Feel free to hit the "Like" button if you found this post helpful, or post your question in the comment if you have one.

References

giscus.app

graphql.org

Add comment system to your static site with Giscus

Top comments (10)

Collapse
 
cavo789 profile image
Christophe Avonture

Excellent tutorial ! Hours of try-errors saved. Thank you ! 👍

Collapse
 
0420syj profile image
Wan Sim

Thanks for your post. It was easy to follow

Collapse
 
commenttool profile image
CommentTool

I did all that you described but there is no way to add a comment on the docusaurus page. Are you sure that there are not a few additional steps left out? Are there certain things to do to create a blog? I added a blog sub-directory manually and copied some files there but perhaps this should be done in a different way? Also what, if anything, should be done with the key generated by the GraphQL at docs.github.com/en/graphql/overvie... ? Does it need to be copied to some location in GitHub or elsewhere? Thanks

Collapse
 
m19v profile image
m19v
  1. Steps described in this post should be sufficient to add giscus comments to docusarus blog posts.
  2. To activate blogging feature of docusarus see please docusaurus.io/docs/blog
  3. To see why the comments are not being added please share the error message or your state of code in e.g. public repository.
Collapse
 
commenttool profile image
CommentTool

I was able to add the giscus comment feature to the blog feature, which I was able to add. (Everything worked fine after I renamed \src\components\GiscusComponent\GiscusComponent.js to index.js. Perhaps you might make this clearer.)

It looks great but is there a way to put the blog at the bottom of the page and not at the top right?

Thanks

Thread Thread
 
commenttool profile image
CommentTool

Hi!

Thanks for describing how to set up the giscus comment feature within a docusaurus blog. It works as advertised and we might implement it on our own product web site.

We do, however, have a couple of concerns. A GitHub account is necessary. Is there any way to 'vet' or restrict the GitHub accounts that are allowed to comment? If we make our docusaurus documentation publically available, anyone could make comments in the blog that would also be public. Individuals unfriendly to our company could make deliberately unhelpful if not malicious comments that might not be detected quickly.

We currently have our documentation behind a login so this is not an issue, but making it all public is something that we are considering. (Having our documentation behind a login means that were we to enable blog comments, our users would need 2 logins to make comments. That is a bit much to ask our customers.)

So the bottom line is that to make it easy to get user comments, we might want to make everything public BUT we would want to have some control over who is making the comments. Would anyone have any idea on how feasible this all is?

Thanks!

Thread Thread
 
m19v profile image
m19v

Hi,

yes, GitHub account to comment and a GitHub repository to store comments are needed. Hence Giscus is used if one just have a basic static web page that do not have authentication, backend with commenting system etc.

I do not think that GitHub have such a possibility to restrict a specific user to comment a discussion of the public repository. However you can moderate comments and conversations. See docs.github.com/en/communities/mod....

Regards!

Collapse
 
jerryi profile image
Kirill Vasin

Is is possible to add it to docs pages as well?

Collapse
 
m19v profile image
m19v • Edited

Hi,
I assume yes as Docusaurus has good architecture. E.g. the easiest way to have comments on docs is to just import GiscusComponent already created in current tutorial in MDX (see docusaurus.io/docs/markdown-featur...).
Otherwise use Swizzling (docusaurus.io/docs/swizzling) and plugin-content-docs (docusaurus.io/docs/api/plugins/@do...) to wrap right docs item with GiscussComponent. Check please docusaurus.io/docs/api/plugins/@do... if it is the right one.

Would be grad for any further details if you get it working. It might be also interesting for others.

Regards

Collapse
 
jerryi profile image
Kirill Vasin

Thanks! It did works so well using DocItem template. :)