Skip to content
Bishal Rajbahak

लेख · 11 MIN

Next.js MDX Blog with the App Router: A Production Setup

The MDX blog setup behind this site: posts in a content folder, next-mdx-remote-client, reading time, RSS, sitemap, canonical URLs and JSON-LD.

Getting an MDX file to render in Next.js takes about ten minutes. Turning it into a blog that search engines, feed readers and link previews handle properly takes the rest of the weekend.

This is the setup behind the blog you are reading. Posts are plain .mdx files in a content/posts folder. A small loader reads them at build time, and every page is static. Around that sit the pieces most tutorials stop short of: reading time, an RSS feed, a sitemap, canonical URLs, structured data and a social image for every post.

Most guides for this keyword end once the first post renders. The official Next.js guide uses @next/mdx and keeps posts inside the app folder; community guides add next-mdx-remote and gray-matter. I'll cover the same core briefly, then spend most of the article on the production parts, with the code exactly as it runs on this site (Next.js 15, React 19).

Why content lives outside the app folder

@next/mdx treats each .mdx file as a page. That works well for documentation, where every file maps to a route. For a blog I wanted something different:

  • Posts as data, so one loader can feed the post pages, the blog index, the home page, the RSS feed and the sitemap.
  • Frontmatter for title, date, excerpt and tags, read once and typed.
  • One dynamic route, /blogs/[slug], instead of a file per post in app.

So the posts live in content/posts/*.mdx, and rendering uses next-mdx-remote-client. It is a maintained fork of next-mdx-remote with support for the App Router and React 19; version 2 of the package is the React 19 line, so check which major matches your React version before installing.

Step 1: write posts with frontmatter

Each post is one file. The file name becomes the slug:

---
title: "Lessons from Debugging a Stubborn Bug"
date: "2026-03-18"
updated: "2026-12-03"
excerpt: "A bug with no error message that only failed some of the time."
tags: ["Debugging", "Problem solving"]
---

Some bugs are easy to fix. Others stay hidden long enough to test your patience...

Keep the frontmatter small. Everything you can calculate, calculate; I learned that the hard way, which I'll get to in the reading time section.

Step 2: one loader for every page

All of the blog reads posts through lib/posts.ts:

// lib/posts.ts
import "server-only";
import fs from "node:fs";
import path from "node:path";
import matter from "gray-matter";

const POSTS_DIR = path.join(process.cwd(), "content", "posts");

function readAll(): Post[] {
  const files = fs.readdirSync(POSTS_DIR).filter((f) => f.endsWith(".mdx"));
  const posts = files.map((file) => {
    const slug = file.replace(/\.mdx$/, "");
    const raw = fs.readFileSync(path.join(POSTS_DIR, file), "utf8");
    const { data, content } = matter(raw);
    const date = String(data.date ?? "");
    return {
      slug,
      title: String(data.title ?? slug),
      date,
      dateDisplay: formatDisplay(date),
      reading: readingTime(content),
      excerpt: String(data.excerpt ?? ""),
      tags: Array.isArray(data.tags) ? data.tags.map(String) : [],
      updated: String(data.updated ?? date),
      content,
    };
  });
  return posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
}

export const getAllPostsMeta = () => readAll().map(({ content, ...meta }) => meta);
export const getPost = (slug: string) => readAll().find((p) => p.slug === slug);
export const getAllSlugs = () => readAll().map((p) => p.slug);

Three details matter here.

import "server-only" makes the build fail if a client component ever imports this file. The loader uses fs, which does not exist in the browser, and this turns a confusing runtime error into a clear build error.

Every frontmatter value goes through String() or a check. YAML is loose: an unquoted date becomes a Date object, and a missing field becomes undefined. Normalising here means every component downstream gets the shape the types promise.

getAllPostsMeta drops the body. The blog index and home page only need titles and excerpts. Stripping content keeps those pages from carrying every article's full text in their server payload.

Reading files on every call sounds slow, but all of this runs at build time on a static site, where a handful of small files costs nothing. If you have hundreds of posts, wrap readAll in React's cache.

Step 3: the post route

// app/blogs/[slug]/page.tsx
import { notFound } from "next/navigation";
import { MDXRemote } from "next-mdx-remote-client/rsc";
import { getAllSlugs, getPost } from "@/lib/posts";

export function generateStaticParams() {
  return getAllSlugs().map((slug) => ({ slug }));
}

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = getPost(slug);
  if (!post) notFound();

  return (
    <article>
      <h1>{post.title}</h1>
      <MDXRemote source={post.content} />
    </article>
  );
}

generateStaticParams makes Next.js build every post to static HTML at deploy time. In Next.js 15 params is a promise, so it is awaited before use. The README for next-mdx-remote-client suggests its evaluate function when you need frontmatter from the MDX itself; since gray-matter has already split the frontmatter off, the simpler MDXRemote component is enough here.

Reading time: calculate it, never type it

My first version had a reading: "07 MIN" field in each post's frontmatter. I copied it from the first post into the others, and months later every post on the site claimed to be a seven-minute read. The real figure was three.

Now the loader calculates it from the body:

const WORDS_PER_MINUTE = 200;

function readingTime(content: string): string {
  const words = content.split(/\s+/).filter(Boolean).length;
  const minutes = Math.max(1, Math.ceil(words / WORDS_PER_MINUTE));
  return `${String(minutes).padStart(2, "0")} MIN`;
}

Two hundred words per minute is a common rule of thumb, and it is conservative for technical text with code blocks. Pick a number and keep it consistent; nobody times themselves against it.

SEO metadata for each post

Every post exports generateMetadata. The parts that matter most:

export async function generateMetadata({ params }) {
  const { slug } = await params;
  const post = getPost(slug);
  if (!post) return { title: "Not found" };
  const url = `${SITE_URL}/blogs/${slug}`;
  return {
    title: post.title,
    description: post.excerpt,
    alternates: { canonical: url },
    openGraph: {
      type: "article",
      url,
      title: post.title,
      description: post.excerpt,
      publishedTime: post.date,
      modifiedTime: post.updated,
      tags: post.tags,
    },
  };
}

The canonical URL deserves its own line. This site serves every post in four different designs, and each copy points its canonical at /blogs/<slug> so Google indexes one page. Even on a simpler site, a canonical protects you from tracking parameters and trailing slash variants splitting your rankings. I wrote about the four-design setup in Multiple Site Themes in Next.js with Middleware.

The excerpt doubles as the meta description, so I keep it under about 155 characters, which is roughly where Google truncates descriptions on desktop.

Structured data with JSON-LD

A BlogPosting object tells search engines who wrote the article and when:

const jsonLd = {
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  headline: post.title,
  description: post.excerpt,
  datePublished: post.date,
  dateModified: post.updated,
  author: { "@type": "Person", name: "Bishal Rajbahak", url: SITE_URL },
  mainEntityOfPage: { "@type": "WebPage", "@id": url },
};

<script
  type="application/ld+json"
  dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
/>

The replace on the last line is easy to miss. JSON.stringify happily outputs a </script> sequence if one appears in a title or excerpt, and that would end the script tag early. Escaping < as < keeps the JSON valid and the page safe.

Keep dateModified honest. I added an updated field to the frontmatter and fall back to the publish date, so the structured data only claims an update when there really was one.

RSS feed as a route handler

Feed readers still bring a steady trickle of developers, and an RSS feed is about thirty lines with a route handler:

// app/feed.xml/route.ts
export const dynamic = "force-static";

const esc = (s: string) =>
  s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");

export function GET() {
  const items = getAllPostsMeta()
    .map((p) => {
      const url = `${SITE_URL}/blogs/${p.slug}`;
      return `<item>
  <title>${esc(p.title)}</title>
  <link>${url}</link>
  <guid isPermaLink="true">${url}</guid>
  <pubDate>${new Date(p.date).toUTCString()}</pubDate>
  <description>${esc(p.excerpt)}</description>
</item>`;
    })
    .join("\n");

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"><channel>
  <title>Writing</title>
  <link>${SITE_URL}/</link>
  ${items}
</channel></rss>`;

  return new Response(xml, { headers: { "content-type": "application/rss+xml; charset=utf-8" } });
}

A folder named feed.xml gives the route a real .xml URL, and force-static makes Next.js generate the file once at build time. Escape every text field: a single & in a title is enough to break the whole feed. Then advertise the feed in your metadata so readers can discover it:

alternates: { types: { "application/rss+xml": [{ url: "/feed.xml", title: "Writing" }] } }

Sitemap

The App Router turns app/sitemap.ts into sitemap.xml. Feed it from the same loader:

// app/sitemap.ts
export default function sitemap() {
  const posts = getAllPostsMeta();
  return [
    { url: `${SITE_URL}/`, lastModified: new Date() },
    { url: `${SITE_URL}/blogs`, lastModified: new Date(posts[0]?.date ?? Date.now()) },
    ...posts.map((p) => ({ url: `${SITE_URL}/blogs/${p.slug}`, lastModified: new Date(p.updated) })),
  ];
}

Using updated for lastModified means a post you rewrote gets recrawled, and one you never touched does not pretend to be fresh.

A social image for every post

Each post gets a generated preview image for Slack, LinkedIn and X, built with ImageResponse from next/og. I started with the opengraph-image.tsx file convention, which is the documented way. It worked on the main post URL, but Next.js serves those images at a URL with a hash appended, and I needed other pages to reference the same image. A route handler at app/blogs/[slug]/og.png/route.tsx gives every post one stable image URL, which I then list in the post metadata myself.

If your posts only live at one URL each, the file convention is simpler, and I would start there.

Styling the MDX output

MDXRemote renders plain h2, p, ul and pre elements, and if you use Tailwind its reset removes their default margins and list styles. I give the wrapper a class and style the elements inside it, with the spacing set on the parent so headings and paragraphs keep a steady rhythm:

.prose > * + * { margin-top: 1.1em; }
.prose h2 { margin-top: 1.9em; font-size: 28px; }
.prose ul { list-style: disc; padding-left: 1.3em; }
.prose pre { overflow-x: auto; }

overflow-x: auto on pre matters on phones. Without it, one long line of code widens the whole page and the reader can scroll sideways, which I have also debugged on this site. The @tailwindcss/typography plugin is a fine shortcut if you do not want to write these rules.

Frequently asked questions

Should I use @next/mdx or next-mdx-remote-client?

Use @next/mdx when each MDX file is its own page, such as documentation. Use next-mdx-remote-client (or next-mdx-remote) when posts are data that several pages need, like a blog index, an RSS feed and a sitemap all reading the same files.

Can MDX posts still be static in the App Router?

Yes. With generateStaticParams listing every slug, Next.js renders each post to static HTML at build time. Nothing in the setup above reads cookies or headers, so no page needs dynamic rendering.

How do I add a reading time to MDX posts?

Count the words in the post body and divide by an average reading speed; 200 words per minute is a common choice. Calculate it in your loader instead of storing it in frontmatter, so it can never go stale.

Do I need a CMS for a developer blog?

Not for a personal blog. MDX files in your repository give you version history, review through pull requests and zero hosting cost. A CMS starts to pay off when people who don't use Git need to publish.

How do I add an RSS feed to a Next.js App Router blog?

Create a route handler in a folder named feed.xml, build the XML from your post list, escape every text field, and set export const dynamic = "force-static" so it is generated at build time.

Wrapping up

The rendering is the smallest part of an MDX blog. What makes it a good blog is one loader that every feature reads from, values calculated instead of typed, and the metadata layer around it: canonical URLs, honest dates, structured data, a feed and a sitemap.

The rest of what I have written lives on the Writing page. If you are curious how one blog post can appear in four completely different designs, that is the middleware post.

  • Next.js
  • MDX
  • React
  • SEO

All writing

EditionKathmandu