Understanding MDX: The Power of Markdown and React
If you are reading this, you are looking at MDX in action. MDX is an extension to Markdown that lets you include JSX (React components) directly in your markdown content. It’s the secret sauce that powers this blog.
What is MDX?
Standard Markdown is great for text, images, and code blocks. But what if you want to embed an interactive chart, a custom alert, or a live code editor?
In standard Markdown, you'd have to use HTML, which can be messy and insecure. With MDX, you can import and use React components just like you would in a .tsx file.
// This is valid MDX!
import { Button } from '@/components/ui/button';
# Hello World
<Button>Click me</Button>
Why We Chose MDX
For TechBlog, we wanted a balance between:
- Ease of Writing: Markdown is the standard for technical writing.
- Flexibility: We need to showcase custom UI components (like the ones in our Labs).
MDX gives us the best of both worlds. We store our content as data (files in content/blog), but we render it as a rich React application.
How It Works Under the Hood
Our architecture uses next-mdx-remote. Here is the flow:
- Read File: We read the
.mdxfile from the file system using Node.jsfs. - Parse Frontmatter: We use
gray-matterto extract metadata like title, date, and tags. - Serialize & Render:
MDXRemotecompiles the MDX string into React components on the server.
The Code
Here is a snippet from our lib/posts.ts that handles this:
const fullPath = path.join(postsDirectory, `${id}.mdx`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const matterResult = matter(fileContents);
Using Components
One of the coolest features is that we can provide a set of "default components" to every MDX file. For example, we can map the standard markdown <a> tag to Next.js's <Link> component for faster navigation, or map <img> to next/image for optimization.
In future updates, we plan to introduce custom components like <Callout /> or <CodePlayground /> directly into these posts.
Conclusion
MDX transforms static content into a dynamic experience. It allows us to treat content as code, bringing the full power of the React ecosystem to our technical documentation and blog posts.