Adding cover images to your Gatsby blog

October 20, 2019

If you decide to use GatsbyJS for your blog I would highly recommend starting with a simple starter and building up. Gatsby blog starter introduces a handful of concepts and is substantially easier to understand than some of the more advanced starters. One feature that adds some personality to your site is featured images for your posts - both on the post list and on the post itself. The rest of this article walks through the steps needed to go from the Gatsby blog starter to having featured images on the post list and post pages.

Add the metadata to a post

The first thing to do is update our GraphQL schema, which we do by adding a new property to the blog post frontmatter. To ensure our featured image is also accessible we’ll specify some alt text. As an example, we’ll add the existing image from the ‘Hello World’ post as a featured image. You can give the property any name you want - I’ve used featuredimage which contains a src and an alt.

If you are running gatsby develop you need to restart that task, as schema changes (or more broadly any changes that require re-running gatsby-node.js) aren’t hot-reloadable.

You can verify this has worked by browsing the GraphQL schema at http://localhost:8000/___graphql and inspecting the allMarkdownRemark nodes - the frontmatter should now have a featuredimage property. The image below shows that our salty egg post has a featured image, and the other two posts have nothing.

I’m using fluid (which generates images that stretch to fill a fluid container), though we could have also used fixed, which is for images that have (unsurprisingly) a fixed width and height. The gatsby-image docs are a great place to start if you want to dig into the details.

To get the image on our page we now need to update the markup. First up we need to import gatsby-image:

import Img from"gatsby-image"

To add the image to each post we first extract the featuredimage from our node:

And there we have it, a rather functional looking image on our post list!

Adding the image to the post page requires repeating the same steps in the \src\templates\blog-post.js file. Depending on your layout you may want to tweak the settings (max size/height - or maybe you’ll want to override the quality and have higher quality images on your post page?).

Further reading

There is a lot of documentation for images in Gatsby, and it isn’t always obvious where to go. I’d suggest working through the following: