Learn Astro · 5/15

Content Creation: Markdown & MDX

6 min read

Content Creation: Markdown & MDX

Welcome to the Content Creation module of the Astro course. Here, we transition from building structural layouts to managing the actual substance of your website: the content.

In the web development ecosystem, content management often creates a friction point between developers (who write code) and writers (who write text). Astro bridges this gap seamlessly by treating Markdown and MDX as first-class citizens.


1. Writing Static Pages with Markdown (.md)

Definition

Markdown is a lightweight markup language for creating formatted text using a plain-text editor. In Astro, any Markdown file placed in the src/pages/ directory automatically becomes a page on your website.

The Problem

Writing content directly in HTML is verbose and prone to errors. For example, writing a simple blog post requires manually opening and closing <p>, <h1>, <ul>, and <li> tags. This reduces readability and slows down the writing process.

Fun Fact: Markdown was created in 2004 by John Gruber and Aaron Swartz. The goal was to write in an easy-to-read, easy-to-write plain text format that converts valid XHTML.

The Solution

Astro allows you to write in .md syntax, which it then compiles into optimized HTML at build time. This allows you to focus on the writing, while Astro handles the rendering.

Implementation

To create a page, simply add a file ending in .md to your src/pages folder.

File Structure:

text
src/
  pages/
    index.astro
    about.md       -> renders at localhost:4321/about
    posts/
      hello.md     -> renders at localhost:4321/posts/hello

Example Content (src/pages/about.md):

markdown
# About Me

Hello! I am a web developer learning **Astro**.

## My Skills
- JavaScript
- React
- Astro 🚀

> "Simplicity is the ultimate sophistication."

When you navigate to /about, Astro renders this as:

html
<h1>About Me</h1>
<p>Hello! I am a web developer learning <strong>Astro</strong>.</p>
<h2>My Skills</h2>
<ul>
  <li>JavaScript</li>
  <li>React</li>
  <li>Astro 🚀</li>
</ul>
<blockquote>
  <p>"Simplicity is the ultimate sophistication."</p>
</blockquote>

2. Frontmatter: Managing Metadata for Your Posts

Definition

Frontmatter is a YAML code block delimited by triple dashes --- at the very top of a Markdown file. It contains key-value pairs that describe the content but do not appear in the rendered HTML body.

The Problem

A Markdown file contains the content of a post, but it lacks context.

  • When was this published?
  • Who is the author?
  • Is this a draft?
  • What is the title for the browser tab?

Without a standardized way to store this data, developers used to hack specific HTML comments or separate JSON files to track metadata, which is difficult to maintain.

The Solution

Astro parses the Frontmatter block and makes that data available to your layouts and components. This separates the data (metadata) from the view (content).

Implementation

Add the YAML block at the top of your file.

Example (src/pages/posts/learning-astro.md):

markdown
---
title: "Learning Astro is Fun"
pubDate: 2023-10-15
author: "Code Camper"
tags: ["astro", "coding", "webdev"]
draft: false
---

# Introduction
This is the content of the post. The title above does not render here automatically; 
it is stored as data to be used by the layout.

Industry Standard:
Always use consistent naming conventions in your frontmatter (e.g., camelCase or snake_case) across all files to prevent type errors when fetching collections of posts later.


3. Supercharging Content with MDX (.mdx)

Definition

MDX (Markdown JSX) is an extension of Markdown that allows you to import and use components (like Astro or React components) directly inside your content.

The Problem

Standard Markdown is static. If you want to include an interactive pricing calculator, a dynamic chart, or a custom-styled alert box inside a blog post, standard Markdown fails. You would have to revert to writing the entire page in HTML/Astro, losing the ease of writing text.

Imagination: Trying to build an interactive dashboard inside a standard .md file is like trying to play a video game on a printed piece of paper. You can draw the buttons, but pushing them does nothing.

The Solution

MDX allows you to mix standard Markdown syntax with Component imports.

Installation

MDX is not installed by default in the bare starter. You must add the integration.

Terminal:

bash
npx astro add mdx

Note: This command automates the configuration by updating your astro.config.mjs file.

Implementation

  1. Rename your file from .md to .mdx.
  2. Import components just like you would in a .astro file.

Example (src/pages/interactive-post.mdx):

mdx
---
title: "Interactive Content"
---
import Counter from '../components/Counter.jsx';
import Alert from '../components/Alert.astro';

# This is MDX

Here is standard text. Below is a React counter component working inside Markdown!

<Counter client:load />

<Alert type="warning">
  This is a custom Astro component wrapping text content!
</Alert>

4. Creating Custom Markdown Layouts

Definition

A Markdown Layout is a special Astro component designed to wrap your Markdown content, providing the surrounding HTML structure (header, footer, styles) that the Markdown file lacks.

The Problem

By default, Astro renders Markdown files as bare HTML fragments. They have no <head>, no <body>, no navigation bar, and no CSS styles applied. If you view a raw Markdown page, it will look like unstyled Times New Roman text on a white background.

The Solution

Astro allows you to specify a layout property in the frontmatter. Astro wraps your rendered Markdown content into a special <slot /> inside that layout file and passes the frontmatter data as properties.

Implementation

Step 1: Create the Layout
Create a file at src/layouts/BlogPostLayout.astro.

astro
---
// src/layouts/BlogPostLayout.astro
const { frontmatter } = Astro.props;
---
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>{frontmatter.title}</title>
  </head>
  <body>
    <nav>
      <a href="/">Home</a>
    </nav>
    
    <article>
      <!-- Metadata injection -->
      <h1>{frontmatter.title}</h1>
      <p>Written by: {frontmatter.author} on {frontmatter.pubDate}</p>
      
      <!-- The rendered Markdown content is injected here -->
      <slot />
      
    </article>
  </body>
</html>

Step 2: Connect the Markdown File
Reference the layout in your Markdown frontmatter.

markdown
---
layout: ../layouts/BlogPostLayout.astro
title: "My Styled Post"
author: "Jane Doe"
pubDate: "2023-11-01"
---

This text will now appear inside the `<slot />` of the layout defined above.
It will include the navigation and the styled header!

Interesting Detail:
If you have nested layouts (e.g., a BaseLayout and a BlogLayout), you can chain them. However, in Markdown files, you only specify the immediate wrapper.


Summary

  1. Markdown (.md): Best for text-heavy, static content.
  2. Frontmatter: Stores metadata (title, date) separate from content.
  3. MDX (.mdx): Best when you need interactivity or components inside your text.
  4. Layouts: The structural shell that holds your content and applies global styles.

References & Extra Reading

Challenge

You are building a blog using Astro and need to create a new blog post that uses a custom layout and includes an interactive component.

Your task is to write the code for two separate files within a single editor: an MDX page and its corresponding Astro layout.

Part 1: The MDX Post (src/pages/blog/advanced-astro.mdx)

  1. Define a frontmatter block with the following key-value pairs:
    • layout: The path to the layout component, ../../layouts/PostLayout.astro.
    • title: "Mastering MDX in Astro"
    • pubDate: A valid date string like 2023-11-20.
    • author: "Jane Astrodev"
    • tags: A YAML array containing the strings "astro", "mdx", and "components".
  2. Below the frontmatter, import a component named Callout from the path ../../components/Callout.astro.
  3. Write some sample Markdown content, including at least one heading and one paragraph.
  4. Within your Markdown content, render the imported <Callout /> component.

Part 2: The Astro Layout (src/layouts/PostLayout.astro)

  1. Create a standard Astro component structure with a frontmatter script block (---) and an HTML template section.
  2. In the script block, retrieve the frontmatter object passed from the MDX page using Astro.props.
  3. In the HTML template, create a full HTML5 document structure (<!DOCTYPE html>, <html>, <head>, <body>).
  4. Inside the <head>, set the document's <title> to be the title from the post's frontmatter.
  5. Inside the <body>, display the post's title in an <h1> element and the author in a <p> element.
  6. Finally, include a <slot /> element where the content from the MDX file will be rendered.

Expected result

Your final code should consist of two distinct blocks, one for each file.

advanced-astro.mdx block:

  • Starts with a valid YAML frontmatter block enclosed in ---.
  • This block must contain the five specified keys (layout, title, pubDate, author, tags) with their correct values and types.
  • Includes a JavaScript import statement for the Callout component.
  • Contains Markdown text and a self-closing <Callout /> tag in the body.

PostLayout.astro block:

  • Starts with an Astro frontmatter script block (---).
  • The script block correctly accesses frontmatter from Astro.props.
  • The template section contains a complete HTML document structure.
  • The page's <title> tag dynamically uses frontmatter.title.
  • The <body> contains an <h1> with frontmatter.title, a <p> with frontmatter.author, and the essential <slot /> component to render the MDX body content.
astro

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.