Parse Markdown Frontmatter In MDX, Remark, and Unified

Minh-Phuc Tran

Minh-Phuc Tran on Dec 25, 2020





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

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()

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



  title: "Hello, World!"

Remember to first install the plugin:

yarn add remark-parse-frontmatter

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

Subscribe to the newsletter

Get emails from me about software development, SaaS, and early access to new articles.