Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 72 ยท Configuration, Tooling and Testing

MDX in Next.js

Use MDX in the Next.js App Router: set up @next/mdx, map Markdown to your own components with mdx-components.tsx, add remark and rehype plugins, and read frontmatter.

Markdown is the easiest way to write long text: headings, lists, links and code come with a few punctuation marks. But a blog post sometimes needs more than text. You may want a chart, a pricing table that reads live data, or a callout box with your own styling. MDX is Markdown that can import and use React components, so one file can mix prose and interactive parts.

Next.js supports MDX through the official @next/mdx package. This lesson goes through the whole setup: enabling MDX, mapping plain Markdown elements to your own components, using remark and rehype plugins, handling frontmatter and loading posts from a folder. The blog project already showed a short MDX section; here you see how every piece works. Next.js and MDX cannot run on this site, so the real files are read-only. The runnable examples are Node.js stand-ins: a tiny Markdown-to-HTML converter with a components map, and a small plugin pipeline.

What MDX adds to Markdown

Prose Normal Markdown for the words.
Components Import and use React in the text.
Exports A file can export metadata or data.

Markdown for authors, React for developers.

1 / 2

Install and enable

Install the package and its type definitions:

Terminal
npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx

Then wrap your config with createMDX and tell Next.js that .md and .mdx files can be pages:

TypeScript
// next.config.mjs (read-only)
import createMDX from "@next/mdx";

/** @type {import('next').NextConfig} */
const nextConfig = {
  pageExtensions: ["js", "jsx", "md", "mdx", "ts", "tsx"],
};

const withMDX = createMDX({
  options: {
    remarkPlugins: [],
    rehypePlugins: [],
  },
});

export default withMDX(nextConfig);

With this in place, any page.mdx file inside app/ is a page. A file app/about/page.mdx renders at /about, with Markdown for its content:

MDX
{/* app/about/page.mdx */}
import { Callout } from "@/components/callout";

# About us

We build **small, fast** sites.

<Callout type="tip">MDX lets this box live inside the page text.</Callout>

You can also import an MDX file into a normal page and render it as a component. That is how blog posts are usually loaded, and it is shown below.

The required mdx-components.tsx file

In the App Router, @next/mdx needs a file named mdx-components.tsx at the project root (or in src/). It exports useMDXComponents, a function that returns a map from element names to React components. Whenever MDX would output an <h1>, <a> or <pre>, it looks the name up in this map first.

TSX
// mdx-components.tsx (read-only)
import type { MDXComponents } from "mdx/types";
import Image, { type ImageProps } from "next/image";
import Link from "next/link";
import { Callout } from "@/components/callout";

export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    h1: ({ children }) => <h1 className="mb-6 text-4xl font-bold">{children}</h1>,
    a: ({ href = "", children }) =>
      href.startsWith("/") ? <Link href={href}>{children}</Link> : <a href={href} rel="noopener noreferrer">{children}</a>,
    img: (props) => <Image sizes="100vw" style={{ width: "100%", height: "auto" }} {...(props as ImageProps)} />,
    Callout,
    ...components,
  };
}

This one file gives you a lot of control. All headings in every post get the same styling, internal Markdown links become next/link (client-side navigation, see Linking and Navigation), Markdown images use next/image (see Images) and <Callout> becomes available in every MDX file without an import. The ...components at the end lets a single page override a mapping.

The stand-in below shows the idea without React. It converts a small subset of Markdown to HTML, but every element goes through a components map, like useMDXComponents. Change the map and the same text gets different markup.

Node.js A mini Markdown converter with a components map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Loading posts from a folder

For a blog you usually do not want a page.mdx per post. Keep posts in a content/ folder and load them in a dynamic route with a dynamic import. The import path must start with a fixed part, so the bundler can find all possible files:

TSX
// app/blog/[slug]/page.tsx (read-only)
import { notFound } from "next/navigation";

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  try {
    const { default: Post } = await import(`@/content/${slug}.mdx`);
    return <Post />;
  } catch {
    notFound();
  }
}

export function generateStaticParams() {
  return [{ slug: "hello" }, { slug: "mdx-tips" }]; // read from the folder in a real app
}

export const dynamicParams = false;

generateStaticParams lists the slugs so every post is built ahead of time (see Static Generation), and dynamicParams = false makes unknown slugs return 404 instead of trying to import a file that does not exist. To build the list, read the file names in content/ at build time with fs.readdir.

Metadata and frontmatter

Frontmatter is the block between two --- lines at the top of a Markdown file, holding data such as the title and date. MDX does not read it by default, so there are two common approaches.

The simplest is an export inside the MDX file. An MDX file can export any JavaScript value, so a post can export its own metadata:

MDX
export const meta = { title: "Hello MDX", date: "2026-03-01", tags: ["mdx", "nextjs"] };

# Hello MDX

Then import both the component and meta: const { default: Post, meta } = await import(...), and use meta in generateMetadata (see Metadata and SEO). If you export a constant named metadata from a page.mdx file, Next.js uses it as the page metadata directly.

The second approach keeps classic frontmatter. Add the plugins remark-frontmatter (so the block is parsed, not printed) and remark-mdx-frontmatter (so it becomes an export named frontmatter):

TypeScript
// next.config.mjs (read-only)
const withMDX = createMDX({
  options: {
    remarkPlugins: ["remark-frontmatter", ["remark-mdx-frontmatter", { name: "frontmatter" }]],
  },
});

The example above passes plugin names as strings with their options, which is the form that the Rust-based compiler (Turbopack) requires, because it cannot take JavaScript functions in the config. With the Webpack-based compiler you may also import the plugin functions. Check the current @next/mdx documentation for the form your Next.js version supports.

remark and rehype plugins

MDX is processed in two stages. remark plugins work on the Markdown syntax tree, and rehype plugins work on the HTML tree that comes after. Popular uses:

  • remark-gfm adds GitHub-style tables, task lists and strikethrough.
  • rehype-slug and rehype-autolink-headings add ids and links to headings, which makes a table of contents possible.
  • rehype-pretty-code or rehype-highlight colors code blocks on the server, so no highlighter ships to the browser.
  • Your own plugin can do things like computing a reading time or turning :::note blocks into callouts.

A plugin is a function that receives the tree and edits it. The stand-in below shows the idea with a small pipeline: each plugin takes a list of blocks and returns a changed list.

Node.js A remark-style plugin pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Safety and when not to use MDX

MDX files are code. They are compiled to JavaScript and can run anything a component can. That is fine for content written by your own team and committed to the repository. It is dangerous for content from users or from a CMS that many people edit, because a malicious author could run code on your server or in your readers' browsers. For untrusted text use plain Markdown with react-markdown and a sanitizing step. If you need MDX that comes from a database or CMS and is not in the repository, the next-mdx-remote family of packages compiles it at request or build time, and the same trust rule applies.

Also remember the build cost: very large numbers of MDX pages slow the build, because each one goes through the compiler. Moving content to plain Markdown and a data file for metadata, or to a CMS with draft mode previews, can be the better trade for hundreds of posts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the job of mdx-components.tsx in the App Router?

    @next/mdx requires this file. Every element MDX produces is looked up in the returned map, so one place controls styling and behavior for all posts.
  2. 2. How can a post provide its own metadata without a plugin?

    MDX files can export values. You can import the export next to the component and use it in generateMetadata; a page.mdx may export metadata directly.
  3. 3. Which statement about remark and rehype is correct?

    MDX is processed in two stages. Remark plugins edit the Markdown tree, then rehype plugins edit the HTML tree.
  4. 4. Why is MDX a poor fit for content written by anonymous users?

    MDX can contain JavaScript expressions and imports. Only use it for trusted authors, and use plain Markdown with sanitizing for untrusted text.

Summary

  • @next/mdx lets .mdx files be pages or importable components. Add withMDX and the page extensions in the config.
  • In the App Router you must create mdx-components.tsx; its useMDXComponents map controls how every element renders.
  • Load posts from a folder with a dynamic import, generateStaticParams and dynamicParams = false.
  • Read metadata from an exported constant, or use remark-frontmatter and remark-mdx-frontmatter for classic frontmatter.
  • remark plugins edit the Markdown tree and rehype plugins edit the HTML tree. With Turbopack, list plugins by string name.
  • MDX is executable code: use it only for trusted content.

Next: Debugging and Error Handling