To create a dynamic route using Next.js and MDX, you can follow these steps:
-
Install the required packages:
npm install next-mdx-remote @mdx-js/react
-
Create a new page in the
pages
directory with the following file structure:- pages - posts - [slug].js
-
Inside the
[slug].js
file, import the necessary modules:import { getFiles, getFileBySlug } from '../../lib/mdx' import { MDXRemote } from 'next-mdx-remote' import { serialize } from 'next-mdx-remote/serialize'
-
Define the main component of the page:
export default function PostPage({ source }) { return ( <div> <MDXRemote {...source} /> </div> ) }
-
Implement the
getStaticPaths
andgetStaticProps
functions to fetch the necessary data for the dynamic route:export async function getStaticPaths() { const posts = await getFiles('posts') // Get the list of post files const paths = posts.map((post) => ({ params: { slug: post.replace(/\.mdx/, '') }, })) return { paths, fallback: false } } export async function getStaticProps({ params }) { const { slug } = params const post = await getFileBySlug('posts', slug) const mdxSource = await serialize(post.content) // Serialize MDX content return { props: { source: mdxSource } } }
-
Implement the necessary helper functions to fetch the post data. In this example, we're using the
fs
module to read the MDX files from theposts
directory:import fs from 'fs' import path from 'path' import matter from 'gray-matter' const root = process.cwd() export async function getFiles(type) { return fs.readdirSync(path.join(root, 'data', type)) } export async function getFileBySlug(type, slug) { const source = slug ? fs.readFileSync(path.join(root, 'data', type, `${slug}.mdx`), 'utf8') : fs.readFileSync(path.join(root, 'data', `${type}.mdx`), 'utf8') const { data, content } = matter(source) return { frontMatter: data, content } }
-
Create a directory named
data
in your project root and place your MDX files inside theposts
directory. For example:- data - posts - hello-world.mdx - another-post.mdx
-
Finally, run your Next.js development server:
npm run dev
You should now be able to access dynamic routes for your MDX posts. For example, if you have a post with the filename hello-world.mdx
, you can access it at /posts/hello-world
.