Project 4: An E-Commerce Back End

Node.js and Express: Build a Back End API from Scratch · Ten Portfolio Projects · 9 min read · Updated

Checkout steps

  1. The cart holds only product ids and quantities.
  2. The server looks up each price and checks stock again.
  3. It charges the provider. A decline stops here with 402 and nothing changes.
  4. Only after success does it reduce stock, save the order and clear the cart.

An online shop is the classic big portfolio project, and the code behind it is more interesting than the screens. Money is involved, stock is limited, and two customers may want the last item at the same moment. This project builds the core: products, a cart for each user, and checkout. Its real lessons are all about trust: never trust the price sent by the browser, check stock again at the moment of purchase, and never reduce stock for a payment that failed.

What you will build

  • GET /api/products shows products that are in stock.
  • POST /api/products lets an admin add a product with a price in cents and a stock count.
  • PUT /api/cart/:productId sets the quantity of a product in your cart, and 0 removes it.
  • POST /api/orders turns the cart into an order, charges the payment provider, reduces stock and empties the cart.
  • GET /api/orders shows the orders of the logged-in user.

Design decisions before any code

Prices are integers in cents. The cart stores only a product id and a quantity. When the customer checks out, the server looks up each price in its own data and calculates the total. The browser has no say in the price. That one rule prevents the oldest trick in e-commerce, changing a price in the browser's developer tools.

The payment provider is passed into createApp as an object with a charge function, so the test can use a fake that approves or declines, and a real provider can replace it later without changes to the shop. That is the storage driver idea of lesson 22 applied to money.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express jsonwebtoken.
  3. Copy p-kit.js, p04-shop.js and p04.test.js into the folder. The shared p-kit.js is in Project 1.
  4. Install the test tools with npm install -D supertest, then run node --test p04.test.js.

The shop in one file. Read the checkout route slowly, because the order of its steps is the whole lesson.

// Project 4: e-commerce back end. Products, cart, orders, stock, and a payment provider behind an interface.
import express from 'express';
import { AppError, requireAuth, requireRole, errorHandler, notFoundHandler } from './p-kit.js';

export function createApp({ payments = { charge: async () => ({ ok: true, id: 'pay_demo' }) } } = {}) {
  const app = express();
  app.use(express.json());
  const auth = requireAuth();
  const products = new Map();
  const carts = new Map();     // userId -> Map(productId -> qty)
  const orders = [];

  app.get('/api/products', (req, res) => res.json([...products.values()].filter((p) => p.stock > 0)));

  app.post('/api/products', auth, requireRole('admin'), (req, res) => {
    const { name, priceCents, stock } = req.body ?? {};
    if (!name || !Number.isInteger(priceCents) || priceCents < 1 || !Number.isInteger(stock) || stock < 0) throw new AppError('name, priceCents (whole number) and stock are required', 422);
    const product = { id: products.size + 1, name, priceCents, stock };
    products.set(product.id, product);
    res.status(201).json(product);
  });

  const cartOf = (userId) => carts.get(userId) ?? carts.set(userId, new Map()).get(userId);

  app.put('/api/cart/:productId', auth, (req, res) => {
    const product = products.get(Number(req.params.productId));
    const qty = req.body?.qty;
    if (!product) throw new AppError('Product not found', 404);
    if (!Number.isInteger(qty) || qty < 0) throw new AppError('qty must be 0 or more', 422);
    if (qty > product.stock) throw new AppError(`Only ${product.stock} in stock`, 409);
    const cart = cartOf(req.user.id);
    if (qty === 0) cart.delete(product.id); else cart.set(product.id, qty);
    res.json({ items: [...cart].map(([id, q]) => ({ productId: id, qty: q })) });
  });

  // Checkout: price from OUR data, stock checked again, stock reduced only after payment works.
  app.post('/api/orders', auth, async (req, res) => {
    const cart = cartOf(req.user.id);
    if (!cart.size) throw new AppError('Your cart is empty', 409);
    let totalCents = 0;
    const lines = [];
    for (const [id, qty] of cart) {
      const product = products.get(id);
      if (qty > product.stock) throw new AppError(`Not enough stock for ${product.name}`, 409);
      totalCents += product.priceCents * qty;
      lines.push({ productId: id, name: product.name, qty, priceCents: product.priceCents });
    }
    const payment = await payments.charge({ userId: req.user.id, amountCents: totalCents });
    if (!payment.ok) throw new AppError('Payment failed', 402);
    for (const line of lines) products.get(line.productId).stock -= line.qty;
    cart.clear();
    const order = { id: orders.length + 1, userId: req.user.id, lines, totalCents, paymentId: payment.id, status: 'paid' };
    orders.push(order);
    res.status(201).json(order);
  });

  app.get('/api/orders', auth, (req, res) => res.json(orders.filter((o) => o.userId === req.user.id)));

  app.use(notFoundHandler, errorHandler);
  return app;
}

The test covers an admin adding products, a customer filling a cart, a successful checkout, a declined payment, and a customer who asks for more than is in stock.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './p04-shop.js';
import { signToken } from './p-kit.js';

const as = (id, role = 'user') => ({ Authorization: `Bearer ${signToken({ id, role, name: `u${id}` })}` });

test('project 4: cart, stock and checkout', async () => {
  const charges = [];
  let paymentOk = true;
  const app = createApp({ payments: { charge: async (c) => { charges.push(c); return { ok: paymentOk, id: 'pay_1' }; } } });
  const admin = as(1, 'admin');

  assert.equal((await request(app).post('/api/products').set(as(2)).send({ name: 'Pen', priceCents: 1500, stock: 5 })).status, 403);
  await request(app).post('/api/products').set(admin).send({ name: 'Pen', priceCents: 1500, stock: 5 });
  await request(app).post('/api/products').set(admin).send({ name: 'Book', priceCents: 49900, stock: 1 });
  assert.equal((await request(app).post('/api/products').set(admin).send({ name: 'Bad', priceCents: 9.99, stock: 1 })).status, 422);

  const buyer = as(2);
  assert.equal((await request(app).put('/api/cart/1').set(buyer).send({ qty: 9 })).status, 409);          // more than the stock
  await request(app).put('/api/cart/1').set(buyer).send({ qty: 3 });
  await request(app).put('/api/cart/2').set(buyer).send({ qty: 1 });

  paymentOk = false;
  assert.equal((await request(app).post('/api/orders').set(buyer)).status, 402);
  assert.equal((await request(app).get('/api/products')).body.find((p) => p.id === 1).stock, 5);          // no stock lost when payment failed

  paymentOk = true;
  const order = await request(app).post('/api/orders').set(buyer);
  assert.equal(order.status, 201);
  assert.equal(order.body.totalCents, 3 * 1500 + 49900);
  assert.equal(charges.at(-1).amountCents, 54400);

  const left = (await request(app).get('/api/products')).body;
  assert.deepEqual(left.map((p) => [p.name, p.stock]), [['Pen', 2]]);                                       // Book is sold out and hidden
  assert.equal((await request(app).post('/api/orders').set(buyer)).status, 409);                            // cart is now empty
  assert.equal((await request(app).get('/api/orders').set(buyer)).body.length, 1);
  assert.equal((await request(app).get('/api/orders').set(as(3))).body.length, 0);                         // others cannot see it
});

Rules worth understanding

Checkout order matters. The route checks that the cart is not empty, looks up every product, checks the stock again, adds up the total from the server's prices, charges the provider, and only if the payment works does it reduce stock and create the order. If the payment fails, nothing has changed and the reply is 402. If the steps were in a different order, a failed payment could still remove stock.

Stock races. In this in-memory version, JavaScript runs one request at a time between awaits, so the check and the update are safe. With a database, two requests can both see 1 item left. The fix is the conditional update of lesson 25: findOneAndUpdate({ _id, stock: { $gte: qty } }, { $inc: { stock: -qty } }), which checks and subtracts in one step, or a transaction when several documents are involved.

Own data only. The cart and the order list are found by req.user.id. A customer can never read another customer's orders by changing an id in the URL.

Hide products that are out of stock. The product list filters on stock > 0, so customers do not see items that they cannot buy.

Security and honesty notes

Only an admin can add products. The body of that route is checked: a name, an integer price of at least 1, and an integer stock of 0 or more. A price of -5 or 19.99 is refused.

In a real shop, the payment goes through a redirect or a hosted page and a webhook, as lesson 37 describes, and the order stays pending until the webhook arrives. This project charges directly through the fake provider to keep the stock logic easy to see.

Extend it

Your task

  1. Replace the direct charge with the pending order and webhook flow of lesson 37.
  2. Add product images with the upload code of lesson 22.
  3. Add a coupon code with a percentage discount that is calculated on the server.

How to check it worked

  • Changing a price in the request does nothing.
  • A declined payment leaves the stock unchanged.
  • A customer cannot see another customer's orders.

On your resume. "Built the back end of an online shop with server-side pricing in cents, per-user carts, stock control and a payment gateway behind an interface, tested with mock payments" is a clear, true summary. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.

Frequently asked questions

Why recheck stock at checkout?

Stock may have changed since the item was added to the cart. The check at the moment of purchase is the one that counts.

What is HTTP status 402?

Payment Required. It is rarely used but is a clear fit for a declined payment.

How do I stop two people buying the last item?

With a database, use a conditional atomic update or a transaction, so that checking and subtracting happen in one step.

Practise with interview questions