Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 32 ยท Projects

Project: a product catalog with cart

Build a small Nuxt store: a server API for products, listing and detail pages with useFetch, a shared cart with useState and a safe checkout route.

An online shop is a good test of everything you have learned about Nuxt, because it needs data from a server, pages that search engines can read, state that survives navigation and one action that must never be trusted to the browser: paying. In this project you build the core of a store: a product API, a listing page, a detail page, a cart and a checkout route.

It combines Server routes and the Nitro engine, Data fetching with useFetch and useAsyncData and State with useState and Pinia. The most important lesson is at the end: the server, not the browser, decides prices.

Real or stand-in? The Nuxt files below are real and read-only, because this site cannot run a Nuxt app. The runnable examples are plain JavaScript stand-ins: one imitates the product API handlers with filtering and a 404, and the other is the cart logic with totals and a checkout validation that ignores prices sent by the client.

The pieces

Server API Products and checkout live in server/api.
Listing page useFetch loads the catalog.
Detail page One dynamic route per product.
Cart useState shares it across pages.
1 / 2
sequenceDiagram
    participant B as Browser
    participant S as Nitro server
    B->>S: GET /api/products
    S-->>B: product list
    B->>B: add items to cart (useState)
    B->>S: POST /api/checkout (ids and quantities)
    S->>S: look up real prices, check stock
    S-->>B: order total or error

The browser sends only ids and quantities. The server looks up the prices itself.

Step 1: product data and the API

A real shop reads from a database (Databases and ORMs). To keep the project focused, the data lives in a server utility. Files in server/utils are auto-imported inside the server folder, so every route can call findProducts without an import line.

TypeScript
// server/utils/products.ts (read-only)
export interface Product {
  id: number
  slug: string
  name: string
  category: string
  priceCents: number
  stock: number
}

const products: Product[] = [
  { id: 1, slug: 'trail-mug', name: 'Trail mug', category: 'kitchen', priceCents: 1800, stock: 12 },
  { id: 2, slug: 'field-notebook', name: 'Field notebook', category: 'paper', priceCents: 950, stock: 40 },
  { id: 3, slug: 'ink-pen', name: 'Ink pen', category: 'paper', priceCents: 450, stock: 0 },
]

export function findProducts(category?: string): Product[] {
  return category ? products.filter((p) => p.category === category) : products
}

export function findProduct(slug: string): Product | undefined {
  return products.find((p) => p.slug === slug)
}

export function findProductById(id: number): Product | undefined {
  return products.find((p) => p.id === id)
}

Prices are stored as whole numbers of cents. Money in floating point numbers produces errors such as 0.1 + 0.2, so integers are the safe choice.

TypeScript
// server/api/products/index.get.ts (read-only)
export default defineEventHandler((event) => {
  const { category } = getQuery(event)
  return findProducts(typeof category === 'string' ? category : undefined)
})
TypeScript
// server/api/products/[slug].get.ts (read-only)
export default defineEventHandler((event) => {
  const slug = getRouterParam(event, 'slug') ?? ''
  const product = findProduct(slug)
  if (!product) {
    throw createError({ statusCode: 404, statusMessage: 'Product not found' })
  }
  return product
})

The suffix .get limits each file to GET requests, and createError produces a proper 404 response. The first stand-in imitates the two handlers and a tiny router, so you can call them like a browser would.

JS The product API as plain functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can see the three behaviors the pages will rely on: a full list, a filtered list and a clean 404 with a JSON message.

Step 2: the listing page

The listing page calls the API with useFetch. It runs on the server during the first render, so the HTML already contains the products, which is exactly what search engines want. The category lives in the URL query, so filtered pages can be linked and shared.

VUE
<!-- app/pages/products/index.vue (read-only) -->
<script setup lang="ts">
const route = useRoute()
const category = computed(() => (route.query.category as string | undefined) ?? '')

const { data: products, status } = await useFetch('/api/products', {
  query: { category },
})

useSeoMeta({
  title: 'All products',
  description: 'Mugs, notebooks and pens for the trail.',
})

const { add } = useCart()
const formatPrice = (cents: number) => '$' + (cents / 100).toFixed(2)
</script>

<template>
  <main>
    <h1>Products</h1>
    <nav>
      <NuxtLink to="/products">All</NuxtLink>
      <NuxtLink to="/products?category=paper">Paper</NuxtLink>
      <NuxtLink to="/products?category=kitchen">Kitchen</NuxtLink>
    </nav>
    <p v-if="status === 'pending'">Loading...</p>
    <ul v-else>
      <li v-for="p in products" :key="p.id">
        <NuxtLink :to="'/products/' + p.slug">{{ p.name }}</NuxtLink>
        <span>{{ formatPrice(p.priceCents) }}</span>
        <button :disabled="p.stock === 0" @click="add(p)">
          {{ p.stock === 0 ? 'Sold out' : 'Add to cart' }}
        </button>
      </li>
    </ul>
  </main>
</template>

Passing the category computed value in query makes useFetch watch it: when the query string changes, it fetches again and updates the list. Because useFetch creates its key from the URL and options, the data sent with the server-rendered HTML is reused in the browser, so there is no second request while hydrating.

Step 3: the detail page

The detail page is a dynamic route. A missing product throws a 404 so the error page is shown with the right status.

VUE
<!-- app/pages/products/[slug].vue (read-only) -->
<script setup lang="ts">
const route = useRoute()
const { data: product } = await useFetch('/api/products/' + route.params.slug)

if (!product.value) {
  throw createError({ statusCode: 404, statusMessage: 'Product not found', fatal: true })
}

useSeoMeta({
  title: product.value.name,
  description: 'Buy the ' + product.value.name + ' for $' + (product.value.priceCents / 100).toFixed(2) + '.',
})

const { add } = useCart()
</script>

<template>
  <article v-if="product">
    <h1>{{ product.name }}</h1>
    <p>{{ (product.priceCents / 100).toFixed(2) }} USD</p>
    <button :disabled="product.stock === 0" @click="add(product)">Add to cart</button>
  </article>
</template>

When the API answers 404, useFetch puts the error in error and leaves data empty, so the check above turns it into a page-level 404.

Step 4: the cart with useState

The cart must be shared by every page and component, and it must be safe on the server. The reason to use useState and not a plain ref at module level is covered in State with useState and Pinia: a module-level ref lives as long as the server process and would be shared between visitors. useState stores its value per request and sends it to the browser with the page.

TypeScript
// app/composables/useCart.ts (read-only)
export interface CartLine {
  id: number
  name: string
  priceCents: number
  quantity: number
}

export function useCart() {
  const lines = useState<CartLine[]>('cart', () => [])

  const count = computed(() => lines.value.reduce((n, l) => n + l.quantity, 0))
  const totalCents = computed(() =>
    lines.value.reduce((sum, l) => sum + l.priceCents * l.quantity, 0),
  )

  function add(product: { id: number; name: string; priceCents: number }) {
    const line = lines.value.find((l) => l.id === product.id)
    if (line) {
      line.quantity += 1
    } else {
      lines.value.push({ id: product.id, name: product.name, priceCents: product.priceCents, quantity: 1 })
    }
  }

  function remove(id: number) {
    lines.value = lines.value.filter((l) => l.id !== id)
  }

  function clear() {
    lines.value = []
  }

  return { lines, count, totalCents, add, remove, clear }
}

The composables folder is auto-imported, so every page just calls useCart() and gets the same shared lines. To keep the cart after a page reload, swap useState for useCookie (the data must stay small, because cookies are limited to a few kilobytes) or sync it to localStorage in onMounted. A logged-in shop would keep the cart on the server instead.

The second stand-in is the same cart logic as a plain function, plus a checkout validation that mirrors the server route you will write in the next step.

JS Cart totals and a checkout that distrusts the client

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the tampered request: the client claimed a price of one cent, and the total is still computed from the server's own catalog. Because the server ignores any price in the request, tampering has no effect. The validation also covers empty carts, unknown products, stock and silly quantities.

Step 5: the checkout route

The browser sends only ids and quantities. The server finds the real prices, checks stock and returns the total. A real shop would now create an order in the database and call a payment provider, which is outside this lesson.

TypeScript
// server/api/checkout.post.ts (read-only)
interface CheckoutBody {
  items?: { id: number; quantity: number }[]
}

export default defineEventHandler(async (event) => {
  const body = await readBody<CheckoutBody>(event)

  if (!Array.isArray(body?.items) || body.items.length === 0) {
    throw createError({ statusCode: 400, statusMessage: 'Cart is empty' })
  }

  let totalCents = 0
  for (const item of body.items) {
    const product = findProductById(item.id)
    if (!product) {
      throw createError({ statusCode: 400, statusMessage: 'Unknown product ' + item.id })
    }
    if (!Number.isInteger(item.quantity) || item.quantity < 1 || item.quantity > 10) {
      throw createError({ statusCode: 400, statusMessage: 'Invalid quantity' })
    }
    if (product.stock < item.quantity) {
      throw createError({ statusCode: 409, statusMessage: product.name + ' is out of stock' })
    }
    totalCents += product.priceCents * item.quantity
  }

  return { ok: true, totalCents }
})

On the client, the checkout page posts the cart and clears it after success. $fetch is the right tool here, because a button press is an action, not data needed to render the page (Data fetching with useFetch and useAsyncData).

VUE
<!-- app/pages/checkout.vue (read-only) -->
<script setup lang="ts">
const { lines, totalCents, clear } = useCart()
const message = ref('')
const busy = ref(false)

async function pay() {
  busy.value = true
  message.value = ''
  try {
    const result = await $fetch('/api/checkout', {
      method: 'POST',
      body: { items: lines.value.map((l) => ({ id: l.id, quantity: l.quantity })) },
    })
    message.value = 'Order placed: $' + (result.totalCents / 100).toFixed(2)
    clear()
  } catch (error: any) {
    message.value = error?.statusMessage ?? 'Something went wrong'
  } finally {
    busy.value = false
  }
}
</script>

<template>
  <main>
    <h1>Checkout</h1>
    <p>Total in your browser: ${{ (totalCents / 100).toFixed(2) }}</p>
    <button :disabled="busy || lines.length === 0" @click="pay">Place order</button>
    <p v-if="message">{{ message }}</p>
  </main>
</template>

Ideas to extend the project

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the checkout route look up prices on the server instead of using the price the browser sends?

    Anything from the browser can be changed. The server must compute the total from its own data and treat the request as ids and quantities only.
  2. 2. Why does the cart use useState instead of a ref created at module level?

    Module-level state in a server process is shared by every request. useState keeps a separate value per request and sends it to the browser.
  3. 3. What happens when the query option of useFetch contains a computed value?

    Reactive sources passed to useFetch are watched. Changing the category in the URL triggers a new request and updates the list.
  4. 4. Why are prices stored as integer cents?

    Whole-number cents avoid floating point rounding errors, and you format them as dollars only when displaying.
  5. 5. Why does the checkout button use $fetch instead of useFetch?

    useFetch is for loading data during rendering. For event-driven actions such as submitting an order, $fetch is the right call.

Summary

  • Keep product data and rules on the server in server/utils, and expose them through server/api routes with .get and .post suffixes.
  • Listing and detail pages use useFetch, so their HTML contains the data. A missing product throws a 404.
  • Share the cart with useState inside an auto-imported composable, never with a module-level ref.
  • Store money as integer cents and format it only for display.
  • The checkout route trusts only ids and quantities, then recomputes prices, validates stock and returns the total.

Next: Project: a dashboard with auth