🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Content & MDX••By Komal Nakrani

Astro MDX: Use Components Inside Markdown

Astro MDX guide: install @astrojs/mdx, import components into Markdown, use expressions and exports, render MDX from collections, and avoid syntax errors.

#Astro#MDX#Markdown#Content Collections#Components

Astro MDX lets you write Markdown that can also import and render components. Install it with npx astro add mdx, rename a file from .md to .mdx, and you can drop an Astro, React, Svelte or Vue component between paragraphs, use JavaScript expressions, and export values, while everything still renders to static HTML by default.

This guide covers setup, the MDX syntax that matters in practice, using MDX in content collections, configuration options, and the errors people hit most often.

Key Takeaways

  • npx astro add mdx installs @astrojs/mdx and adds it to integrations in astro.config.mjs.
  • In an .mdx file you can import components, use them as tags, and write expressions in curly braces.
  • Components in MDX render on the server; add a client:* directive to framework components that must be interactive.
  • MDX inherits your markdown config (processor, plugins, Shiki) unless you set extendMarkdownConfig: false.
  • MDX is stricter than Markdown: unescaped { or <, unclosed tags and HTML comments cause compile errors.

When to use MDX instead of Markdown

Plain Markdown (.md) is the right default for most articles. It’s faster to compile, harder to break, and any editor can handle it. MDX earns its place when content needs something Markdown can’t express:

  • A callout, tabs, or a code comparison component in the middle of a post.
  • An interactive demo, such as a calculator or a live chart.
  • Reusable snippets, like a shared pricing table or a disclaimer.
  • Values computed at build time, such as the current version number of a package.

If a post is just prose, headings, images and code blocks, keep it in .md. If you’re weighing this against a CMS, the Markdown or CMS guide compares the options.

Install the MDX integration

npx astro add mdx

That installs @astrojs/mdx and updates your config:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';

export default defineConfig({
  integrations: [mdx()],
});

Restart the dev server after installing. Without the integration, Astro won’t know how to process .mdx files, and you’ll see the error described in the MDX integration missing fix.

Importing and using components in MDX

Put import statements after the frontmatter, then use the component like an HTML tag:

---
title: Choosing a host
---
import Callout from '../../components/Callout.astro';
import PriceCalculator from '../../components/PriceCalculator.svelte';

## Static hosting

Most Astro sites can be hosted for free.

<Callout type="tip" title="Rule of thumb">
  If you have no server routes, any static host works.
</Callout>

<PriceCalculator client:visible />

The Callout is an Astro component, so it renders to HTML with no JavaScript. PriceCalculator is a Svelte component with client:visible, so it hydrates when scrolled into view, just like on a normal Astro page. Framework components need their integration installed, for example npx astro add svelte.

Markdown keeps working inside component children as long as you leave blank lines around it:

<Callout type="info">

This paragraph supports **bold**, `code` and [links](/docs/).

</Callout>

Expressions, variables and exports

Anything between curly braces is a JavaScript expression:

---
title: Release notes
version: 7.4
---
export const released = new Date('2026-10-15');

# Astro {frontmatter.version}

Released on {released.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}.

{['Faster builds', 'Better errors'].map((item) => <li>{item}</li>)}

Three things to know:

  1. Frontmatter values are available in the body through the frontmatter object.
  2. export const defines a value you can use in the file. Other files can import it too, if they import the .mdx file directly.
  3. Comments use JSX syntax: {/* note to editors */}. HTML comments (<!-- -->) are not valid MDX and fail to compile.

Images in MDX

Standard Markdown image syntax works, and relative images are optimized by Astro:

![Dashboard screenshot](./images/dashboard.png)

For control over sizes and formats, import the Image component from astro:assets:

import { Image } from 'astro:assets';
import dashboard from './images/dashboard.png';

<Image src={dashboard} alt="Analytics dashboard with weekly traffic" width={960} />

Imported local images get their dimensions read at build time, which prevents layout shift. The Astro image cheatsheet lists every option.

MDX in content collections

MDX files work in any glob() collection. Include the extension in the pattern:

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

const blog = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
  }),
});

export const collections = { blog };

Render an entry with render() and output the Content component:

---
// src/pages/blog/[id].astro
import { getCollection, render } from 'astro:content';
import Callout from '../../components/Callout.astro';

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({ params: { id: post.id }, props: { post } }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---
<article>
  <h1>{post.data.title}</h1>
  <Content components={{ Callout }} />
</article>

Passing components to <Content /> makes Callout available in every post without an import line, and lets you replace standard elements like h2 or a. That mapping deserves its own article: see mapping custom components to MDX elements.

Configuring the MDX integration

By default, MDX inherits your markdown config: the same Markdown processor, remark and rehype plugins, Shiki theme and GitHub-flavored Markdown settings. In current Astro 7 releases, plugins are configured on the processor itself, and MDX picks them up automatically:

npm install @astrojs/markdown-remark remark-toc
// astro.config.mjs
import { defineConfig } from 'astro/config';
import { unified } from '@astrojs/markdown-remark';
import mdx from '@astrojs/mdx';
import remarkToc from 'remark-toc';

export default defineConfig({
  markdown: {
    processor: unified({ remarkPlugins: [remarkToc] }),
    shikiConfig: { theme: 'github-dark' },
  },
  integrations: [mdx({ optimize: true })],
});

Older configs that put remarkPlugins and rehypePlugins directly under markdown or inside mdx() still work, but those options are now marked deprecated in the type definitions and will be removed in a future major version. New projects should use the processor form.

Option What it does
extendMarkdownConfig Inherit markdown settings (default true)
processor Use a different Markdown processor for .mdx files than for .md
recmaPlugins MDX-only plugins that run on the compiled JavaScript
optimize Compiles static parts of MDX to plain HTML strings for faster builds; accepts ignoreElementNames
syntaxHighlight, shikiConfig Same meaning as in markdown

optimize is worth trying on large sites. It reduces the work done per page, but it can interfere with element mapping through the components prop, which is why ignoreElementNames exists. The official MDX integration docs cover each option, and the remark and rehype plugins list suggests useful ones.

Common MDX errors and how to avoid them

MDX is compiled to JavaScript, so it’s less forgiving than Markdown. These cause most build failures:

  • Unescaped curly braces. Use {name} here is parsed as an expression. Write \{name\} or put it in backticks.
  • A bare less-than sign. if a < b can be read as the start of a tag. Escape it as \< or use backticks.
  • HTML comments. Replace <!-- --> with {/* */}.
  • Unclosed void tags. Write <br /> and <img ... />, not <br>.
  • Indented component children. Four spaces of indentation inside a component turns Markdown into a code block. Keep children flush left with blank lines around them.
  • Missing imports. Every component used in the file must be imported or passed through components.

When a build fails, the error points to the line and column in the .mdx file. Most are fixed in seconds once you know these patterns. Many Astro blog themes ship with MDX already configured and a few components ready to use, which is a quick way to see working examples. The content docs explain how collections are set up in Komal themes.

FAQ

Do I need MDX to use Markdown in Astro?

No. Astro supports .md files out of the box, in src/pages/ and in content collections. You only need the @astrojs/mdx integration if you want .mdx files with imports, components and expressions.

Can I use React components in Astro MDX?

Yes. Install the React integration with npx astro add react, import the component in the .mdx file, and use it like a tag. Add a client:* directive such as client:visible if it needs to be interactive in the browser.

How do I access frontmatter inside an MDX file?

Use the frontmatter object in the body, for example {frontmatter.title}. In a page or layout that renders the file from a collection, use entry.data instead.

Why does my MDX file fail to compile?

The usual causes are unescaped { or < in prose, HTML comments, unclosed tags like <br>, or a component that wasn’t imported. Check the line and column in the error message, then escape the character or switch to JSX syntax.

Is MDX slower than Markdown in Astro?

MDX takes more work to compile, so large MDX collections build slower than plain Markdown. The output HTML is the same speed for visitors, since both render to static HTML. Enabling optimize in the MDX integration reduces build cost on content-heavy sites.