javascript 44 lines · 8 steps

Building a dynamic blog post page in Next.js

An async Server Component fetches a post by slug, generates its metadata, and streams related posts with Suspense.

Explained by highlit
1import { notFound } from 'next/navigation'
2import { Suspense } from 'react'
3import { getPostBySlug, getRelatedPosts } from '@/lib/posts'
4import { RelatedPosts } from '@/components/related-posts'
5 
6export async function generateMetadata({ params }) {
7 const { slug } = await params
8 const post = await getPostBySlug(slug)
9 
10 if (!post) {
11 return { title: 'Post not found' }
12 }
13 
14 return {
15 title: post.title,
16 description: post.excerpt,
17 }
18}
19 
20export default async function PostPage({ params }) {
21 const { slug } = await params
22 const post = await getPostBySlug(slug)
23 
24 if (!post || post.status !== 'published') {
25 notFound()
26 }
27 
28 return (
29 <article className="prose mx-auto py-12">
30 <header>
31 <h1>{post.title}</h1>
32 <time dateTime={post.publishedAt}>
33 {new Date(post.publishedAt).toLocaleDateString()}
34 </time>
35 </header>
36 
37 <div dangerouslySetInnerHTML={{ __html: post.html }} />
38 
39 <Suspense fallback={<p>Loading related posts…</p>}>
40 <RelatedPosts promise={getRelatedPosts(post.id)} />
41 </Suspense>
42 </article>
43 )
44}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Async Server Components let you await data directly in the component body instead of wiring up client-side fetching.
  2. 2generateMetadata and the page share the same data-loading pattern so SEO tags and rendered content stay in sync.
  3. 3Passing an unawaited promise into a Suspense boundary streams slower content without blocking the main article.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a dynamic blog post page in Next.js — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code