Angelos Orfanakos

Add support for drafts in Gatsby

Gatsby does not ship with support for drafts in Markdown posts, but it’s pretty easy to implement it.

Note: This assumes you’ve already added support for Markdown pages.

Add the following to gatsby-node.js:

const { env } = require('process'); // eslint-disable-line no-undef

exports.onCreateNode = ({ node, actions }) => {
  // ...

  if (node.internal.type === 'MarkdownRemark') {    const listed =      node.frontmatter.draft !== true || env.NODE_ENV === 'development';    actions.createNodeField({      node,      name: 'listed',      value: listed    });  }
  // ...
};

Modify the page query of your index page in src/pages/index.js to include draft posts in development and exclude them in production:

query {
  allMarkdownRemark(
    filter: {      fields: { listed: { eq: true } }    }    sort: { fields: [frontmatter___date], order: DESC }
  ) {
    edges {
      node {
        # ...
      }
    }
  }
}

Repeat the process in gatsby-config.js if you’ve added an RSS feed.

Finally, add draft: true to the frontmatter of your draft posts and change it to false (or remove it altogether) when you want to publish them.