Stocks crunch

How To Add Draft Posts To A Gatsby Blog

How To Add Draft Posts To A Gatsby Blog

2019-05-26 15:02:35

I need to exclude specific posts from displaying in production in my blog build with Gatsby and mark them as drafts during development. I will describe how to achieve this goal so you can do this too in less than 5 minutes.

This post is a part of «10 Better with Gatsby» series where I share my personal experience on tuning and tweaking Gatsby.

The End Result

List of posts in development:

List of posts in production:

RequirementsShow all posts in developmentHide draft posts in productionRender released and draft posts differently in developmentMark post as released automatically if its date is after build timeMark post as released manually in md files.

I found a plugin but could not achieve everything I needed. Mine open sourced solution can be found here:

gatsby-plugin-released

It allows you to add release functionality via config and skip part of this article. Also there are additional options you can use. Visit plugins README to learn more.

Overview

Step #1. Adding new fields to GraphQL

We will add a field called released based on:

date field from markdown filereleased field from markdown fileprocess.env.NODE_ENVtimezonebuild time (a moment in time when the build happens)

Also we will add a field called releasedNotForced. Similar to releasedbut with process.env.NODE_ENV been ignored.

This step is abstracted into gatsby-plugin-released

Step #2. Update GraphQL queries to respect the released value

We should exclude drafts from building and displaying.

Step #3. Update components to render drafts differently.

To have a nice visual distinction and feel good about it. :)

ExecutionStep #1. Adding new fields to GraphQL

The goal of this step is to add fields to node.frontmatter.fields to use via GraphQL. Gatsby offers a special API for this. What we need is to modify gatsby-node.js file.

We will add two fields:

released fieldreleasedNotForced field that act just like released but ignores the process.env.NODE_ENV variable.Why adding two fields?

Just in case you are wondering.

In development mode we may want to force posts to be rendered without editing any GraphQL queries. It is done by forcing released to be truebased on process.env.NODE_ENV. Thus in a development mode we loose the original value we may want to use in a component code to have a visual distinction between drafts and released posts.

The way to preserve this is to always set the released field in a markdown file. But it was so nice to have this value be calculated automatically based on date.

That is why I’ve added a releasedNotForced property — to preserve that value while forcing released to be true.

Remember, if you don’t want to mess with your config just use this plugin.