Gatsby
Up and Running with Gatsby: Markdown & MDX

Creating Page Slugs

PRO

We can tap into Gatsby's build process and create page slugs for our events.

Even though we created our first Markdown file in the content/events folder and we've told Gatsby to pull it into the GraphQL for our site, we don't have any way of transforming that data into pages and routes. We need Gatsby to programatically do this for us: every time it seems a file in that folder, we want it to create a route like /events/2019-11-12-game-night and a corresponding page based on a layout.

The first part of that is the route, also known as a slug. That's what we're going to learn in this video. Then, we'll cover the page creation in the next video.

At the root of the project, create a new file called gatsby-node.js. This is a configuration file that lets us affect the Node build process.

To create the slug, we'll use the Gatsby createFilePath function, which translates file names into useable URLs.

Here's the final code in the video:

const { createFilePath } = require("gatsby-source-filesystem")

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  if (node.internal.type === "Mdx") {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: "slug",
      node,
      value: `/events${value}`,
    })
  }
}

In this function, we tell Gatsby to add a new slug field to each MDX node of the GraphQL data that contains /events and the file name (which won't include the extension).

Next, let's create the actual pages.