javascript
64 lines · 7 steps
Static MDX blog pages in Next.js
A Next.js App Router page reads Markdown files at build time and renders them as MDX with plugins.
Explained by
highlit
1import fs from 'node:fs/promises';
2import path from 'node:path';
3import { notFound } from 'next/navigation';
4import matter from 'gray-matter';
5import { MDXRemote } from 'next-mdx-remote/rsc';
6import remarkGfm from 'remark-gfm';
7import rehypeSlug from 'rehype-slug';
8
9const POSTS_DIR = path.join(process.cwd(), 'content', 'blog');
10
11async function getPost(slug) {
12 try {
13 const raw = await fs.readFile(path.join(POSTS_DIR, `${slug}.md`), 'utf8');
14 const { content, data } = matter(raw);
15 return { content, frontmatter: data };
16 } catch {
17 return null;
18 }
19}
20
21export async function generateStaticParams() {
22 const files = await fs.readdir(POSTS_DIR);
23 return files
24 .filter((file) => file.endsWith('.md'))
25 .map((file) => ({ slug: file.replace(/\.md$/, '') }));
26}
27
28export async function generateMetadata({ params }) {
29 const { slug } = await params;
30 const post = await getPost(slug);
31 if (!post) return {};
32 return {
33 title: post.frontmatter.title,
34 description: post.frontmatter.excerpt,
35 };
36}
37
38export default async function BlogPostPage({ params }) {
39 const { slug } = await params;
40 const post = await getPost(slug);
41 if (!post) notFound();
42
43 return (
44 <article className="prose mx-auto py-12">
45 <h1>{post.frontmatter.title}</h1>
46 <time dateTime={post.frontmatter.date}>
47 {new Date(post.frontmatter.date).toLocaleDateString('en-US', {
48 year: 'numeric',
49 month: 'long',
50 day: 'numeric',
51 })}
52 </time>
53 <MDXRemote
54 source={post.content}
55 options={{
56 mdxOptions: {
57 remarkPlugins: [remarkGfm],
58 rehypePlugins: [rehypeSlug],
59 },
60 }}
61 />
62 </article>
63 );
64}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Reading content from the filesystem in a Server Component lets you pre-render pages at build time with no runtime database.
- 2generateStaticParams and generateMetadata let one dynamic route file produce many fully static, SEO-ready pages.
- 3MDXRemote's rsc entry renders MDX on the server, so remark and rehype plugins run without shipping the parser to the browser.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/static-mdx-blog-pages-in-next-js-explained-javascript-b960/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.