๐ฏ By the end of this lesson you canโฆ
- Create dynamic segments with [param]
- Read params in a page
- Pre-render with generateStaticParams and handle notFound
โ๏ธ JSX
app/blog/[slug]/page.jsx
๐ Tap a line to explain it
1import { notFound } from "next/navigation";2import { getPost, getAllPosts } from "@/lib/posts";3 4export async function generateStaticParams() {5 const posts = await getAllPosts();6 return posts.map((p) => ({ slug: p.slug }));7}8 9export default async function PostPage({ params }) {10 const { slug } = await params;11 const post = await getPost(slug);12 if (!post) notFound();13 return (14 <article>15 <h1>{post.title}</h1>16 <p>{post.body}</p>17 </article>18 );19}
The URL matching itself is simple logic โ try it:
๐ ๏ธ Match a route
Write matchRoute(pattern, path) that returns the params object when the path matches a pattern like /blog/[slug] or /shop/[category]/[id], or null if it doesnโt match.
๐ Key takeaways
app/blog/[slug]/page.jsxmatches/blog/anything.- The page receives
params(e.g.params.slug). generateStaticParamslists pages to pre-build;notFound()shows the 404 page.
Finished reading & practising?
Saved in this browser. Create a free account to keep it forever.