How to parse Frontmatter data in a Next MDX Blog

Frontmatter is used to specify metadata in markdown files. In this article, I will show you how to parse this metadata while rendering the MDX content.

markdown
---
title: This is frontmatter
---
 
# Frontmatter example

Installation

We will be using two libraries for this, remark-frontmatter and remark-mdx-frontmatter.

bash
npm i remark-frontmatter remark-mdx-frontmatter

Usage

I use multiple remark plugins in my application. This is how I apply them in next.config.mjs.

typescript
import nextMDX from '@next/mdx'
 
import { recmaPlugins } from './src/mdx/recma.mjs'
import { rehypePlugins } from './src/mdx/rehype.mjs'
import { remarkPlugins } from './src/mdx/remark.mjs'
 
const withMDX = nextMDX({
  options: {
    remarkPlugins,
    rehypePlugins,
    recmaPlugins,
  },
})

In remark.mjs, I enable the plugins by adding them to the exported array.

typescript
import { mdxAnnotations } from 'mdx-annotations'
import remarkFrontmatter from 'remark-frontmatter'
import remarkGfm from 'remark-gfm'
import remarkMdxFrontmatter from 'remark-mdx-frontmatter'
 
export const remarkPlugins = [
  mdxAnnotations.remark,
  remarkGfm,
  remarkFrontmatter,
  remarkMdxFrontmatter,
]