Problem
By default, you can't add a comment system to a static generated site unless you use a third party help. As a developer using GitHub API to give our personal site a comment system is something fun and sometimes useful to do.
Solution
There are two different option that you can choose , it's either giscus or utterances, the difference is that giscus utilize GitHub discussion API, while utterances utilize GitHub issues
Goal
In this post, I will share step-by-step how to utilize Giscus to give our Next.js site a comment system.
Step 1: Enable GitHub discussion
- On GitHub.com, navigate to the main page of the repository.
Under "Start a new discussion," edit the template to align with the resources and tone you want to set for your community.
Step 2: Enable Giscus
Head to https://github.com/apps/giscus and enable giscus in your desired repository
Step 3: Get your repository API key
You can access your GitHub details via GitHub GraphQL API , you can access it here and then login with your GitHub account.
query {
repository(owner: "melvnl", name:"melvinliu.com"){
id
discussionCategories(first:10) {
edges {
node {
id
name
}
}
}
}
}
Basically, we are just making a request via GraphQL query to GitHub API to fetch our repository id, and our list of ten first discussion categories and its details (id, and name). The result will be something like this.
{
"data": {
"repository": {
"id": "R_kgDOGjYtbQ",
"discussionCategories": {
"edges": [
{
"node": {
"id": "DIC_kwDOGjYtbc4CA_TR",
"name": "Announcements"
}
},
{
"node": {
"id": "DIC_kwDOGjYtbc4CA_TS",
"name": "General"
}
},
{
"node": {
"id": "DIC_kwDOGjYtbc4CA_TU",
"name": "Ideas"
}
},
{
"node": {
"id": "DIC_kwDOGjYtbc4CA_TT",
"name": "Q&A"
}
},
{
"node": {
"id": "DIC_kwDOGjYtbc4CA_TV",
"name": "Show and tell"
}
}
]
}
}
}
}
Step 4: Install @giscus/react package
yarn add @giscus/react
or
npm i @giscus/react
Step 5: Import and use Giscus component
import { Giscus } from "@giscus/react";
export default function Comment() {
return (
<Giscus
repo="melvnl/melvinliu.com"
repoId="R_kgDOGjYtbQ"
category="General"
categoryId="DIC_kwDOGjYtbc4CA_TS"
mapping="pathname"
reactionsEnabled="0"
emitMetadata="0"
theme="dark"
/>
);
}
It will render a GitHub comment widget where other developer can sign in using their GitHub account to comment through GitHub Discussion API.
That's it folks! Hope this tutorial help, and happy hacking!
Reference:
https://giscus.app/
https://graphql.org/
https://www.freecodecamp.org/news/graphql-vs-rest-api/
You can find me on
Twitter: https://twitter.com/mlven23
GitHub: https://github.com/melvnl
LinkedIn: https://www.linkedin.com/in/melvin-liu/
Top comments (3)
Giscus is a great application, so I plan to create a detailed blog describing how to add it to my blog site at rw-community.org/blog
Very helpful
What if I put my article in markdown? Can I use giscus but have different comments on each article?