Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Change MDX Page URL TO Slugs In Gatsby

The [TODO: Code shorthand span ] creates URLs based off the directory structure of files. This is how to setup Gatsby with an [TODO: Code shorthand span ] directory that lets you put [TODO: Code shorthand span ] keys in the frontmatter to control the URL.

### Modules

bash
npm install gatsby-plugin-mdx
npm install gatsby-source-filesystem

### src/layouts/blog - post - v1.js

javascript
import { graphql } from 'gatsby';
import { MDXRenderer } from 'gatsby-plugin-mdx';
import React from 'react';

export const query = graphql`
  query($slug: String!) {
    mdx(frontmatter: { slug: { eq: $slug } }) {
      frontmatter {
        title
        slug
      }
      body
    }
  }
`;
const Post = ({ data: { mdx: post } }) => {
  const { title } = post.frontmatter;
  const { body } = post;
  return (
    <div>
        <h1>{title}</h1>
        <MDXRenderer>{body}</MDXRenderer>
    </div>
  );
};
export default Post;

### src/mdx - pages/example - dir/hello - world.mdx

title: Hey, MDX
date: February 15, 2021
slug: /hello-world-example-of-code

This is the [TODO: Code shorthand span ] file.

### gatsby - config.js

javascript
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `mdx`,
        path: `${__dirname}/src/mdx-pages/`,
      },
    },
    `gatsby-plugin-mdx`,
  ],
}

### gatsby - node.js

javascript
exports.createPages = async ({ actions, graphql, reporter }) => {
  const { createPage } = actions
  const blogPostV1Layout = require.resolve(`./src/layouts/blog-post-v1.js`)
  const result = await graphql(`
    {
      allMdx {
        edges {
          node {
            frontmatter {
              slug
            }
          }
        }
      }
    }
  `)
  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }
  result.data.allMdx.edges.forEach(({ node }) => {
    createPage({
      path: node.frontmatter.slug,
      component: blogPostV1Layout,
      context: {
        slug: node.frontmatter.slug,
      },
    })
  })
}