Using next-mdx-remote for Server-Side Rendered MDX Pages
Show how to use 'next-mdx-remote' to server-side render MDX pages in Next.js 14, for improved performance and SEO.
import { serialize } from 'next-mdx-remote/serialize';
import { MDXRemote } from 'next-mdx-remote';
// Additional components you might be using within your MDX content:
import SomeComponent from '../components/SomeComponent';
export default function PostPage({ source }) {
return <MDXRemote {...source} components={{ SomeComponent }} />;
}
This is the component file where the server-side serialized MDX content is rendered on the page. The `MDXRemote` component from `next-mdx-remote` is used to render the MDX content. It also supports using custom components within MDX.
export async function getServerSideProps(context) {
// Fetch your MDX content from a data source, like a file system or a CMS.
const mdxContent = await fetchData(context.params.slug);
// Use the serialize function to serialize the MDX content for SSR.
const mdxSource = await serialize(mdxContent);
return { props: { source: mdxSource } };
}
This is the `getServerSideProps` function from Next.js which fetches the MDX content on each request and serializes it using the `serialize` function from `next-mdx-remote`. The `source` prop is then passed to the page component for rendering.
/* Example CSS for the MDX content styling */
h1 {
color: #333;
}
p {
color: #666;
}
This is an example CSS snippet that could be included in your stylesheet to style the MDX content once it is rendered on the page.