LESSON 02 / 04

Dynamic Routes

One file for thousands of pages: /blog/[slug], reading params, not-found pages and pre-generating pages at build time.

๐ŸŽ“Mediumlevel
โฑ๏ธ30 minto finish
โœ๏ธ1activities

๐Ÿ“‚ Data & Routing๐Ÿท๏ธ Next.js

๐ŸŽฏ 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.jsx matches /blog/anything.
  • The page receives params (e.g. params.slug).
  • generateStaticParams lists pages to pre-build; notFound() shows the 404 page.

Finished reading & practising?

Saved in this browser. Create a free account to keep it forever.