Gareth Brown

Using GraphCMS and Remark with Gatsby

January 8, 2021

I got started with Gatsby as a tool to create and manage my blog. However very quickly I found writing local markdown files for posts was not a very convenient way of adding content. After a brief search on headless options to use as a CMS I settled on GraphCMS.

The basics for how to manage this were easily found here: I followed the video and then used the example as a reference when adding this to my own site.

The first decision was what to use to write the body of my posts, the options being rich text or markdown. I had a few posts already in markdown files so eventually settled on the markdown option so I could easily transfer them over. Plus I do like the markdown way of styling and was happy to keep it up.

The challenge with this was how to render it as html in on the page. I feel like this should have been easier than it was. The first option I looked at was using gatsby-transformer-remark which parser markdown files and converts them to HTML for you. This is what is used by default in Gatsby. However it only works with markdown in files, not in http responses.

After doing a bit of research into (, which is what gatsby-transformer-remark uses under the hood, I decided to use this.

I imported remark and remark-html straight into the blog post template, which has access to the blog post as returned from GraphCMS.

import remark from 'remark'
import html from 'remark-html'

The conversion from markdown to html was as simple as the code snippet below:

let blogBody = '';
      .process(post.body, function (err, file) {
        blogBody = String(file)

This was then used in the template using the following:

<div dangerouslySetInnerHTML={{ __html: blogBody }} />

React has kindly written this attribute to remind you that it's dangerous to render html straight onto the page but this is how Gatsby does it and as the page receives the data as markdown in the first place then what could possibly go wrong!

Now the writing of my blog should be an easier and more convenient experience.

Written by Gareth Brown who lives and works in Bristol, UK. You should follow him on Twitter