Accessing MDX Frontmatter in Gatsby

November 7, 2018

While building this site in Gatsby using MDX, I noticed that there wasn't any documentation on how to include data from the frontmatter of an MDX document in the document's page layout.

Though this isn't anywhere in the gatsby-mdx docs (that I can tell), there's an example of how to use it in the repo. Frontmatter is passed to the layout component in props.pageContext.frontmatter. This means you can do things like this in your markdown document:

---
title: My Page
---
This is the content

And in your layout component, you can grab the frontmatter:

const MyPageLayout = (props) => {
    return (
        <div>
            <h1>{props.pageContext.frontmatter.title}</h1>
            <div>
                {props.children}
            </div>
        </div>
    ); 
};

On this blog's home page I use frontmatter of all the MDX documents, which includes things like title, date, and preview text, to render the list of blog post previews.

Tweet This
Get New Posts Via Email
Picture of me with a corgi

Noah Gilmore

I'm Noah, a software developer based in the San Francisco Bay Area. I focus mainly on full stack web and iOS development

  • 💻 I co-founded Replo, a no-code platform for e-commmerce
  • ✍️ You can read technical posts on my blog
  • 📱 I wrote an app which lets you create transparent app icons called Transparent App Icons
  • 🧩 I made a puzzle game for iPhone and iPad called Trestle
  • 🎨 I wrote a CoreImage filter utility app for iOS developers called CIFilter.io
  • 👋 Please feel free to reach out on Twitter / 𝕏