MDX Notes
What frontmatter is, how MDX uses it, YAML syntax you need to know, and how to get at that data in your components.
What is Frontmatter?
Frontmatter is a block of metadata at the very top of your file, wrapped in triple dashes (---). It holds structured info *about* your document — stuff like the title, author, tags, publish date — without showing up in the rendered output.
Think of it as a data layer for your MDX file. Your app reads this data to build navigation, generate SEO tags, sort posts by date, filter by category — all without touching the content itself.
The name comes from book publishing. "Front matter" is everything before the actual text: title page, copyright, table of contents.
# Your content starts here...YAML Syntax Fundamentals
Frontmatter uses YAML syntax. It's a human-readable format that relies on indentation and simple punctuation. Here's everything you need to know.
Basic Data Types
---
# Strings
title: "Hello World"
subtitle: Plain strings work too
multiline: |
This is a multiline
string that preserves
line breaks
# Numbers
views: 1500
rating: 4.5
# Booleans
draft: false
featured: true
# Dates
date: 2024-01-15
publishedAt: 2024-01-15T10:30:00Z
# Null values
reviewer: null
---Arrays and Lists
Nested Objects
---
seo:
title: "Custom SEO Title"
description: "A meta description for search engines"
image: "/images/og-cover.png"
sidebar:
position: "left"
collapsible: true
defaultOpen: true
---How Frontmatter Works in MDX
When your MDX file gets processed by a bundler or framework, the frontmatter is parsed separately from the content. The parser pulls out the YAML, turns it into a JavaScript object, and hands it off to your app.
The actual MDX content below the --- gets compiled into a React component. The frontmatter data usually shows up as a named export or gets passed as props — depends on your framework.
Processing Pipeline
Under the hood, most MDX tools use gray-matter to split frontmatter from content:
// How gray-matter processes your file
import matter from 'gray-matter';
const fileContent = fs.readFileSync('post.mdx', 'utf8');
const { data, content } = matter(fileContent);
// data = { title: "My Post", date: "2024-01-15", ... }
// content = "# Your content starts here..."Accessing Frontmatter Data
Here's how you actually use frontmatter data in the major frameworks.
In Next.js (App Router)
In Docusaurus
Docusaurus parses frontmatter automatically. You just reference it:
---
title: My Document
sidebar_label: Getting Started
sidebar_position: 1
---
# {frontMatter.title}
This document was last updated on {frontMatter.date}.In Gatsby
// gatsby-node.js creates pages, and GraphQL queries expose frontmatter
export const query = graphql`
query BlogPostQuery($slug: String!) {
mdx(frontmatter: { slug: { eq: $slug } }) {
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
author
tags
}
body
}
}
`;Frontmatter vs Exports
MDX gives you two ways to attach data to a document: frontmatter (YAML) and named exports (JavaScript). They solve different problems.
---
title: "Using Frontmatter"
---
export const meta = {
title: "Using Exports",
dynamic: typeof window !== 'undefined' ? window.title : 'SSR'
};
# Content here| Feature | Frontmatter | Exports |
|---|---|---|
| Syntax | YAML | JavaScript |
| Static analysis | ✅ Easy to parse without compiling | ❌ Requires JS execution |
| Dynamic values | ❌ Static only | ✅ Can compute values |
| Tooling support | ✅ Universal | ⚠️ Framework-dependent |
| CMS compatibility | ✅ Widely supported | ❌ Rarely supported |
| Build-time queries | ✅ GraphQL, collections | ⚠️ Limited |
Use frontmatter when: you need data that's queryable at build time, editable in a CMS, or used for static configuration.
Use exports when: you need dynamic values, computed properties, or complex data structures that benefit from JavaScript.
Common Frontmatter Fields
Essential Fields
Field Descriptions
- title: The display title. Shows up in headings, browser tabs, and search results.
- slug: URL-friendly identifier. Most frameworks derive this from the filename if you skip it.
- description: Short summary for SEO meta tags, social cards, and content previews.
- author: Who wrote it. Can be a plain string or an object with name, avatar, bio.
- date: When it was published. Used for sorting and display.
- lastModified: When it was last updated. Good for SEO and reader trust.
- tags: Topic labels for filtering and categorization.
- category: Primary classification (usually single-value, unlike tags).
- draft: Boolean flag — is this content ready to show publicly?
- published: Alternative to
draftwith inverse logic —truemeans visible.
Frontmatter Validation
Unvalidated frontmatter leads to build errors or subtle runtime bugs. Validate with a schema and catch problems early.
Using Zod for Validation
Content Collections in Astro
Astro has this built in. Define your schema once, and Astro validates every file at build time:
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
const blogCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
date: z.date(),
author: z.string(),
tags: z.array(z.string()),
draft: z.boolean().default(false),
image: z.string().optional(),
}),
});
export const collections = {
blog: blogCollection,
};Best Practices
- Keep it concise — Store metadata only. If a field is growing into paragraphs, move it into the document body or a separate data file.
- Be consistent with names — Pick
camelCaseorsnake_caseand stick with it across every file.
- Validate early — Add schema validation to your build so you catch typos and missing fields before deploy, not after.
- Document your schema — Keep a reference of what fields exist so content authors aren't guessing.
- Set defaults — Use your validation library to fill in optional fields, so authors only need to specify what matters.
- Don't repeat what you can compute — Reading time? Word count? Generate those at build time from the content itself.
- Use ISO dates —
YYYY-MM-DDeverywhere. No ambiguity, no timezone surprises.
- Group related fields — Use nested objects like
seo.titleandseo.descriptioninstead of flat prefixed keys likeseoTitle.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Frontmatter Basics.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this MDX Tutorial topic.
Search Terms
mdx-tutorial, mdx tutorial, mdx, tutorial, frontmatter, basics, frontmatter basics
Related MDX Tutorial Topics