T
TanStack6mo ago
fair-rose

Pre-rendering or static generation some part of the routes

Hi folks. Are you guys ever trying to do static generation with Tanstack React Router? I have no luck finding any good reference about it. I have an app and want to create the help & support page to be static that live within the app. What I've done so far; not much but I just confused to get things right when getting the HTML of the page. The /docs/$slug component is using MDX and I have no issue in local development.
import { renderToString } from "react-dom/server";
import fs from "node:fs/promises";
import path from "path";
import { createRouter } from "@tanstack/react-router";
import { routeTree } from "../src/routeTree.gen";

async function build() {
const router = createRouter({ routeTree });
const mdxRoutes =
router.routesByPath["/docs/$slug"].options.staticData?.slugs?.map(
(slug) => `/docs/${slug}`,
) ?? [];
const routes = ["/", ...mdxRoutes];

for (const route of routes) {
const html = renderToString(/** what to do */);

const outputPath = path.join(
"dist",
route === "/" ? "index.html" : `${route}/index.html`,
);

await fs.mkdir(path.dirname(outputPath), { recursive: true });
await fs.writeFile(outputPath, html);
}
}

build().catch(console.error);
import { renderToString } from "react-dom/server";
import fs from "node:fs/promises";
import path from "path";
import { createRouter } from "@tanstack/react-router";
import { routeTree } from "../src/routeTree.gen";

async function build() {
const router = createRouter({ routeTree });
const mdxRoutes =
router.routesByPath["/docs/$slug"].options.staticData?.slugs?.map(
(slug) => `/docs/${slug}`,
) ?? [];
const routes = ["/", ...mdxRoutes];

for (const route of routes) {
const html = renderToString(/** what to do */);

const outputPath = path.join(
"dist",
route === "/" ? "index.html" : `${route}/index.html`,
);

await fs.mkdir(path.dirname(outputPath), { recursive: true });
await fs.writeFile(outputPath, html);
}
}

build().catch(console.error);
If you have any thought about this, I really appreciate it. Thank you!
5 Replies
exotic-emerald
exotic-emerald6mo ago
with start you can do prerendering natively
fair-rose
fair-roseOP6mo ago
is it doable to setup with my existing app? i only need to prerender /docs routes and keep the rest with current single index.html
exotic-emerald
exotic-emerald6mo ago
what is not working here?
rival-black
rival-black6mo ago
I think it may be worthwhile to have a MDX demo or something. MDX is amazing but it isn't at all clear how to integrate it with Tan STack Start.
afraid-scarlet
afraid-scarlet6mo ago
@BenHouston3D where you able to figure out how to use mdx with start?

Did you find this page helpful?