← Return home

Dynamic imports of MDX files in Next.js

I've been working with Next.js recently, but MDX documentation remains a bit sparse.

Say you keep your MDX files in the following path: pages/blog/*.mdx.

You can export variables as an alternative to YAML frontmatter:

// blog-post.mdx
export const metadata = {
title: "My blog post!",
slug: "my-blog-post",
};

Then, in any other page where you need to grab all your MDX metadata, you can use the following code, which makes use of dynamic imports:

// list-page.tsx
export const getStaticProps: GetStaticProps = async (context) => {
// fetch posts
const postDirectory = path.join(process.cwd(), "pages/blog");
const postFilenames = fs.readdirSync(postDirectory);
const postModules = await Promise.all(
postFilenames.map(async (p) => import(`pages/blog/${p}`))
);
const postMetadata = postModules.map((m) => m.metadata);
// return props
return {
props: {
postMetadata: postMetadata,
},
};
};

You can access this postMetadata prop anywhere in your frontend, and render out your list of blog posts. With this, you neither need fancy plugins to get YAML frontmatter, nor do you need to read and convert your MDX to AST.