CodeBlanks Logo Icon CodeBlanks

Cart API

Write a POST API route that adds a product to the cart.

Project outcome

In this project we built a store with Next.js: static home, dynamic product page, cart API. We combined three core App Router features (SSG, dynamic route, API route).

The static home is built at build time, the dynamic product via generateStaticParams, the cart API via route.js.

At the end you have the skeleton of a real store: list products, view details, add to cart.

Final step: combine

Now you combine all pieces in one flow. You write the products array, Home, generateStaticParams and Page components together.

Home shows the product list, Page shows the selected product's detail. generateStaticParams tells Next.js which product pages to pre-render at build time.

This is the foundation of real e-commerce sites; SEO-friendly and fast.

Practice Store final

Combine all pieces: write Home (a products array, render <ul> with <li>{product.name}</li>). Write generateStaticParams (products.map(p => ({ params: { id: String(p.id) } }))). Write Page ({ params } destructure, find the product, <h1>{product.name}</h1>). Define const products = [{ id: 1, name: "Pen" }, { id: 2, name: "Notebook" }]. export default Home and export default Page.

Starter code

App.jsx
// app/page.js ve app/product/[id]/page.js

// products dizisi, Home, generateStaticParams ve Page buraya yaz

Sample solution

App.jsx
// app/page.js
const products = [{ id: 1, name: "Pen" }, { id: 2, name: "Notebook" }];

export default function Home() {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

// app/product/[id]/page.js
export async function generateStaticParams() {
  return products.map((p) => ({ params: { id: String(p.id) } }));
}

export default function Page({ params }) {
  const product = products.find((p) => p.id === Number(params.id));
  return <h1>{product.name}</h1>;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which feature is NOT in this project?

  • Dynamic product page
  • Static home page
  • Authentication Correct answer
  • Cart API

Explanation: Project scope = static + dynamic + API.

2 generateStaticParams return

Question
export async function generateStaticParams() {
  return products.map((p) => ({
    ____: { id: String(p.id) }
  }));
}
Answer
export async function generateStaticParams() {
  return products.map((p) => ({
    params: { id: String(p.id) }
  }));
}

Explanation: params links the id to the URL.

3 Cart API: match the terms

Term Meaning
app/page.js Static home
[id]/page.js Dynamic product
api/cart/route.js Cart API
generateStaticParams Static build

All lessons in Advanced