Setting up syntax highlighting with Ghost blog is not too complicated, because it is handled client side with the prism.js library. Getting it to work with Gatsby is a bit more complicated and not yet fully supported out of the box.

There are plugins for Gatsby that implement prism.js, like gatsby-remark-prismjs, but this would require that your post content is available in Gatsby as Markdown file before you build your project. Instead the content of a post/page is set as inner HTML of the Content component. Therefore the gatsby-remark-prismjs plugin won't work. I found hints to a working solution in a discussion on github.

Syntax highlighting in Gatsby with a Ghost Backend

  1. install prismjs
npm install prismjs

2. Add a theme for prismjs to gatsby-browser.js


3. Implement syntax highlighting in your content component. Include prism.js and the plugins you want in your file (more about plugins can be found in the prism.js documentation). Add Prism.highlightAll() to your componentDidMount function. This will trigger the syntax highlighting client side after loading your component. This requires that you use a class component to display your content. If you also want to have line numbers, every <pre> element before a <code> element needs to be of class line-numbers. I use a very hacky solution, where I use a RegEx to replace all occurances of <pre> with <pre class="line-numbers">.

... imports
import Prism from 'prismjs'
import "prismjs/plugins/line-numbers/prism-line-numbers.js"

class Post extends React.Component {

  		... constructor = RegExp("<pre><code", "g"), '<pre class="line-numbers"><code')


      return (
      		<PostStyled dangerouslySetInnerHTML= {{ __html: }}/>

After completing these steps your posts should now have syntax highlighting with line numbers enabled.



Markus Wallinger

I am currently finishing my Master Thesis at the Vienna University of Technology. One the side I work as a freelance software developer, based in Vienna and Tyrol.