Skip to content

The product list ​

The need: an employee opens the back office and immediately sees the products in the database, with a readable price and a clear signal when stock is low.

Related rules: Products · Talking to the API

1. API access ​

Everything starts in web/lib/products.js. The highlighted lines are used for reading:

js
// API_URL est lue au moment de la requête (et non au build) :
// la même image Docker fonctionne ainsi en dev comme en prod.
function productsUrl() {
  const apiUrl = process.env.API_URL;
  if (!apiUrl) {
    throw new Error('API_URL is not defined');
  }
  return `${apiUrl}/api/products/`;
}

function checkResponse(response) {
  if (!response.ok) {
    throw new Error(`API responded with status ${response.status}`);
  }
}

export async function fetchProducts() {
  const response = await fetch(productsUrl(), { cache: 'no-store' });
  checkResponse(response);

  const data = await response.json();
  // DRF renvoie { results: [...] } quand la pagination est activée.
  return Array.isArray(data) ? data : data.results ?? [];
}

export async function createProduct(product) {
  const response = await fetch(productsUrl(), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(product),
  });
  checkResponse(response);
  return response.json();
}

export async function deleteProduct(id) {
  const response = await fetch(`${productsUrl()}${id}/`, { method: 'DELETE' });
  checkResponse(response);
}

productsUrl() (lines 3-9) builds the address from API_URL. If the variable is missing, it throws a clear error instead of calling undefined/api/products/.

checkResponse() (lines 11-15) turns any error response into an exception. fetch does not throw on a 404 or a 500: without this function, we would try to read error JSON as a list.

fetchProducts() (lines 17-24) calls the API and always returns an array.

Why cache: 'no-store'?

Next.js can cache the result of fetch. For a stock back office, a stale list is worse than one more request: the cache is disabled.

Why handle data.results?

Django REST Framework returns { count, results } when pagination is enabled. It is not today, but line 23 keeps the page from breaking the day Patrice enables it.

2. The page ​

js
import ProductForm from '../components/ProductForm';
import ProductList from '../components/ProductList';
import { fetchProducts } from '../lib/products';

// La page est rendue à chaque requête : sans ça, Next essaierait d'appeler
// l'API pendant le build, alors qu'elle n'existe pas dans le job CI.
export const dynamic = 'force-dynamic';

export default async function HomePage() {
  let products = [];
  let error = null;

  try {
    products = await fetchProducts();
  } catch (e) {
    error = e.message;
  }

  return (
    <main>
      <div className="page-title">
        <h1>Produits</h1>
        {!error && <span className="count">{products.length} produit{products.length > 1 ? 's' : ''}</span>}
      </div>
      {error ? (
        <p role="alert" className="alert">API indisponible : {error}</p>
      ) : (
        <>
          <ProductForm />
          <ProductList products={products} />
        </>
      )}
    </main>
  );
}

Line 7: force-dynamic forces Next.js to build the page on every request. Without it, next build would try to pre-render it and call the API, which does not exist in the build job. The build would fail.

Lines 13-17: the error is caught. The page shows a banner rather than the Next.js error page.

Lines 25-32: without an API, neither the form nor the table is shown. Adding a product would fail anyway.

3. The table ​

js
import { removeProduct } from '../app/actions';

function formatPrice(price) {
  return `${Number(price).toFixed(2).replace('.', ',')} €`;
}

function stockStatus(stock) {
  if (stock === 0) {
    return { label: 'Rupture', tone: 'badge-danger' };
  }
  if (stock < 10) {
    return { label: 'Stock faible', tone: 'badge-warning' };
  }
  return { label: 'En stock', tone: 'badge-success' };
}

export default function ProductList({ products }) {
  if (products.length === 0) {
    return (
      <div className="card">
        <p className="empty">Aucun produit.</p>
      </div>
    );
  }

  return (
    <div className="card">
      <table className="products">
        <thead>
          <tr>
            <th>Produit</th>
            <th className="num">Prix</th>
            <th className="num">Stock</th>
            <th>État</th>
            <th />
          </tr>
        </thead>
        <tbody>
          {products.map((product) => {
            const status = stockStatus(product.stock);
            return (
              <tr key={product.id}>
                <td>
                  <span className="name">{product.name}</span>
                  {product.description && <span className="description">{product.description}</span>}
                </td>
                <td className="num">{formatPrice(product.price)}</td>
                <td className="num">{product.stock}</td>
                <td>
                  <span className={`badge ${status.tone}`}>{status.label}</span>
                </td>
                <td className="num">
                  <form action={removeProduct}>
                    <input type="hidden" name="id" value={product.id} />
                    <button type="submit" className="delete" aria-label={`Supprimer ${product.name}`}>
                      Supprimer
                    </button>
                  </form>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

formatPrice() (lines 3-5): the API sends the price as text ("2.50"), because an exact decimal does not fit in a JavaScript number. We convert it, fix two decimals and replace the dot with a comma.

stockStatus() (lines 7-15) returns the badge label and CSS class. The threshold of 10 is the "low stock" rule described in Products.

Why isn't this a client component?

It only displays. The Delete button is a classic HTML <form> calling a Server Action: no JavaScript needed in the browser. Less code shipped, faster page.

4. The health route ​

js
// GET /api/health : utilisé par le HEALTHCHECK Docker, Traefik et le job
// de déploiement pour savoir si le conteneur est prêt à recevoir du trafic.
export const dynamic = 'force-dynamic';

export function GET() {
  return Response.json({ status: 'ok' });
}

It always answers {"status":"ok"}, without calling the API. If it depended on the API, an API outage would also mark the web as down, and Swarm would restart it for nothing.

Pitfalls ​

The price is a string

Never compute directly on product.price: "2.50" + 1 gives "2.501". Convert with Number() first.

fetch does not throw on a 4xx or 5xx

Any new function in lib/products.js must go through checkResponse().

What to remember ​

  • A single file talks to the API: lib/products.js.
  • The page is rendered on every request and does not crash if the API is missing.
  • The price arrives as text, the badge depends on a threshold of 10.