Blog>
Snippets

Loading and Rendering MDX Content from External Sources

Example of loading and rendering MDX content from external sources such as a CMS or file system within a Next.js application.
import { useEffect, useState } from 'react';
import { getMDXComponent } from 'mdx-bundler/client';

export default function MDXPage() {
  const [mdxContent, setMdxContent] = useState(null);
  const [Component, setComponent] = useState(null);

  useEffect(() => {
    fetch('/api/mdx')
      .then((response) => response.text())
      .then((mdx) => {
        const { code, frontmatter } = getMDXComponent(mdx);
        setMdxContent({ code, frontmatter });
      });
  }, []);

  useEffect(() => {
    if (mdxContent) {
      const Component = getMDXComponent(mdxContent.code);
      setComponent(<Component />);
    }
  }, [mdxContent]);

  return <div>{Component}</div>;
}
The code fetches MDX content from an API endpoint, compiles it into a React component, and renders it. useState hooks manage the MDX content and the compiled component. useEffect hooks handle the fetching and compilation after the component mounts and when the fetched MDX content changes.
import { bundleMDX } from 'mdx-bundler';

// Mock function to simulate fetching MDX data from an external source
async function fetchMDXFromSource() {
  // Fetching from a CMS or file system would typically occur here
  return `# Example Title

This is some MDX content`;
}

export default async function handler(req, res) {
  const mdxSource = await fetchMDXFromSource();
  const { code, frontmatter } = await bundleMDX({ source: mdxSource });
  res.status(200).json({ code, frontmatter });
}
This is a server-side API handler using Next.js API routes. It fetches MDX content from an external source, using 'bundleMDX' to transpile it into executable code and frontmatter. The bundled result is then returned in the response to be used by the client-side React component.