Blog>
Snippets

Integrating MDX with Next.js API Routes

Provide an example of how to use Next.js API routes to fetch and process MDX content before rendering.
// pages/api/mdx-content.js
import { serialize } from 'next-mdx-remote/serialize';
import fs from 'fs';
import path from 'path';

export default async function handler(req, res) {
  // Path to the MDX file
  const filePath = path.join(process.cwd(), 'content', 'example.mdx');
  const mdxContent = fs.readFileSync(filePath, 'utf8');

  // Serialize the MDX content
  const mdxSerialized = await serialize(mdxContent);

  // Return the serialized MDX content
  res.status(200).json({ mdxSerialized });
}
This is a Next.js API route that reads an MDX file from a specified directory, serializes it with `next-mdx-remote/serialize`, and sends the serialized content as a JSON response.
// pages/index.js
import { useState, useEffect } from 'react';
import { MDXRemote } from 'next-mdx-remote';

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

  useEffect(() => {
    fetch('/api/mdx-content')
      .then((res) => res.json())
      .then((data) => {
        setMdxContent(data.mdxSerialized);
      });
  }, []);

  return (
    <div>
      {mdxContent ? <MDXRemote {...mdxContent} /> : <p>Loading...</p>}
    </div>
  );
}
This code snippet is a React component that uses a `useEffect` hook to fetch MDX content from a Next.js API route and renders it using `MDXRemote` from `next-mdx-remote`, displaying a loading message until the content is fetched.
// styles/globals.css
body {
  font-family: 'Arial', sans-serif;
}

/* Placeholder CSS styles for the rendered MDX content */
.mdx-rendered-content {
  margin: 20px;
  font-size: 16px;
  line-height: 1.6;
}
This is a global CSS file that includes basic styles for the body and additional styles for rendered MDX content, ensuring consistent font and layout.