Customizing Blog Post Paths in Gatsby: A Step-by-Step Guide

2023-01-14

Are you tired of using the folder structure and file name of your markdown files as the path for your blog posts in Gatsby? Do you want more control over the path of your blog posts and make them more meaningful for your users and for SEO? Look no further!

In this guide, we will show you step-by-step how to customize the path of your blog posts in Gatsby. By the end of this guide, you will have a better understanding of how Gatsby generates the paths for your blog posts, and how you can use a custom path that is based on the post's title and date.

The first step is to install the slugify package. This package is used to create a URL-friendly string that can be used as the path for the blog post. You can install it by running the following command:

npm install slugify

Once the package is installed, you can import it in your gatsby-node.js file, as shown in the example code:

const slugify = require("slugify")

Next, you need to modify the onCreateNode function. This function is responsible for creating the slug field that is used as the path for the blog post. Instead of using the createFilePath function to generate the path, you can use a custom string that is defined using the slugify package to create the path using the post's title and date.

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = `/${new Date(node.frontmatter.date).toISOString().split('T')[0]}-${slugify(node.frontmatter.title, {
      lower: true,
      strict: true,
    })}`

    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}

In this example, the post's title is passed to the slugify function and the result is then used in the path. The date is also used to make the path unique.

Finally, you need to update the createPage function in the createPages function to use the custom path. Instead of passing in post.fields.slug as the path, you can use the custom path you defined in onCreateNode function.

createPage({
    path: post.fields.slug,
    component: blogPost,
    context: {
      id: post.id,
      previousPostId,
      nextPostId,
      slug: post.fields.slug,
    },
  });

With these changes, you can now have more control over the path of your blog posts, and make them more meaningful for your users and for SEO. Now, you can have a path that contains the post's title and date, which can be more readable for the user and more SEO friendly.

Try this out in your own Gatsby project and see the difference it makes! Happy coding!