Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Frontmatter in React MDX Markdown File

I have set up a next.js markdown blog using mdx: https://mdxjs.com/.

I would like to be able to reference data in the frontmatter section within the mdx file itself. Something like this:

// my-file.mdx
---
title: "My blog post title"

# {title} // should be replaced by the frontmatter title

Now, this does not work. It does NOT replace {title} with the title found in the frontmatter (i.e,. My blog post title). What I am wondering is whether or not there is a way to do this and, if so, how?

Thanks.

like image 714
Moshe Avatar asked Feb 27 '26 12:02

Moshe


2 Answers

Check out the Docusaurus docs page on available exports. For your example, title is available as <p>{contentTitle}</p>. For more specific keys, you can use something like:

<p>{Object.entries(frontMatter).find(frontmatter => frontmatter[0] === 'description'}</p>

to retrieve, in this example, the description. (Replace html <p> tag with whatever tag is appropriate.)

like image 52
s-santillan Avatar answered Mar 01 '26 01:03

s-santillan


I'm using MDX with Next.js 13 and spent too much time looking for a complicated solution for accessing frontmatter within MDX, like using remark-mdx-frontmatter as per https://mdxjs.com/guides/frontmatter/. But if you're using gray-matter with Next 13 for your frontmatter, the frontmatter object is exposed to the MDX markdown body by default. So if your MDX has this frontmatter:

---
date: 'September 9, 2023'
---

You can access it from the MDX body with:

{frontmatter.date}
like image 45
VanAlbert Avatar answered Mar 01 '26 01:03

VanAlbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!