Enea Xharja Logo

Add a Published Filter To Your Gatsby MDX Posts

A published filter is a great feature to filter your draft post, so that you can keep working on a it until it's ready to be shared with everyone. We can implement this feature by adding a boolean value named published in the frontmatter of your post. If we set this boolean to true, the post will be visible to the world! Otherwise, the post is visible only to you.

Let's implement this feature in a Gatsby post.

Add published to the frontmatter

We can start by adding the published boolean to the frontmatter of all our existing posts:

mdx
1---
2slug: '/your-post-slug'
3date: '2020-09-01'
4published: true
5title: 'The best post ever'
6---

Adding the filter to the GraphQL queries

Once we have added the boolean value to all our post, we need to update the GraphQL queries in order to filter out any post where published is set to false.

Inside your gatsby-node.js file, update the queries that fetch your MDX posts and the one for your tags (if you have this feature implemented on your website, if not check out my post for more info):

js
1{
2 allMdx(filter: { frontmatter: { published: { eq: true } } }) {
3 edges {
4 node {
5 excerpt
6 frontmatter {
7 title
8 slug
9 date(formatString: "MMMM DD, YYYY")
10 tags
11 }
12 }
13 }
14 }
15 tagsGroup: allMdx(
16 filter: { frontmatter: { published: { eq: true } } }
17 limit: 2000
18 ) {
19 group(field: frontmatter___tags) {
20 fieldValue
21 }
22 }
23}

Additionally, if you have an RSS Feed integrated into your website, you need to modify also the gatsby-config.js file:

js
1feeds: [
2 {
3 // ...
4 query: `
5 {
6 allMdx(
7 sort: { order: DESC, fields: [frontmatter___date] },
8 filter: { frontmatter: { published: { eq: true } } }
9 ) {
10 edges {
11 node {
12 excerpt
13 html
14 frontmatter {
15 title
16 slug
17 date(formatString: "MMMM DD, YYYY")
18 }
19 }
20 }
21 }
22 }
23 `,
24 // ...
25 },
26],

In case you need some help with adding an RSS Feed to your Gatsby MDX blog, I wrote about it here.

Once we have updated the GraphQL queries contained into the Gatsby configuration files, it's time to update the query that fetches for our posts inside the postTemplate file:

js
1export const getPosts = graphql`
2 query getPosts($skip: Int!, $limit: Int!) {
3 allMdx(
4 limit: $limit
5 skip: $skip
6 sort: { order: DESC, fields: [frontmatter___date] }
7 filter: { frontmatter: { published: { eq: true } } }
8 ) {
9 edges {
10 node {
11 excerpt
12 frontmatter {
13 title
14 slug
15 date(formatString: "MMMM DD, YYYY")
16 tags
17 }
18 }
19 }
20 }
21 }
22`;

For reference, have a look at my postListTemplate.js on GitHub.

Finally, for those of you who have integrated tags and categories into your website, remember to update also the GraphQL queries inside your tags page and tagTemplate component.