skip to Main Content

Just followed the Next13 + MDX Tutorial, but I am still not sure how I can load my mdx files dynamically? I do not have my mdx files on some remote server, so I do not need next-mdx-remote. However, I do need a way to load a different mdx file depending on my route (e.g. /blog/[slug]). All my mdx files are in the same repo.

So when a user requests /blog/article-1 I want to import my article1.mdx file. In the tutorial, this is just a hard-coded import for a static page:

import HelloWorld from './hello.mdx';

export default function Page() {
  return <HelloWorld />;
}

…but I need the page & the imports to be dynamic.

2

Answers


  1. On the page you could run a function that will run on the server like
    const blogPages = await getBlogPages();

    and inside you could do this

    const blogPath = "./src/app/blog/[slug]/";
    const getBlogPages = async (): Promise<
      Array<{
        fileName: string;
        path: string;
      }>
    > => {
      const blogPages = await glob("*.mdx", {
        cwd: blogPath,
      });
    // and so on
    

    Now, its still not quite the same as how you would do it in Next < 13, but it accomplishes what you want

    Login or Signup to reply.
  2. I am currently working on same issue, this works but I am not sure this is the right way to go. This will be the page under dynamic route e.g [title]/page.jsx and will receive "title" as a prop.

    import dynamic from 'next/dynamic';
    export default async function Post({params:{title}})
    {
        const Content = await getPostData(title);
        return (<div>{<Content />}</div>)
    }
    
    async function getPostData(title)
    {
        return dynamic(() => import(`../../content/${title}.mdx`));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search