Saturday, 5 August 2023

Simple blog with Next.js 13 + app router — MDX or otherwise

I'm migrating a Gatsby website over to Next.js (v13.4) and using the new App Router. But I'm kinda stumped migrating the blog over, and the newness of the App Router means I'm having trouble finding guidance online that's still accurate.

On Gatsby, one can create a bunch of MDX files with frontmatter and then use a dynamic slug to render those into a page. For the blog index, one makes a page and does a GraphQL query over the frontmatter. Simple, except I think the GraphQL stuff feels heavy for just accessing stuff on the filesystem, which is part of why I'm migrating.

Here's where I'm stuck.

The Index Page

On Next.js, seems like the way to do this is to use regular Node fs and path modules to iterate over the MDX files. Next has a standard metadata format that I think I can use for the metadata? Or I can define my own TypeScript type. But I'm not sure what's the Next-based way to parse that while iterating.

The alternative is to use standard Markdown frontmatter along with gray-matter...which I've now got working but seems like an unnecessary dependency.

The Individual Blog Pages

Here's where I'm stuck. Next's own documentation shows how you import an MDX file in a page, but given I need a dynamic slug, import isn't going to work. What I need to do, I think, is read it off the filesystem and then parse it. gray-matter can separate the frontmatter from the MDX, but doesn't actually parse the MDX.

A lot of examples use Next's remote MDX capabilities, but that seems silly given these files are local.

My suspicion is that I need to abandon Next's MDX package altogether and use something third-party; but I'm not sure what the best practices are there, and again, a lot of the tutorials out there assume the Pages Router.

I could abandon MDX altogether, which makes managing the posts a little more awkward but seems doable. I guess to do that, I'd have to move away from dynamic slugs and make each post its own page.tsx in its own slug-based directory. Which I guess is fine since I can centralize shared stuff in a layout file.

But then I get stuck on the index file again: what's the appropriate method for stripping that metadata out to render the index? The best I can come up with is to move it into its own, say, meta.json file that's read by both the post-level page.tsx and the index, but I don't love that approach.


Anyway. That's a lot. All I want is to set up a simple, low-volume blog that I can edit easily, centralizes its layout information, and auto-generates its index page. And I can't figure out how one is meant to do that in Next.js 13 + App Router. Help?



from Simple blog with Next.js 13 + app router — MDX or otherwise

No comments:

Post a Comment