← Back to list

How to make MDX work for Gatsby

In this guide, we’ll show you how to configure and add MDX pages to your Gatsby website

Ahmad Souqi · 2023-04-17 21:59 · 0 claps · 1.5 min read
#gatsbyjs #mdx #gatsbyjs-blog
Open on Medium ↗

How to make MDX work for Gatsby

In this guide, we’ll show you how to configure and add MDX pages to your Gatsby website

Install the needed packages:

yarn add gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react

Update Gatsby Config: gatsby-config.js

    "gatsby-plugin-mdx",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "pages",
        path: `${__dirname}/src/mdx`,
      },
    },

Update Gatsby Node to create pages: gatsby-node.js

exports.createPages = async ({ actions, graphql }) => {
  const { data } = await graphql(`
    query {
      allMdx {
        edges {
          node {
            internal {
              contentFilePath
            }
            frontmatter {
              title
              path
            }
            id
          }
        }
      }
    }
  `)

  return data.allMdx.edges.map((edge) => {
    const {
      title,
      path,
    } = edge.node.frontmatter
    const {
      id,
      internal: { contentFilePath },
    } = edge.node

    const mdxPageTemplate = require.resolve("./src/components/MDXPageTemplate.tsx")

    actions.createPage({
      path,
      component: `${mdxPageTemplate}?__contentFilePath=${contentFilePath}`,
      context: { id, title },
    })
  })
}

This block of code will query all mdx edges and call action.createpage to create page from a component we specify, for this example will be MDXPageTemplate.tsx

Create your Template component for MDX pages: src/component/MDXPageTemplate.tsx

import * as React from "react"
import { MDXProvider } from "@mdx-js/react"
import Layout from "../components/layout"

const components = {
    /** Add your custom mdx component */
    p: (props) => <p style={{color: 'tomato'}} {...props}/>,
}

const MDXPageTemplate: React.FC<{ children: React.ReactNode, title: string }> = ({ children }) => {
    // TODO:: use title for SEO
    return (
        <Layout>
            <MDXProvider components={components}>{children}</MDXProvider>
        </Layout>
    )
}

export default MDXPageTemplate

Start Creating your MDX files: will add all mdx files in mdx folder to create pages _src ____mdx ______test.mdx

---
title: Test MDX Page
path: test
---

# Hello World MDX page

custom paragraph

Now you should see this page at: http://localhost:8000/test/

mdx page

mdx page

if you need to run it locally pull this github repo.


메타데이터
post_id
8d2c99ca4541
slug
how-to-make-mdx-work-for-gatsby-8d2c99ca4541
url
https://medium.com/@asouqi/how-to-make-mdx-work-for-gatsby-8d2c99ca4541
canonical_url
https://medium.com/@asouqi/how-to-make-mdx-work-for-gatsby-8d2c99ca4541
author_url
https://medium.com/@asouqi
status
ok
fetched_at
2026-06-10 21:21:38