Skip to the workspace
Pebellslearn by building
Frontend Basics for Backend Developers  ›  Capstone Project

JavaScript — the Client You Don't Control

JavaScript 14 minBrowser JavaScript calls your API with fetch and JSON, but anyone can change it or bypass it, so the server must validate every request and compute anything that matters itself.

backend / JavaScript — the Client You Don't Control

Explore each scene at your own pace.

01 · The rule

The rule

JavaScript — the Client You Don't Control

Modern pages rarely reload to talk to the server. The bookshop's "Add to basket" button runs JavaScript that sends a small JSON request to your API and updates the page in place. That code runs on the shopper's machine, where the shopper can read it, change it or skip it entirely.

The rule

Every request is a suggestion; the server decides what is true.

The browser's fetch function sends HTTP requests from JavaScript:

const res = await fetch("/api/books?limit=5");
if (!res.ok) {
  throw new Error(`Request failed: ${res.status}`);
}
const books = await res.json();

Two details matter to a backend developer:

  • fetch does not reject on 4xx or 5xx. It only rejects when there is no response at all, such as a network failure. A 404 or 500 still resolves, with res.ok set to false. That is why your status codes must be honest: the client's error handling depends on them.
  • JSON bodies need a header. When sending JSON, the client should say so, and your server should read the body as JSON:
await fetch("/api/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ book_id: 42, quantity: 1 }),
});

Now the key point. Anyone can open the browser's developer tools and change this code, or skip the page and send the request with a tool such as curl:

curl -X POST https://bookshop.example/api/orders \
  -H "Content-Type: application/json" \
  -d '{"book_id": 42, "quantity": -5, "price": 1}'

The server cannot tell whether a request came from your page or from someone typing. So treat every field as untrusted input.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.