How to Use Markdown and MDX in Astro

How to Use Markdown and MDX in Astro

Master Markdown and MDX in Astro: Build type-safe, high-performance content systems using Content Collections, custom AST pipelines, and interactive islands.

Enterprise content engineering faces a persistent dilemma: non-technical stakeholders require an ergonomic authoring experience, while systems architects demand rigorous type safety, zero-runtime overhead, and strict design system adherence. Traditional monolithic CMS solutions introduce latency and infrastructure sprawl, whereas legacy Single-Page Applications (SPAs) parsing client-side Markdown deliver suboptimal Core Web Vitals and poor SEO performance.

Astro resolves this friction through its compiler-first architecture and native support for both CommonMark/GFM and MDX (Markdown with JSX components). By combining content-as-code paradigms with Astro’s “Zero-JS by default” Islands Architecture, engineering teams can build resilient, ultra-fast technical documentation hubs, knowledge bases, and corporate web platforms.

This guide provides an end-to-end architectural deep dive into deploying Markdown and MDX at scale within Astro, covering strict schema validation, Abstract Syntax Tree (AST) customization, interactive island injection, and CI/CD content governance.


Architectural Foundations: Markdown vs. MDX

Before establishing repository structures, architects must delineate between pure Markdown (.md) and MDX (.mdx). While both parse through Astro’s underlying unified pipeline, their compilation artifacts and execution costs differ.

Pure Markdown (.md)
[ Raw Source ] ──> [ Remark AST ] ──> [ Rehype AST ] ──> [ Static HTML Engine ] ──> Pure HTML (Zero JS)

MDX (.mdx)
[ MDX Source ] ──> [ remark-mdx ] ──> [ esast / JSX ] ──> [ Astro Compiler ] ──> JS/HTML + Hydrated Islands

Pure Markdown (.md)

  • Compilation Mechanism: Transpiled strictly into raw HTML at build time via remark and rehype.
  • JS Footprint: Exactly zero bytes of JavaScript shipped to the client browser.
  • Use Cases: Standard prose, static enterprise changelogs, privacy policies, API reference documentation without interactive sandboxes.
  • Performance Characteristics: Highest throughput build times; minimal memory pressure during static site generation (SSG).

MDX (.mdx)

  • Compilation Mechanism: Compiled into JSX, transformed into an Astro component module, and executed during the render phase.
  • JS Footprint: Zero bytes by default, unless interactive components configured with client:* hydration directives are explicitly imported.
  • Use Cases: Dynamic design system showcases, API documentation featuring interactive request runners, complex visual diagrams, embedded business analytics calculators.
  • Performance Characteristics: Slightly higher compilation overhead due to JavaScript module evaluation; requires careful boundary management to avoid excessive hydration payloads.

Type-Safe Content Governance with Content Collections

Enterprise teams cannot rely on unvalidated Markdown frontmatter. Missing metadata, erroneous typing, or schema drift can cause production build failures or break rendering layouts. Astro’s Content Collections provide an enforced TypeScript layer driven by Zod schemas.

Schema Definition and Strict Validation

Place all structured content in the reserved directory src/content/. Astro validates all frontmatter properties against your contract defined in src/content/config.ts.

// src/content/config.ts
import { defineCollection, z } from 'astro:content';

const technicalDocumentation = defineCollection({
  type: 'content', // Enforces Markdown/MDX content parsing
  schema: ({ image }) =>
    z.object({
      title: z.string().max(70, 'Meta title must be under 70 characters for SERP optimization'),
      description: z.string().max(160, 'Meta description should satisfy SEO thresholds'),
      publicationDate: z.date(),
      updatedDate: z.date().optional(),
      author: z.object({
        name: z.string(),
        role: z.string().default('Staff Engineer'),
        avatar: image(), // Validates, optimizes, and transforms local assets
      }),
      status: z.enum(['draft', 'review', 'published', 'archived']).default('draft'),
      tags: z.array(z.string()).min(1, 'Supply at least one diagnostic tag'),
      version: z.string().regex(/^\d+\.\d+\.\d+$/, 'Version must strictly follow SemVer (e.g., 2.4.1)'),
      canonicalUrl: z.string().url().optional(),
    }),
});

export const collections = {
  docs: technicalDocumentation,
};

This configuration establishes compile-time assertions:

  1. If an author defines an invalid SemVer string, the build exits with a nonzero status code.
  2. The image() helper asserts local image existence at build time, preventing broken references before deployment.
  3. Every queried document has exact, auto-generated TypeScript typings.

Dynamic Routing and Content Rendering

Rendering content requires decoupling data retrieval from visual composition. Use Astro’s dynamic routing parameters to generate SSG routes at scale.

Implementing Dynamic Route Handlers

The following file dynamically maps and renders MDX/Markdown documentation at src/pages/docs/[...slug].astro.

---
// src/pages/docs/[...slug].astro
import { getCollection, type CollectionEntry } from 'astro:content';
import DocumentationLayout from '@/layouts/DocumentationLayout.astro';

export async function getStaticPaths() {
  const docEntries = await getCollection('docs', ({ data }) => {
    // Pipeline optimization: filter out drafts in non-production builds
    return import.meta.env.PROD ? data.status === 'published' : true;
  });

  return docEntries.map((entry) => ({
    params: { slug: entry.slug },
    props: { entry },
  }));
}

interface Props {
  entry: CollectionEntry<'docs'>;
}

const { entry } = Astro.props;

// Compile and transform Markdown/MDX into accessible Astro Component
const { Content, headings, remarkPluginFrontmatter } = await entry.render();
---

<DocumentationLayout 
  title={entry.data.title}
  description={entry.data.description}
  headings={headings}
  readingTime={remarkPluginFrontmatter.readingTime}
>
  <article class="prose prose-slate dark:prose-invert max-w-none">
    <Content />
  </article>
</DocumentationLayout>

entry.render() parses the content node, evaluates remark/rehype transformations, and extracts document outlines (headings) for building automated Table of Contents (ToC) structures.


Augmenting MDX with Design System Primitives

MDX bridges narrative prose and operational code. In enterprise architectures, this allows injecting your core UI design system directly into documentation without manual wrapper markup.

1. Global Component Overrides

You can replace native HTML output (e.g., <table>, <blockquote>, <code>) with sophisticated, access-controlled components from your design system.

// src/components/mdx/TableOfContents.astro
---
import CustomTable from '@/components/ui/CustomTable.astro';
import EnterpriseCallout from '@/components/ui/EnterpriseCallout.astro';
import CodeBlockWrapper from '@/components/ui/CodeBlockWrapper.astro';

export const mdxComponents = {
  table: CustomTable,
  blockquote: EnterpriseCallout,
  pre: CodeBlockWrapper,
};

Map these components during rendering to enforce accessibility standards (WCAG 2.1 AA) without relying on content authors to write custom HTML:

---
// Inside src/pages/docs/[...slug].astro
import { mdxComponents } from '@/components/mdx/TableOfContents.astro';
// ...
---
<Content components={mdxComponents} />

2. Controlled Hydration with Astro Islands

A major anti-pattern in modern content systems is over-shipping JavaScript. MDX inside Astro supports framework-agnostic interactive components (React, Vue, Svelte, or Solid) that hydrate only when necessary.

Consider an MDX document that embeds an interactive micro-frontend:

---
title: "Configuring Kubernetes Ingress Controllers"
description: "Production guide to Traefik v3 ingress routing."
publicationDate: 2024-03-15
status: "published"
tags: ["infrastructure", "kubernetes", "networking"]
version: "1.0.0"
author:
  name: "DevOps Architecture Guild"
  avatar: "@/assets/authors/guild.png"
---

import IngressTrafficSimulator from '@/components/react/IngressTrafficSimulator.jsx';
import MetricTelemetryDisplay from '@/components/svelte/MetricTelemetryDisplay.svelte';

Standard deployment patterns require strict HTTP/3 ingress monitoring. Use the interactive harness below to test upstream timeout configurations.

{/* Zero-JS by default; loads dynamic JS bundle only when scrolled into the viewport */}
<IngressTrafficSimulator client:visible environment="production" maxNodes={12} />

Review the current telemetry baseline:

{/* Hydrates immediately on idle CPU time */}
<MetricTelemetryDisplay client:idle telemetryStream="cluster-us-east-1" />

This hybrid model ensures your documentation platform scores 100 on Google PageSpeed Insights while retaining interactive debugging consoles and live component sandboxes.


Custom AST Pipelines: Enterprise Remark and Rehype Plugins

Astro’s native content engine leverages the unified ecosystem. You can alter Abstract Syntax Trees (ASTs) by defining custom Remark (Markdown AST / mdast) and Rehype (HTML AST / hast) plugins in your root configuration.

Common enterprise AST requirements include:

  • Calculating strict reading times for operational scheduling.
  • Validating and sanitizing outbound hyperlinks for zero-trust security compliance.
  • Auto-injecting anchors and structural telemetry metrics.

Building a Production-Grade Remark Plugin

The following custom plugin computes word counts, estimates reading duration, and exposes this metadata directly to Astro’s rendering engine through frontmatter mutation:

// plugins/remark-reading-time.mjs
import getReadingTime from 'reading-time';
import { toString } from 'mdast-util-to-string';

export function remarkReadingTime() {
  return function (tree, { data }) {
    // Convert Markdown AST to raw textual representation
    const textOnPage = toString(tree);
    const readingTimeResult = getReadingTime(textOnPage);

    // Astro captures values appended to `data.astro.frontmatter`
    data.astro.frontmatter.readingTime = {
      text: readingTimeResult.text,
      minutes: Math.ceil(readingTimeResult.minutes),
      words: readingTimeResult.words,
    };
  };
}

Building a Hardened Rehype Security Plugin

To comply with enterprise security architectures, all external links must contain dynamic rel guards (noopener, noreferrer, nofollow) to prevent tabnabbing and backlink manipulation.

// plugins/rehype-link-security.mjs
import { visit } from 'unist-util-visit';

export function rehypeLinkSecurity(options = {}) {
  const internalDomain = options.allowedDomain || 'internal.enterprise.io';

  return (tree) => {
    visit(tree, 'element', (node) => {
      if (node.tagName === 'a' && node.properties && typeof node.properties.href === 'string') {
        const href = node.properties.href;

        // Skip internal relative links or matching domain links
        if (href.startsWith('/') || href.startsWith('#') || href.includes(internalDomain)) {
          return;
        }

        // Apply strict outbound parameters
        node.properties.target = '_blank';
        node.properties.rel = ['noopener', 'noreferrer', 'nofollow'];
        
        // Inject an enterprise tracking metadata attribute
        node.properties['data-outbound-audit'] = 'true';
      }
    });
  };
}

Integrating Plugins into astro.config.mjs

Inject these lifecycle transforms through the root Astro configuration:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import { remarkReadingTime } from './plugins/remark-reading-time.mjs';
import { rehypeLinkSecurity } from './plugins/rehype-link-security.mjs';
import expressiveCode from 'astro-expressive-code';

export default defineConfig({
  site: 'https://internal.enterprise.io',
  integrations: [
    expressiveCode({
      themes: ['github-dark', 'github-light'],
      useThemedScrollbars: true,
    }),
    mdx(),
  ],
  markdown: {
    syntaxHighlight: false, // Handled by Expressive Code
    remarkPlugins: [remarkReadingTime],
    rehypePlugins: [
      [rehypeLinkSecurity, { allowedDomain: 'enterprise.io' }],
    ],
  },
});

Enterprise Asset Optimization Pipeline

A common issue in decentralized documentation systems is uncompressed, unmanaged raster assets. Astro includes an image pipeline that integrates with Markdown and MDX.

MDX Source [ ![Architecture](./diagram.png) ] 
       │
       ▼
Astro Asset Compiler
       ├── Resolves Relative Path 
       ├── Sharp Engine Optimization (Transforms to WebP/AVIF)
       ├── Calculates Intrinsic Dimensions (Prevents CLS)
       └── Emits Production Assets to /_astro/

Colocated Assets in MDX

By collocating images beside documents inside src/content/, images are treated as first-class module dependencies.

src/content/docs/
└── cluster-scaling/
    ├── index.mdx
    └── topology-diagram.png

Authors can reference local images using standard Markdown syntax, and Astro processes the assets using Sharp:

<!-- index.mdx -->
## Network Topology

![Multi-Region Cluster Topology](./topology-diagram.png)

At build time, Astro executes:

  1. Format Negotiation: Converts uncompressed PNG/JPEG files into modern WebP and AVIF formats.
  2. Layout Stability: Computes the width, height, and layout footprint to eliminate Cumulative Layout Shift (CLS).
  3. Asset Hashing: Writes deterministic hashes (e.g., topology-diagram.b39f7a1c.webp) into the build output for long-term edge caching.

For finer control, import Astro’s <Image /> component directly into MDX:

import { Image } from 'astro:assets';
import topologyDiagram from './topology-diagram.png';

<Image 
  src={topologyDiagram} 
  alt="Detailed diagram showing our global distributed database nodes and failover routes" 
  quality={80}
  format="avif"
  class="rounded-lg shadow-xl border border-slate-700" 
/>

Production Readiness: Verification and Validation in CI/CD

Enterprise content pipelines must enforce code and prose validation rules during pull request reviews. Incorporating linters and schema validators guarantees that broken links, invalid code blocks, and unauthorized frontmatter variations never reach production.

GitHub Actions / CI
 ├── Step 1: Astro Sync (generate .astro/types.d.ts)
 ├── Step 2: Markdown Linting (markdownlint-cli2)
 ├── Step 3: Prose & Style Linting (Vale)
 └── Step 4: Astro Check & Static Build

GitHub Actions Quality Gate

This sample workflow runs frontmatter validation, type safety verification, prose linting, and a static compilation check:

# .github/workflows/content-pipeline.yml
name: Content Platform CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  validate-content:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: Setup Node.js Environment
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install Dependencies
        run: npm ci

      - name: Execute Astro Type Generation
        run: npx astro sync

      - name: Validate Frontmatter & Application Types
        run: npx astro check

      - name: Lint Markdown Files
        run: npx markdownlint-cli2 "src/content/**/*.md" "src/content/**/*.mdx"

      - name: Audit Prose with Vale Core Engine
        uses: errata-ai/vale-action@v2
        with:
          files: 'src/content'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Execute Production Build
        run: npm run build

Architectural Decision Matrix: Markdown, MDX, and Astro

To guide your engineering organization toward consistent patterns, use this decision matrix when defining technical documentation architectures:

Architectural Metric Native Markdown (.md) MDX (.mdx) Headless CMS via API
Parsing Overhead Extremely Low (Fastest builds) Moderate (Compiles to JSX) High (Network latency bound)
Client JS Footprint Exactly 0 kB 0 kB by default (Scales with islands) 0 kB to Heavy (Platform dependent)
Component Embedding Not supported natively Native (Astro, React, Svelte, Vue) Limited to custom shortcodes
Schema Governance Zod via Content Collections Zod via Content Collections CMS Content Type Builder
Asset Pipeline Automatic Sharp optimization Automatic Sharp optimization Third-Party CDN Transforms
Authoring Ergonomics High (Universal syntax) High (Requires JSX awareness) Very High (WYSIWYG / GUI)
Best Suited For Static reference docs, legal copy Interactive guides, SDKs, design hubs Non-technical marketing copy

Conclusion

Astro’s integration of Markdown and MDX fundamentally alters content engineering. By pairing a unified compiler pipeline with Zod-based content schemas and Astro’s zero-JS islands, teams can dismantle the divide between static prose and dynamic web platforms.

Using Content Collections, teams can enforce compile-time type safety across all documents. With custom Remark and Rehype plugins, organizations can implement universal security standards, telemetry, and link integrity checks directly within the AST. The resulting architecture scales effectively across large multi-team repositories, delivering high performance to end users while maintaining strict engineering standards.