Parse Markdown Frontmatter In MDX, Remark, and Unified

phuctm97

Minh-Phuc Tran

Posted on December 25, 2020

Parse Markdown Frontmatter In MDX, Remark, and Unified

Today I created a small Unified/Remark plugin called remark-parse-frontmatter to help easily parse frontmatter in a Markdown or MDX document using either mdxjs or remarkjs or unifiedjs.

In case you don't know what is Unified/Remark is, Unified provides an interface for processing content like Markdown, HTML, JSX, etc, in an extremly modular design which allows writing and using plugins easy (but sometimes also feel a bit fragmented).

What is frontmatter in Markdown?

Frontmatter is the first block in a Markdown document that starts and ends with a line ---. Frontmatter defines a Markdown document's metadata.

For example, this is the frontmatter of this article you're reading:

---
title: Parse Markdown Frontmatter In MDX, Remark, and Unified
description: >-
  Leverage Unified/Remark plugin ecosystem to easily parse frontmatter in your
  Markdown or MDX documents.
tags: [markdown, javascript, react, plugin]
published time: 2020-12-25
---
Enter fullscreen mode Exit fullscreen mode

Markdown frontmatter is supported by Github and most popular code editors which help writing and maintaining them more fun.

Parse frontmatter with remark-parse-frontmatter

remark-parse-frontmatter provides 2 essential features when working with frontmatter:

  • Parses the YAML content of a markdown and turns that into a JavaScript object for usage.

  • Validates the object using revalidator.

This plugin requires plugin remark-frontmatter to be applied first (which reads the text and turns into a syntax tree, not a JSON object, and has no validation).

const processor = remark()
  .use(require("remark-frontmatter"))
  .use(require("remark-parse-frontmatter"))
  .freeze();

const file = processor.processSync(`
---
title: Hello, World!
---
`);

console.log(file.data.frontmatter);
Enter fullscreen mode Exit fullscreen mode

⬇️

{
  title: "Hello, World!"
}
Enter fullscreen mode Exit fullscreen mode

Remember to first install the plugin:

yarn add remark-parse-frontmatter
Enter fullscreen mode Exit fullscreen mode

Check out the NPM package and the plugin's repository for more details.

💖 💪 🙅 🚩
phuctm97
Minh-Phuc Tran

Posted on December 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related