MDX frontmatter in Gatsby

March 28, 2020

MDX is an incredible toolkit that allows you to write JSX in your Markdown files; creating opportunities for more dynamic and interactive experiences in your content. An example of how MDX could be used:

When I transitioned this site over to MDX, I immediately went to work creating a better Code component, and slew of shortcodes that allowed me to remove a few remark plugins I wanted to bring in-house.

The challenge

Storing additional types of data in Markdown frontmatter is a pretty common-practice; especially with CMS solutions like Netlify CMS. This allows us seperate out chunks you may want to present in different ways - like so:

But - what if you have Markdown content within your frontmatter - or better yet, MDX?

Solutions within Gatsby for normal Markdown frontmatter previously led me down the path of creating a runtime component to parse the Markdown strings that would be queried on the frontend:

The upside to this method was that I could add as many remark plugins as needed - with the obvious downside being the bloat it would add to our bundle. The other downer was gatsby-remark-* plugins that may have additional logic inside of gatsby-browser.js and gatsby-ssr.js wouldn't be accessible in this component. This implementation was never ideal.

With MDX thrown in the mix, @mdx-js/runtime was closer to a plugin 'n play solution, but with the downside of being quite large and not recommended for most usecases.

The solution

After struggling with a few different suggestions across the Gatsby community, I came across a method that was straight-forward and easy to extend - enter createSchemaCustomization. This allows us to customize Gatsby’s GraphQL schema by creating type definitions, field extensions or adding third-party schemas.

The above functionality does a few things:

  1. Creates a new, mdx field extension that automatically attaches the MDX internals to the fields it is assigned to.
  2. Funnels our type definitions down to our specific items frontmatter field.
  3. Assigns the newly created mdx field to our value; which is what we want transformed into MDX.

When querying this data with Gatsby's built-in graphiql tool, what's returned is the transformed body content, ready to be consumed by <MDXRenderer />.