How to dynamically prerender blog post routes from MDX files? #13849
-
Hi there, I’m building a blog with React Router 7 and using MDX files for my posts. I want to prerender all my blog post routes, but I don’t want to manually update the Currently, my posts are loaded dynamically at runtime using the following export const postModules = import.meta.glob("../routes/blog/**/*.mdx", {
eager: true,
import: "handle",
});
export async function getPosts() {
const { routes } = await import("virtual:react-router/server-build");
let files = Object.entries(postModules).map(([path, handle]) => {
const metadata = postHandleSchema.parse(handle);
const id = path.replace("../", "").replace(/\.mdx$/, "");
const slug = routes[id]?.path;
if (slug === undefined) throw new Error(`No route for ${id}`);
return { slug: `/${slug}`, metadata };
});
return files;
} But for prerendering, I need to list all the routes in the // react-router.config.ts
export default {
prerender: [
"/blog/my-first-post",
"/blog/another-post",
// ...etc
],
} satisfies Config; I tried importing the post slugs dynamically using the same // react-router.config.ts
export default {
async prerender() {
const posts = await getPosts();
return posts.map(({ slug }) => slug);
},
} satisfies Config; However I get the following error:
I understand this is because the config runs before the virtual modules are available, but my question is: Is there a way to dynamically generate the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I just realized that you can access the static paths via // react-router.config.ts
import type { Config } from "@react-router/dev/config";
import { href } from "react-router";
import { isDraft } from "./app/lib/utils";
export default {
prerender({ getStaticPaths }) {
const paths = getStaticPaths();
const publishedPosts = paths.filter(
(path) => path.startsWith("/blog/") && !isDraft(path),
);
return [href("/privacy-policy"), href("/legal-notice"), ...publishedPosts];
},
} satisfies Config; |
Beta Was this translation helpful? Give feedback.
I just realized that you can access the static paths via
getStaticPaths
inside theprerender
function. This allows me to dynamically filter out draft posts and prerender only the published ones: