Add Disqus comments to a Gatsby blog

April 07, 2018

This blog is a static site built using GatsbyJS. This means you can’t add a comment field like on a normal blog engine such as Wordpress, because there’s no dynamic server to handle it. That’s not a problem though, as we can use a third party comment plugin, such as Disqus. This is how I added Disqus comments to this site. You should be able to see them down below.

The nice thing about Gatsby is that every site is a React site, so we can use React components. There’s a nice React component for Disqus, so it’s simple to add it to our blog. First go to disqus.com and register your site. You’ll need the shortname later. Then install the package using Yarn or NPM:

yarn add disqus-react

My blog is based on the gatsby-starter-blog template, so the specific files will refer to those, but you should be able to quite easily apply this to any other Gatsby site. I’ve converted mine to TypeScript, but the syntax differences are minimal.

Now you’ve installed the package, you need to add the comments field to the blog posts. Add it to src/templates/blog-post.js (or blog-post.tsx if you’ve TypeScriptified yours like mine).

import { DiscussionEmbed } from "disqus-react";

Add your Disqus configuration at the top of the render() method:

  render() {
    const post = this.props.data.markdownRemark;
    const siteTitle = get(this.props, "data.site.siteMetadata.title");
    const { previous, next } = this.props.pathContext;
    const disqusShortname = "yourdisqusshortname";
    const disqusConfig = {
      identifier: post.id,
      title: post.frontmatter.title,
    };

…then add the comments box at the bottom of the page:

            {next && (
        <li>
            <Link to={next.fields.slug} rel="next">
            {next.frontmatter.title}</Link>
        </li>
        )}
    </ul>
    <DiscussionEmbed shortname={disqusShortname} config={disqusConfig} />
    </div>

Now view the page and there should be a nice comment box at the bottom. Try it out by leaving me a comment below!


I'm Matt Kane. I've made high-speed flashes and beekeeping software, but I mostly spend my time making web and mobile apps with React and TypeScript. Follow me on Twitter and Github.