Skip to content

Instantly share code, notes, and snippets.

@hazre
Created May 25, 2023 02:17
Show Gist options
  • Save hazre/f1f55e76b3e78c97f4e8688546592f79 to your computer and use it in GitHub Desktop.
Save hazre/f1f55e76b3e78c97f4e8688546592f79 to your computer and use it in GitHub Desktop.
nextjs dynamic route mdx

To create a dynamic route using Next.js and MDX, you can follow these steps:

  1. Install the required packages:

    npm install next-mdx-remote @mdx-js/react
  2. Create a new page in the pages directory with the following file structure:

    - pages
      - posts
        - [slug].js
    
  3. 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'
  4. Define the main component of the page:

    export default function PostPage({ source }) {
      return (
        <div>
          <MDXRemote {...source} />
        </div>
      )
    }
  5. Implement the getStaticPaths and getStaticProps 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 } }
    }
  6. 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 the posts 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 }
    }
  7. Create a directory named data in your project root and place your MDX files inside the posts directory. For example:

    - data
      - posts
        - hello-world.mdx
        - another-post.mdx
    
  8. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment