DEV Community

Steven Mercatante
Steven Mercatante

Posted on • Updated on • Originally published at

Add a Published Field to Your Gatsby Posts to Control Their Visibility

The Problem

After converting my site to Gatsby, I quickly realized I needed a way to manage draft posts - pieces of writing I started, but for whatever reason weren't ready to be released publicly. Gatsby makes your posts public by default - as soon as you create that Markdown file and build your site, your post is available for all to see.

The Solution?

Easy! Throw a draft: true|false flag in the post's frontmatter, update the page query to only fetch pages where draft === false, and call it a day. Or, maybe not...

The Real Solution

The problem with the draft flag is that it's not explicit enough for this use case. The post will still be made public if I either forget to include the draft flag, or if it has a typo (e.g dratf: false).

Let's flip the conditional on its head and check if a published flag is true instead. What if I forget to add that flag, or have a typo (👋 publisehd)? The post doesn't appear until I fix the flag. This is a minor annoyance, but not as bad compared to if I accidentally publish something that isn't ready to be released.

The Code

Here's the frontmatter for this post - nothing crazy going on:

title: Manage Draft Posts in Gatsby
slug: '/manage-draft-posts-in-gatsby/'
tags: gatsby
published: false

And here's my page query:

query {
    filter: { frontmatter: { published: { eq: true } } }
    sort: { fields: [frontmatter___date], order: DESC }
  ) {
    edges {
      node {
        fields {
        frontmatter {
          date(formatString: "MMMM DD, YYYY")

That frontmatter: { published: { eq: true } } line in the filter block is where the magic happens.

A few things to keep in mind:

  • you'll need to restart your Gatsby dev server after adding new fields to frontmatter before you can query them
  • adding a published flag has implications if you have Previous Article and Next Article links: you need to make sure you're not linking to unpublished articles. I'll show you how I handle that in the future article. Stay tuned, friends!

👋 Enjoyed this post?

Join my newsletter and follow me on Twitter @mercatante for more content like this.

Top comments (0)