Skip to lesson content

PROJECT 2 · LESSON 5 OF 18

Build individual product pages

Use a route parameter to select a product and handle missing products.

  • dynamic routes
  • async params
  • notFound
  • metadata

Your workspace: edushop

Continue from lesson 4: Render products from a file. Keep existing files; create or replace the complete files listed below.

Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.

1. Understand the problem and the concepts

Why we need this feature

Creating a separate source file for every product would make the catalog difficult to maintain. One dynamic route can handle many URLs by looking up the product identified by the URL.

[slug] matches one variable URL segment. In Next.js 16 the params prop is a Promise: await it before reading slug.

A missing product is a normal routing outcome. Return the not-found screen instead of allowing undefined data to crash the page.

A route parameter is input, not the product itself

The [slug] folder is a placeholder for one segment. /products/desk-lamp and /products/pen-set both select the same page module. Next.js supplies different params values. The page then decides which record matches that value.

In this Next.js version, params is asynchronous. Awaiting it gives an object containing slug. The Props type documents that contract. Do not use params.slug directly from an older example when params is a Promise.

Read the lookup and the failure branch

find checks each product and returns the first matching object, or undefined when no product matches. That is why the code checks if (!product) before reading product.name. After that guard, the successful branch can safely use the product.

notFound() interrupts rendering for the route segment and activates its not-found UI. It is not a string you return as the product. Visitors can type arbitrary URLs, and old product links can outlive a catalog entry, so this branch is a normal part of the feature.

Do not confuse a missing product with an unavailable database in later projects. A successful lookup with no match is a not-found result. A failed database connection is an operational error and should not be disguised as a missing product.

Metadata and visible content answer different questions

generateMetadata uses the route input to choose the document title. ProductPage uses the same input to render the visible screen. The first helps browser tabs and page discovery; the second presents the product. Defining metadata does not automatically add an h1.

The local array lookup is inexpensive. When you later replace it with a database operation, understand how repeated reads and caching work before assuming both functions share a single query. Keep the examples correct without depending on invisible caching behavior.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The browser requests /products/desk-lamp.

  2. Next.js matches app/products/[slug]/page.tsx and provides slug = desk-lamp.

  3. The page awaits params, finds the matching record and chooses the successful branch.

  4. The response displays the lamp; an unknown slug instead activates the not-found screen.

Evaluate the lookup for two URLs

  1. For /products/desk-lamp, the comparison fails for the notebook and succeeds for the lamp. product is the lamp object.
  2. The heading reads Desk lamp and money(89900) displays ₹899.00.
  3. For /products/unknown, every comparison fails. product is undefined.
  4. notFound stops the normal page before product.name could throw an error.

3. Build it, one file at a time

  1. Create app/products/[slug]/page.tsx with the exact bracketed folder name.
  2. Add the not-found page.
  3. Open two product links and compare their headings and browser titles.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

app/products/[slug]/page.tsx

This one page handles all product-detail URLs by resolving the requested slug.

app/products/[slug]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { products } from "@/lib/products";
import { money } from "@/lib/money";
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const product = products.find((item) => item.slug === slug);
  return { title: product?.name ?? "Product not found" };
}
export default async function ProductPage({ params }: Props) {
  const { slug } = await params;
  const product = products.find((item) => item.slug === slug);
  if (!product) notFound();
  return (
    <>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
      <strong>{money(product.price)}</strong>
    </>
  );
}

Read the code

  1. Props declares asynchronous params. Await it before extracting slug; [slug] matches the segment but does not prove a product exists.
  2. generateMetadata supplies the document title independently of the visible page heading.
  3. The page checks its lookup result before reading fields. notFound stops the success branch and selects the segment’s fallback UI.
  4. find returns the one matching local product or undefined. money converts the successful record’s paise price for display.

app/products/[slug]/not-found.tsx

This supplies a useful destination when the details page cannot find the requested product.

app/products/[slug]/not-found.tsx
import Link from "next/link";
export default function MissingProduct() {
  return (
    <>
      <h1>Product not found</h1>
      <p>Try another item from our catalog.</p>
      <Link href="/products">Back to products</Link>
    </>
  );
}

Read the code

  1. Next.js renders it when the page calls notFound for this route segment. It is not a catch-all for every database failure.
  2. The return link gives a shopper a recovery path to the catalog rather than leaving a dead end.

4. Run it and check your result

  • /products/desk-lamp shows only the desk lamp.
  • /products/does-not-exist displays the missing-product screen.

5. Predict, change and observe

Change the lamp slug in the product file to reading-lamp. Visit both the old and new URLs.

Compare your prediction with the expected result

What you should observe

The new URL works and the old URL becomes missing.

Why it happens

A slug is part of the public address. In a real store, plan redirects when changing existing slugs so previously shared links remain useful.

6. Troubleshoot with evidence

A common mistake

A folder named slug is a fixed route; [slug] is the dynamic route. Do not use older synchronous params examples.

Every URL shows the same product.

Likely cause: The lookup uses a fixed slug or always reads the first array entry.

Check and correct: Check that find compares item.slug with the awaited route slug.

The fallback never appears and the page crashes.

Likely cause: The code reads product.name before verifying product exists.

Check and correct: Place the notFound guard immediately after the lookup.

7. Practice and explain it back

Your independent task

Add /categories/[category] that reuses ProductCard to display matching products.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why use find rather than filter here?

A details page expects one matching product. find returns that object or undefined, whereas filter returns an array.

Does [slug] validate that the product exists?

No. It matches the URL shape. Your data lookup determines whether the requested product exists.