Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 40 ยท Projects

Project: A Checkout API

Build a small checkout API in Node: server-side cart totals, stock checks, an order state machine and an idempotent payment endpoint, all tested with fetch.

This project pulls the middle of the course into one running program: a small HTTP API that takes a visitor from an empty cart to a paid order. You will build the pieces that every shop needs and that are easy to get subtly wrong: totals computed on the server, stock checks at checkout, an order state machine, and a payment endpoint that is safe to retry. The server listens on loopback, and the program tests it by calling it with fetch, so you see real requests and real responses.

The ideas come from earlier lessons: integer money, cart design, reservations and overselling, the order lifecycle and idempotency. If you want the HTTP server basics first, read The http Module: Servers.

The payment gateway here is a stand-in object with a fake delay. It models the behaviour that matters (success, decline, a charge that must not happen twice), but it is not a real provider. Prices are integers in cents, and everything runs in one process with in-memory maps, so there is no database. In production, the stock check and the idempotency record would be one conditional UPDATE and one unique index.

The API we are building

Method and path Meaning Success
POST /carts Create an empty cart 201
PUT /carts/:id/items/:sku Set the quantity of a product (0 removes it) 200
POST /carts/:id/coupon Apply a coupon code 200
GET /carts/:id Read the cart with priced totals 200
POST /carts/:id/checkout Turn the cart into an order and hold the stock 201
POST /orders/:id/pay Charge the card (needs an Idempotency-Key header) 200
POST /orders/:id/cancel Cancel an unpaid order and release the stock 200
flowchart LR
  A["Cart<br/>(open)"] -->|checkout| B["Order<br/>pending_payment"]
  B -->|"pay (idempotent)"| C["Order<br/>paid"]
  B -->|cancel| D["Order<br/>cancelled"]
  C -->|later lessons| E["Order<br/>fulfilled"]

The cart converts to an order once; the order moves only along the arrows.

A few rules shape every handler:

  • The client sends intent, never money. A request says "two of TEE-M", never "two at 19.00". Prices, discounts, shipping and tax are all calculated by the server from its own catalog.
  • Errors use one envelope: { "error": "message" } with an honest status. 404 for unknown things, 409 for a conflict with the current state (out of stock, already paid), 422 for invalid input, 402 for a declined card.
  • Money is an integer number of cents from the first line to the last. The only rounding happens in two named places: the percent discount and the tax.

Stage 1: carts and totals

The first stage has no payments. It has a tiny router, a catalog, the pricing function and the checkout that turns a cart into an order.

The pricing function is the heart of the API, so keep it pure: it receives a cart and returns a plain object. Calling it twice gives the same answer, and you can test it without any HTTP. The order of operations is a business decision that you must write down once: subtotal, then discount, then shipping (free from $50.00 after the discount), then tax on the discounted goods. This stand-in does not tax shipping; real rules depend on the jurisdiction (see Sales Tax, VAT and GST).

Checkout does three things in a fixed order: it re-validates every line against current stock, it calculates the totals one last time, and only then does it change anything. Because the check and the decrement run with no await in between, no other request can slip between them inside one Node process. A real database needs the same guarantee from a conditional update such as UPDATE stock SET qty = qty - 2 WHERE sku = 'MUG' AND qty >= 2.

The order stores a snapshot of the lines and totals. If the catalog price changes tomorrow, yesterday's order must not change.

Node.js Stage 1: a cart, server-side totals and checkout

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output against the rules above. The subtotal is 2 x 1900 + 1200 = 5000. The 10% coupon removes 500, leaving 4500, which is under the free-shipping line, so shipping is 500. Tax is 8% of 4500, which is 360. The total is 4500 + 500 + 360 = 5360.

Stage 2: paying safely

Payment is where a bug costs real money, and two things go wrong in practice. A customer double-clicks the button, or the network drops after the charge succeeded and the browser retries. Without protection, both become two charges.

The fix is an idempotency key, described in Idempotency and Reliable Payments. The client generates a unique key for each intent to pay and sends it in a header. The server remembers the outcome per key:

  • First use of a key: do the work, store the response, return it.
  • Same key, same request: return the stored response without charging again. If the first request is still running, wait for it and share its result.
  • Same key, different request: refuse with 422. The client has a bug, because a key names exactly one request.

The essential trick is to store the promise of the work before awaiting it. Two concurrent requests with the same key then find the same entry and wait for the same result:

JavaScript
const seen = idem.get(key);
if (seen) {
  const result = await seen.promise;       // finished or still running
  return [result[0], result[1], { 'idempotent-replayed': 'true' }];
}
const promise = work();                    // starts the charge
idem.set(key, { fingerprint, promise });   // stored before any await

A fingerprint (here the order id plus the card token) detects a reused key with a changed body. Business errors such as a decline are stored too, so a retry gets the same 402. A customer who wants to try another card starts a new intent, so the client sends a new key.

Idempotency answers "did I already process this request?". It is not the same as the order state machine, which answers "is this order still allowed to be paid?". You need both. A different key for an order that is already paid must fail with 409, not charge again.

sequenceDiagram
  participant B as Browser
  participant S as Checkout API
  participant G as Gateway
  B->>S: POST /orders/o_2/pay (key k1)
  S->>G: charge 5360
  Note over B,S: network drops, no response
  B->>S: retry POST /orders/o_2/pay (key k1)
  S-->>B: stored result, no second charge
  G-->>S: charge ok (first request)

The retry reuses the key, so the gateway is charged exactly once.

Stage 3: the whole API with tests

The last example holds the complete API and a test suite that runs against it. Each test starts its own shop on a random port, so tests never share state. The helper createShop() is a factory that returns a server, the stand-in gateway and a way to stop it. The tests do not look inside the program; they talk to it only through HTTP, which is how a real client sees it.

Read the tests as a specification. Each one names a rule from the lessons: the client cannot choose the price, the last cap cannot be sold twice, concurrent duplicate payments charge once, and a paid order cannot be paid again.

Node.js Stage 3: the complete checkout API with eleven tests

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When a test passes you learn little; when you break the program on purpose, you learn a lot. Try these experiments in the editor and predict which test fails before you run it:

  1. In the /pay handler, remove the order.status !== 'pending_payment' check. Which test notices?
  2. In withIdempotency, move idem.set(...) to after await work(). Which test notices, and why does only the concurrent one catch it?
  3. Make priceCart read a price from the request body. Is there a test that fails, or did the suite miss a rule?

What a production version adds

The structure above carries over to real systems. These are the differences you would plan for:

  • A database for the same guarantees. The idempotency table gets a unique index on the key, the stock decrement becomes a conditional update, and order creation plus stock changes share one transaction. See Reservations and Overselling.
  • Expiring holds. Stage 1 holds stock forever for an order that is never paid. Real shops release the stock after a time limit, which the inventory service project builds.
  • Webhooks. A payment can finish after the browser has gone. The provider tells you with a signed event, which the webhook handler project handles.
  • Authentication and authorization. Anyone who knows an order id can pay or cancel it here. A real API checks who owns each cart and order (see Securing an Online Shop).
  • Key expiry and stored responses. Idempotency records are kept for a day or so, not forever, and a worker that crashed halfway needs a recovery path.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the client send only a SKU and a quantity instead of a price?

    Anything the browser sends can be edited. The server must derive prices, discounts, shipping and tax itself and treat the client's input as intent only.
  2. 2. Two requests with the same Idempotency-Key arrive at the same moment. What must the server do?

    If the key is recorded only after the work finishes, both requests pass the check and both charge. Recording the in-flight work first closes that gap.
  3. 3. A paid order receives another pay request with a brand-new idempotency key. What should happen?

    Idempotency protects a single request, not the order. The state machine decides what the order may still do, and paid orders cannot be paid again.
  4. 4. Why does checkout check every line first and change the stock only afterwards?

    Validating everything before mutating means an out-of-stock third line cannot leave the first two lines' stock already reduced.
  5. 5. Which statement about a declined card and the idempotency key is correct?

    A key names one intent. Replaying its outcome, including a decline, keeps retries predictable. A new attempt with different details is a new intent with a new key.

Summary

  • Build checkout around server-side truth: the client sends SKUs and quantities, and the server prices everything in integer cents with named rounding steps.
  • Validate all lines, then change stock, and make that step atomic (no await in one process, a conditional UPDATE in a database).
  • Store a snapshot of lines and totals on the order so later catalog changes do not rewrite history.
  • Make the pay endpoint idempotent: a required key, a fingerprint of the request, the stored result and the in-flight promise recorded before any await.
  • Use the order state machine to refuse impossible actions (paying twice, cancelling a paid order), whatever key the request carries.
  • Test through HTTP only, name each test after a business rule, and break the code on purpose to confirm a test can fail.

Next: Practice Exercises with Solutions