June 20, 2019
Add comments to a static Gatsby blog with Disqus
gatsbytipsJAMstacktutorialThis is an easy one!
Static websites have huge advantages but you can run into some issues when trying to sort out relatively simple tasks such as blog comments or form handling.
Blog comments need to be stored somewhere. This would usually be on your own server but of course this isn't available with a static site. Some solutions such as Staticman store the comments on your own repo which is great if you're concerned about allowing third parties to handle your user generated content.
For simplicity and ease of use Disqus is a great option however. I use Disqus comments on this blog. Have a scroll down to the bottom and take a look to see how they work in practice. It's free for small, personal and non-commercial sites so a perfect option for most small blogs.
How to set it up.
First you need to make an account on disqus.com. Then you need to register your site. When you fill out a 'Website Name' it will show you a suggested shortname. You can click 'Customize Your URL' below this to pick a unique, memorable shortname. This is the name disqus will use to identify your website so its an important one!
Okay, once that is done we can go back to your code. Install the disqus-react package:
npm install --save disqus-react
Lovely.
Now for most blogs on gatsby we will have a template called something like blogpost.js
that is used for all the programmatically generated posts. As we want comments at the end of every post this is the perfect place.
Import the discussion component at the top:
import { DiscussionEmbed } from 'disqus-react';
Then in the render method we need a little bit of config. I've just used information I had anyway via my graphQL query for identifier and title:
const blogPost = (props) => {
const post = props.data.markdownRemark;
const disqusShortname = "myshortname"; const disqusConfig = { identifier: post.id, title: post.frontmatter.title, };
return (
...
Finally (yes really), you just need to add the actual discussion component somewhere on the page and use the config we set up.
Note: You can only have one instance of this component per page. I'm not sure why you'd want to put multiple on but you can't sorry.
<DiscussionEmbed shortname={disqusShortname} config={disqusConfig} />
And there we have it! A super easy comment system for your blog. One of my favourite things about Disqus is how familiar it's UI is. It looks professional and somehow seems to merge beautifully with your website so it doesn't look like you've just stuck something in an iframe.
If you found this helpful, try it out by commenting below!