Same Con to Hoyci — too many choices —

A blog about Web development, usability and AI.

Howto: Draft Posts With Gridsome

 by Ville Säävuori

Gridsome is a Vue-based static site generator inspired by Gatsby. As of version 0.7 there is no official way to have a publishing flow that separates draft and published posts. For me this is a big deal as I like to iterate on my writings for several days or weeks before publishing them. Luckily, there is an easy way to add support for draft posts yourself.

Adding a New GraphQL Property

At the heart of a Gridsome site is a GraphQL data layer that you can use and manipulate in development mode. Gridsome fetches any sources you define into this GraphQL storage in development mode and during the build process writes the data into static files as instructed in your configuration.

The naive way of importing any data into Gridsome just adds it into the storage and it then respectively gets published as you build the site. A super simple way to implement draft functionality is to simply add an attribute to your data object and then filtering by this attribute when building the site.

Add the following javascript in a file called gridsome.server.js in the root of your Gridsome project:

module.exports = function(api) {
  api.loadSource(store => {
    if (process.env.NODE_ENV === 'production') {
      const posts = store.getContentType('Post')

      posts.data().forEach(node => {
        if (node.published !== true) {
          posts.removeNode(node.id)
        }
      })
    }
  })
}

(Change the Post ContentType to match whatever your source plugin typeName has been configured to in gridsome.configjs plugins section. The default for source-filesystem-plugin is FileNode.)

Now, when you run gridsome build, the API that loads your sources at build time filters out each post that hasn't got a published-attribute that evaluates to true. (Note that if you have a blog with lots of content and you don't want to add a new attribute to all of them, you might want to reverse the logic, for example to if (node.draft !== true). I like to explicitly mark published posts, YMMV.)

For Markdown and Front Matter content you can now add published: false to your post meta to be able to filter out draft posts in production. (Modifying other content sources is left to the reader.)

Follow @uninen on Twitter