Featured images

Posted on 20th January 2020

A stock image of a MacBook and some JavaScript

On most websites a blog post will have a featured image. Sometimes it's a huge full width monster taking up your entire screen, sometime it's a bit more sedate and sits in front of your article content (like this image is).

It's also usually the featured image that is shown in a thumbnail linking to the article from another page, or appears in the preview when you share the url on twitter/facebook, etc.

I didn't have this on my site until now, I've been adding in my images by hand amongst the markdown, but I've noticed my sharing links looking a little plain, so I've decided to try and implement it using frontmatter variables in my posts and tweaking my template query to fetch it for me.

This is the only article on my site with one, but as I go on I will probably add more, which will probably be useful for an inevitable redesign. Here are some things I changed to make it work, you can follow along here, but the official Gatsby docs might see you better.

##Query changes

This was added inside the frontmatter part of the query on my page:

featured {
childImageSharp {
fluid(maxWidth: 800) {

And the following lines were added to my template above and in the rendered component (it should be obvious where these go in your js file, but if not let me know and I'll point you in the right direction):

import Img from 'gatsby-image';
const featuredImage = {
img: null,
alt: post.frontmatter.featuredAlt || ''
if (post.frontmatter.featured) {
featuredImage.img = post.frontmatter.featured.childImageSharp.fluid;
{featuredImage.img && (

All that remained was to add an additional piece of frontmatter to my post:

featured: ../images/featured-macbook.jpg

Et voilà! A featured image right at the top of my post and ready to be consumed by other pages and components - I won't put them on the homepage yet, but I'm definitely going to update my react helmet so that opengraph can see the image.

🙏 Special Thanks

Kudos for the photo by Clément H on Unsplash, keep up the great work!

Enjoyed this post? Feel free to share it with your audience using the links below:

Don't see your favourite social network on the list? Feel free to let me know and I'll get it added.


©2022 Pursuit of Loot. All rights reserved.