I am having an issue with rendering MDX content on a page using next-mdx-remote with Next.js. Currently, only the title from the frontmatter is being displayed, while the actual MDX content is not showing up. Below is the code snippet showcasing my setup:
PostPage.tsx
import { MDXRemote, MDXRemoteSerializeResult } from 'next-mdx-remote/rsc';
import { getPostBySlug } from '../../../lib/mdx';
export interface Props {
source: MDXRemoteSerializeResult;
frontmatter: {
title: string;
date: string;
};
}
export default async function PostPage() {
const { source, frontmatter } = await getPostBySlug();
console.log('MDX Source:', source);
console.log('Frontmatter:', frontmatter);
return (
<div className="pt-16">
<h1>{frontmatter.title}</h1>
<MDXRemote source={source} />
</div>
);
}
lib/mdx.js
import { serialize } from 'next-mdx-remote/serialize';
import { promises as fs } from 'fs';
import matter from 'gray-matter';
import path from 'path';
const postsDirectory = path.join(process.cwd(), 'content/biography');
export async function getPostBySlug() {
const filePath = path.join(postsDirectory, `life.mdx`);
const mdxText = await fs.readFile(filePath, 'utf8');
// Parse the front matter and content
const { content, data } = matter(mdxText);
// Serialize the content
const mdxSource = await serialize(content, { scope: data });
console.log('Serialized MDX Source:', mdxSource);
return {
source: mdxSource,
frontmatter: data,
};
}
export async function getAllPostSlugs() {
const filenames = await fs.readdir(postsDirectory);
return filenames.map((filename) => filename.replace('.mdx', ''));
}
life.mdx in content/biography
---
title: "Example Post"
date: "2023-01-01"
---
# Hello, world!
This is an example post written in MDX.
next.config.mjs
import remarkGfm from 'remark-gfm';
import createMDX from '@next/mdx';
const nextConfig = {
// Configure `pageExtensions`` to include MDX files
pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
// Optionally, add any other Next.js config below
};
const withMDX = createMDX({
// Add markdown plugins here, as desired
options: {
remarkPlugins: [remarkGfm],
rehypePlugins: [],
},
});
export default withMDX(nextConfig);
When accessing the PostPage through the /about route, only the title "Example Post" is visible, and the content (e.g., "# Hello, world!") is not rendering. How can I resolve this issue and display the MDX content correctly?