Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 72 ยท Projects

Project: A Markdown Blog

Build a fast, SEO-friendly Markdown blog in Next.js: file-based posts, generateStaticParams, metadata, a sitemap and the MDX option, with runnable stand-ins.

A blog is the classic first real Next.js project, and it is a good one, because it uses the features that make the framework worth learning: file-based routes, pages built ahead of time, per-page metadata for search engines, and a clean separation between content and code. In this project you write posts as Markdown files, and Next.js turns them into fast static pages.

We will build four things: a data layer that reads the posts, a home page that lists them, a post page with proper metadata, and a sitemap. Then we look at MDX, which lets you use React components inside posts. This lesson combines Static Generation and generateStaticParams, Dynamic Routes and Metadata and SEO.

Real or stand-in? The Next.js app below is real code in read-only blocks, because this site cannot run a Next.js build. The two runnable examples are Node.js stand-ins that do the same jobs by hand: one reads post files and works out the routes, the page params and the sitemap, and the other renders a post page with its metadata and a 404. Together they show what the framework does for you behind the scenes.

The plan

What we are building

Posts Markdown files with front matter.
Data layer One module reads and sorts them.
Pages A list page and a post page.
SEO Metadata and a sitemap.
1 / 2
flowchart LR
    M["content/posts/*.md"] --> D["getAllPosts()"]
    D --> G["generateStaticParams()"]
    G --> P["One HTML page per post"]
    D --> S["sitemap.ts"]
    D --> H["Home page list"]

At build time the same data layer feeds the pages, the page list and the sitemap.

Project structure

TEXT
my-blog/
  content/
    posts/
      hello-nextjs.md
      why-server-components.md
  lib/
    posts.ts
  app/
    layout.tsx
    page.tsx
    blog/
      [slug]/
        page.tsx
    sitemap.ts
  next.config.ts

Each post is a Markdown file with front matter, a block of metadata between two --- lines at the top:

MARKDOWN
---
title: Why Server Components?
description: Keep data access and heavy libraries on the server.
date: 2026-02-03
tags: [nextjs, react]
draft: false
---

Server Components run **only** on the server.

## What you gain

- Less JavaScript in the browser
- Direct access to your data

The file name is the URL slug: why-server-components.md becomes /blog/why-server-components. That keeps the content folder simple and the URLs stable.

Step 1: the data layer

All reading of files lives in one module. The pages never touch the file system, which keeps them simple and makes the source of posts easy to replace later, for example with a database or a CMS (see Data Access Layers and ORMs).

TypeScript
// lib/posts.ts
import 'server-only';
import { cache } from 'react';
import fs from 'node:fs/promises';
import path from 'node:path';
import matter from 'gray-matter';

const postsDirectory = path.join(process.cwd(), 'content', 'posts');

export type Post = {
  slug: string;
  title: string;
  description: string;
  date: string; // YYYY-MM-DD
  tags: string[];
  body: string;
};

export const getAllPosts = cache(async (): Promise<Post[]> => {
  const names = (await fs.readdir(postsDirectory)).filter((name) => name.endsWith('.md'));

  const posts = await Promise.all(
    names.map(async (name) => {
      const raw = await fs.readFile(path.join(postsDirectory, name), 'utf8');
      const { data, content } = matter(raw);
      return {
        slug: name.replace(/\.md$/, ''),
        title: String(data.title),
        description: String(data.description ?? ''),
        // YAML turns an unquoted 2026-02-03 into a Date object.
        date: data.date instanceof Date ? data.date.toISOString().slice(0, 10) : String(data.date),
        tags: Array.isArray(data.tags) ? data.tags.map(String) : [],
        draft: data.draft === true,
        body: content,
      };
    }),
  );

  return posts
    .filter((post) => !post.draft)
    .sort((a, b) => (a.date < b.date ? 1 : -1))
    .map(({ draft, ...post }) => post);
});

export async function getPost(slug: string): Promise<Post | undefined> {
  const posts = await getAllPosts();
  return posts.find((post) => post.slug === slug);
}

Four details deserve a comment. The import 'server-only' line makes the build fail if a Client Component ever imports this file (see Keeping Server Code on the Server). cache from React shares one result between the home page, the post page and the sitemap during a single render, so the files are read once. gray-matter is a small, popular package that parses front matter, and it hands you a Date for unquoted dates, hence the conversion. And drafts are removed here, in one place, so no page can accidentally publish one.

The first stand-in does the same job without any packages. It parses front matter by hand, drops drafts, sorts by date and then computes what Next.js would compute from the result: the static params, each post's newer and older neighbor, tag counts and a sitemap.

Node.js From post files to routes and a sitemap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice what the build would learn from this one pass. Three published posts become three static params. The draft never reaches a route or the sitemap. And a file with broken front matter stops the build with a clear message instead of publishing a half-empty page. That last behavior is worth keeping in the real data layer: validate early, fail loudly, and you never ship a post without a title.

Step 2: the layout and the home page

The root layout carries what every page shares, including the title template so each page only supplies its own part of the title, and metadataBase, which lets relative URLs in metadata become absolute.

TSX
// app/layout.tsx
import type { Metadata } from 'next';
import Link from 'next/link';

export const metadata: Metadata = {
  metadataBase: new URL('https://blog.example.com'),
  title: { default: 'My Blog', template: '%s | My Blog' },
  description: 'Notes on building with Next.js.',
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <header>
          <Link href="/">My Blog</Link>
        </header>
        <main>{children}</main>
      </body>
    </html>
  );
}
TSX
// app/page.tsx
import Link from 'next/link';
import { getAllPosts } from '@/lib/posts';

export default async function Home() {
  const posts = await getAllPosts();

  return (
    <>
      <h1>Latest posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.slug}>
            <Link href={'/blog/' + post.slug}>{post.title}</Link>
            <time dateTime={post.date}> {post.date}</time>
            <p>{post.description}</p>
          </li>
        ))}
      </ul>
    </>
  );
}

This page reads no cookies, headers or search params, so Next.js prerenders it at build time. It is plain static HTML on your CDN.

Step 3: the post page

The post page is the heart of the project. It does four jobs: it tells Next.js which slugs exist, builds metadata for each post, loads the post, and renders the Markdown.

TSX
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Markdown from 'react-markdown';
import { getAllPosts, getPost } from '@/lib/posts';

type Props = { params: Promise<{ slug: string }> };

export const dynamicParams = false;

export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((post) => ({ slug: post.slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) return {};

  return {
    title: post.title,
    description: post.description,
    alternates: { canonical: '/blog/' + post.slug },
    openGraph: {
      type: 'article',
      title: post.title,
      description: post.description,
      publishedTime: post.date,
    },
  };
}

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

  return (
    <article>
      <h1>{post.title}</h1>
      <time dateTime={post.date}>{post.date}</time>
      <Markdown>{post.body}</Markdown>
    </article>
  );
}

Walk through it:

  • params is a promise in current Next.js, so both generateMetadata and the page await it.
  • generateStaticParams returns one object per post. At build time Next.js renders the page once for each, so every post is ready-made HTML.
  • dynamicParams = false says "only the slugs I listed exist". Any other slug returns a 404 without running your code. If you left it out (the default is true), an unknown slug would be rendered on demand the first time it is requested, which is useful for huge sites but unnecessary for a blog whose content is in the repository.
  • generateMetadata runs on the server and produces the <title>, description, canonical link and Open Graph tags. The root layout's template turns the post title into "Why Server Components? | My Blog".
  • react-markdown renders Markdown as React elements and does not execute raw HTML in posts by default, which is the safe choice. If you trust your authors and need HTML in posts, you have to opt in with an extra plugin and accept the risk.
  • notFound() is still called, because it narrows the TypeScript type and keeps the page correct if you ever turn dynamicParams back on.

When you run next build, the output lists /blog/[slug] as a statically generated route, with each real path printed beneath it. Adding a post means adding a file and rebuilding or redeploying.

The second stand-in plays the part of this page. It converts Markdown to HTML (a tiny subset, with escaping), builds the head tags, and answers an unknown slug with a 404, like dynamicParams = false does.

Node.js Render a post page with metadata and a 404

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first response shows the whole contract of a blog page: a unique title, description and canonical URL in the head, one h1, a time element with a machine-readable date, and body headings shifted down one level so the document keeps a single h1. The <script> text in the post came out as &lt;script&gt;, escaped and harmless. The second response is the 404 that dynamicParams = false produces, with noindex so search engines do not list it.

Step 4: the sitemap

Search engines find your posts faster when you list them. A sitemap.ts file in app/ becomes /sitemap.xml:

TypeScript
// app/sitemap.ts
import type { MetadataRoute } from 'next';
import { getAllPosts } from '@/lib/posts';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getAllPosts();

  return [
    { url: 'https://blog.example.com', lastModified: new Date() },
    ...posts.map((post) => ({
      url: 'https://blog.example.com/blog/' + post.slug,
      lastModified: new Date(post.date),
    })),
  ];
}

Because it uses the same getAllPosts, a new post appears in the sitemap automatically, and a draft never does. Pair it with a robots.ts that points to the sitemap (see Metadata and SEO).

Going further with MDX

MDX is Markdown that can import and use React components. A post can then contain an interactive chart or a custom callout instead of only text. The official @next/mdx package supports it. You enable it in the config and add a small file that maps Markdown elements to your own components:

TypeScript
// next.config.ts
import createMDX from '@next/mdx';
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  pageExtensions: ['ts', 'tsx', 'md', 'mdx'],
};

const withMDX = createMDX({});

export default withMDX(nextConfig);
TSX
// mdx-components.tsx (project root)
import type { MDXComponents } from 'mdx/types';

export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    h2: ({ children }) => <h2 className="mt-8 text-2xl font-bold">{children}</h2>,
    ...components,
  };
}

A post file such as content/hello.mdx can then export its own metadata and render components:

MDX
export const metadata = { title: 'Hello MDX', description: 'A post with a component.' };

# Hello MDX

<Callout>This is a React component inside a post.</Callout>

and the post page imports it dynamically by slug:

TSX
// app/blog/[slug]/page.tsx (MDX version)
export const dynamicParams = false;

export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const { default: Post } = await import('@/content/' + slug + '.mdx');
  return <Post />;
}

The trade-off is control. Plain Markdown with react-markdown is safer for content written by many people and easy to move elsewhere. MDX gives authors power but ties posts to your component set, and it should only be used for content you trust.

Ideas to extend the project

  • A tag page at app/blog/tags/[tag]/page.tsx that filters getAllPosts().
  • An RSS feed in app/feed.xml/route.ts, built with a Route Handler.
  • Newer and older links at the bottom of each post, using the neighbor logic from the first stand-in.
  • An Open Graph image for each post with an opengraph-image.tsx file (see Templates and Other Special Files).
  • A revalidate setting and on-demand revalidation if posts move from files to a CMS (see Revalidating Data).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does generateStaticParams do for app/blog/[slug]/page.tsx?

    generateStaticParams returns an array of params objects. Next.js renders the page once per object during the build.
  2. 2. With export const dynamicParams = false, what happens for a slug that was not returned by generateStaticParams?

    dynamicParams = false means only the listed params exist. Everything else is a 404.
  3. 3. Why does the data layer start with import 'server-only'?

    The server-only package throws at build time when a Client Component imports the module, which protects server-side code and secrets.
  4. 4. Why is a title template (title.template) set in the root layout?

    With template '%s | My Blog', a page that sets title 'Caching Notes' ends up as 'Caching Notes | My Blog'.
  5. 5. What is the main trade-off of MDX compared with plain Markdown?

    MDX is powerful because it executes JavaScript and components. That makes it a poor fit for untrusted content and less portable than plain Markdown.

Summary

  • Store posts as Markdown files with front matter, and read them in one server-only data layer that parses, filters drafts and sorts.
  • generateStaticParams plus dynamicParams = false gives you one prebuilt page per post and a clean 404 for everything else.
  • generateMetadata and a title template produce unique titles, descriptions, canonical links and Open Graph tags.
  • sitemap.ts reuses the same data layer, so new posts are listed automatically.
  • Use react-markdown for safe content, or MDX when authors need React components.
  • Validate content at build time so a broken post stops the build instead of reaching readers.

Next: Project: An Admin Dashboard