Building Software
Sections

Contents Section 6, Design

Frontend and Backend

Splitting responsibility between the user interface and the server: where state lives, where checks run, and how the two talk.

Section 6 of 9, subsection 6 of 6. Depth: explain. A 6-minute read.

Mistakes to catch in review

  1. Authorization, pricing or discount logic enforced only in the browser, where any user can change it.

  2. Clickable divs with no keyboard handler or label, so the interface cannot be used from a keyboard or a screen reader.

  3. A screen with no loading, empty or error state, which shows a blank page or an endless spinner when anything goes wrong.

  4. Client and server validation that disagree, so a form accepts input the server rejects or rejects input the server would accept.

The Browser Belongs to the User

An agent adds two features to your event-ticketing app. Organizers get a "Cancel event" button, and customers can buy up to four tickets per order. You log in as a customer and check: the cancel button is gone, and the quantity box stops at 4. Both features look finished.

Here is the part the agent wrote for the server:

TypeScript
app.post("/events/:id/cancel", requireLogin, async (req, res) => {
  await db.events.update(req.params.id, { status: "cancelled" });
  res.sendStatus(204);
});

app.post("/orders", requireLogin, async (req, res) => {
  const { eventId, quantity } = req.body;
  const order = await createOrder(req.user.id, eventId, quantity);
  res.status(201).json(order);
});

Any logged-in customer can cancel any event, and any customer can buy 400 tickets. Both rules exist only in the browser, and the server checks neither.

What the server can actually know

Start with what physically happens. The browser is a program running on the user's computer. It downloads your JavaScript, runs it, and eventually sends an HTTP request to your server. The server receives bytes: a method, a path, some headers, a body. It has no way to know which program produced those bytes or whether your JavaScript ran at all.

That means the user can skip your interface entirely. Every browser has developer tools that let you edit the page's code, change a hidden button back to visible, or copy a request and resend it with different values. Outside the browser it is one command:

Shell
curl -X POST https://tickets.example.com/events/42/cancel \
  -H "Cookie: session=<the customer's own session cookie>"

The customer's session is valid, so requireLogin passes. Nothing else is checked, so event 42 is cancelled. Hiding the button changed only what honest users see; the server allows exactly what it allowed before.

On the left, a box labelled user's computer holds three senders: your page, running your JavaScript; dev tools, an edited or resent request; and curl, one command. Arrows from all three converge on one box, a request: method, path, headers, body. An arrow runs from it into a box labelled your server, which holds a highlighted box, server checks, the code the user can't change. A note under the request reads can't tell who sent it; a note inside the server box reads only these can refuse.
Your page, an edited page in dev tools and a curl command all send a request the server cannot tell apart, so only the server's own checks can refuse.

So a check in the browser is a convenience. It gives fast feedback and saves a round trip for users who are trying to do the right thing. Every rule that protects money, data or permissions has to be enforced again on the server, because the server is the only code the user cannot change:

TypeScript
app.post("/events/:id/cancel", requireLogin, async (req, res) => {
  const event = await db.events.get(req.params.id);
  if (!event) return res.sendStatus(404);
  if (event.organizerId !== req.user.id) return res.sendStatus(403);
  await db.events.update(event.id, { status: "cancelled" });
  res.sendStatus(204);
});

The quantity limit gets the same treatment: the server rejects any quantity that isn't an integer from 1 to 4, whatever the form allowed.

When you review a feature, list every field in the request and every action the endpoint takes. For each one, ask what happens if the user sends a different value, or calls the endpoint when the interface would never have let them. Prices, totals, discounts, user IDs, roles and quantities are the usual places to look. If the server accepts a number it could have computed itself, such as a price or a total, it should compute it itself and ignore the one it was sent.

When the two sides disagree

Validation often lives in both places, which creates a quieter problem. Suppose the signup form checks passwords like this:

TypeScript
const passwordOk = (p: string) => p.length >= 8;

and the server, written separately, requires 12 characters. A user types a 10-character password. The form shows a green check, the server returns a 400, and the form, which never expected the server to reject a valid-looking password, shows "Something went wrong." The user has no idea what to fix.

The mismatch can run the other way. If the client checks emails with a pattern like /^[a-z0-9.]+@[a-z0-9.]+$/, it rejects maya+work@example.com, which the server would have accepted. That user simply can't sign up, and no error ever reaches your logs, because the request was never sent.

Both directions show up as soon as you run the same inputs through both sets of rules:

TypeScriptRuns in your browser
const client = {
  password: (p: string) => p.length >= 8,
  email: (e: string) => /^[a-z0-9.]+@[a-z0-9.]+$/.test(e),
};
const server = {
  password: (p: string) => p.length >= 12,
  email: (e: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e),
};

const inputs: [keyof typeof client, string][] = [
  ["password", "correct horse battery"],
  ["password", "tenletters"],
  ["email", "maya@example.com"],
  ["email", "maya+work@example.com"],
];
for (const [field, value] of inputs) {
  const c = client[field](value);
  const s = server[field](value);
  const verdict = c === s ? "agree" : c ? "form says ok, server returns 400" : "form blocks it, server would accept";
  console.log(`${field.padEnd(9)} ${JSON.stringify(value).padEnd(24)} ${verdict}`);
}
A highlighted box at the top, schema module, the rules defined once. Two boxes below it, the signup form in the browser and the signup endpoint on the server, each send an arrow up into it. A note at the bottom reads both import one schema.
The signup form and the signup endpoint import the same schema module, so the browser and the server check the same rules.

The fix is one definition of the rules. In a TypeScript codebase that can be a single schema module imported by both the form and the endpoint. Where that isn't possible, make the server the authority and have it return errors per field, such as {"field": "password", "message": "Use at least 12 characters"}, so the form can show the server's answer next to the right input. Client checks must not be stricter than the server's, and a client-only restriction that blocks input the server would accept, like the email pattern above, should be removed. To spot the problem in review, find the client's rules and the server's rules for the same form and compare them line by line.

Every screen has more than one state

Here is a list component an agent might write:

TypeScript (TSX)
function Orders() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/orders")
      .then((r) => r.json())
      .then((data) => {
        setOrders(data);
        setLoading(false);
      });
  }, []);

  if (loading) return <Spinner />;
  return <ul>{orders.map((o) => <li key={o.id}>{o.name}</li>)}</ul>;
}

Trace what the user sees in each situation. If the network drops, fetch rejects, nothing catches it, loading stays true, and the spinner turns forever. If the server returns a 500 with a JSON error body, fetch does not reject, because an HTTP error status is still a completed response, so data becomes the error object. fetch rejects on network failure, on cancellation and on invalid arguments, and a status like 500 is something you have to check yourself with r.ok. orders.map then throws, and in React an uncaught render error with no error boundary unmounts the whole app, leaving a blank page. If the user has no orders, they see an empty list with no text, which looks the same as broken.

A table of four rows, read left to right as server answer, what the code does, what the user sees. Has orders: setOrders runs, and the user sees the list, highlighted as the state it was written for. Network down: fetch rejects and nothing catches it, so the spinner turns forever because loading stays true. HTTP 500: fetch resolves and the error body becomes data, so orders.map throws and the page goes blank. No orders: an empty list with no text, which looks broken. A note reads every other state by accident.
Only the first row was designed. A dropped network leaves the spinner turning, a 500 makes orders.map throw into a blank page, and an empty list looks broken.

The component was written for one state, success with data, and every other state falls out by accident. A way to make the others visible is to list them explicitly as a type:

TypeScript (TSX)
type OrdersState =
  | { kind: "loading" }
  | { kind: "error"; message: string }
  | { kind: "ready"; orders: Order[] };

function Orders() {
  const [state, setState] = useState<OrdersState>({ kind: "loading" });

  useEffect(() => {
    fetch("/api/orders", { signal: AbortSignal.timeout(10_000) })
      .then(async (r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return (await r.json()) as Order[];
      })
      .then((orders) => setState({ kind: "ready", orders }))
      .catch(() =>
        setState({ kind: "error", message: "We couldn't load your orders." })
      );
  }, []);

  switch (state.kind) {
    case "loading":
      return <Spinner />;
    case "error":
      return <p role="alert">{state.message}</p>;
    case "ready":
      return state.orders.length === 0 ? (
        <p>You have no orders yet.</p>
      ) : (
        <ul>{state.orders.map((o) => <li key={o.id}>{o.name}</li>)}</ul>
      );
  }
}

Now each state has a screen. The timeout matters too. fetch has no timeout option of its own, so a request to a server that accepts the connection and never answers can leave the spinner running for a long time. AbortSignal.timeout turns that into an error after ten seconds.

You can run both versions' logic against the answers a server can give. The block below drops React and keeps only what decides the screen. Response is the same class fetch resolves with, so r.ok behaves as it does in the browser.

TypeScriptRuns in your browser
interface Order { id: number; name: string }
const json = (body: unknown, status = 200) =>
  new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });

const servers: Record<string, () => Promise<Response>> = {
  "has orders": async () => json([{ id: 1, name: "2 tickets, Oct 3" }]),
  "no orders": async () => json([]),
  "HTTP 500": async () => json({ error: "database unavailable" }, 500),
  "network down": async () => { throw new TypeError("network error"); },
};

const list = (orders: Order[]) => `<ul>${orders.map((o) => `<li>${o.name}</li>`).join("")}</ul>`;

async function agentScreen(get: () => Promise<Response>) {
  let orders: Order[] = [];
  let loading = true;
  await get()
    .then((r) => r.json())
    .then((data) => { orders = data; loading = false; })
    .catch(() => {}); // the agent's code has no catch; this one only keeps the playground running
  if (loading) return "spinner, forever";
  try { return list(orders); } catch (e) { return `blank page (render threw ${(e as Error).name})`; }
}

async function fixedScreen(get: () => Promise<Response>) {
  try {
    const r = await get();
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    const orders = (await r.json()) as Order[];
    return orders.length === 0 ? "You have no orders yet." : list(orders);
  } catch {
    return "We couldn't load your orders.";
  }
}

for (const [name, get] of Object.entries(servers)) {
  console.log(name.padEnd(13), "|", (await agentScreen(get)).padEnd(36), "|", await fixedScreen(get));
}

In the 500 row, the agent's version never saw an error: the request completed, the error body became orders, and the failure surfaced later, in rendering.

Real screens have more states than this. A list can be partly loaded, a form can be submitting, a save can have failed while the old data is still shown. When you review a screen, write the states down and say what the user sees in each. A state with no screen shows the user a blank page or an endless spinner when it occurs.

Buttons a keyboard can reach

The same agent will often write a clickable icon like this:

TypeScript (TSX)
<div className="icon-btn" onClick={removeItem}>
  <TrashIcon />
</div>

It works with a mouse. A div isn't in the keyboard's Tab order, though, so a keyboard user can never reach it, and pressing Enter or Space on it does nothing even if they could. A screen reader announces nothing useful, because the element has no role and the icon has no text. For someone who can't use a mouse, the item can never be removed.

A real button gets all of that from the browser:

TypeScript (TSX)
<button type="button" onClick={removeItem} aria-label="Remove item">
  <TrashIcon aria-hidden="true" />
</button>

It is focusable, it activates on Enter and Space, and a screen reader announces it as a button named "Remove item". The test takes a minute: put the mouse aside and use the page with Tab, Shift+Tab, Enter and Space. Anything you can't reach or operate is a bug. On a Mac, turning on VoiceOver with Command+F5 lets you hear what a screen reader user hears.

Where each piece of state belongs

Every value on a screen has one home that holds the true copy, and choosing the wrong home causes predictable bugs.

Kind of state Examples Home What breaks if it lives elsewhere
Server state Prices, permissions, order history Database, via the server Kept in the browser, the user can edit it
URL state Search terms, filters, page number, open tab The address bar Kept in memory, a reload or a shared link loses it
Client state An open menu, text typed but not saved Component memory Kept on the server, every keystroke needs a round trip
Cached state The order list fetched a minute ago A client cache Never refreshed, the user sees stale data after changing it

A cache is a copy of server state, so it needs a rule for when it is refreshed, such as after the user saves a change. A price kept in localStorage and posted back at checkout is server state living in the wrong place: the user can open developer tools and change it. When you review, pick a value, find every place it is stored, and ask which copy wins if they differ. If the answer is the browser's copy, and the value affects money or access, the design is wrong.

A rule that only the browser enforces is a suggestion to honest users. For every rule that protects money, data or permissions, find the line on the server that enforces it; if there is no such line, the rule is not enforced.

Check your understanding

7 questions on this lesson. Pick an answer to see whether it holds and why.

  1. 1An agent wrote this endpoint for the profile form. The form only ever sends the logged-in user's own ID. What should change?
    TypeScript
    app.post("/profile", requireLogin, async (req, res) => {
      const { userId, displayName, bio } = req.body;
      await db.users.update(userId, { displayName, bio });
      res.sendStatus(204);
    });
    Show the answer

    Answer C. Anyone logged in can send this request by hand with another user's ID, and requireLogin only proves they are someone. The server already knows who is asking, so it should use that and ignore the value it was sent. A hidden field is still part of a request the user controls, and a well-formed ID can still belong to someone else.

  2. 2The tickets endpoint returns HTTP 500 with the body {"error": "timeout"}. There is no error boundary. What does the user see?
    TypeScript (TSX)
    useEffect(() => {
      fetch("/api/tickets")
        .then((r) => r.json())
        .then(setTickets)
        .catch(() => setError(true));
    }, []);
    
    if (error) return <p role="alert">Couldn't load tickets.</p>;
    return <ul>{tickets.map((t) => <li key={t.id}>{t.title}</li>)}</ul>;
    Show the answer

    Answer B. A 500 is a completed response, so fetch resolves and .catch never runs. The error body goes to setTickets, and tickets.map throws during rendering, which happens outside the promise chain, so with no error boundary React unmounts the app. Checking r.ok and throwing inside the chain would send the 500 to the .catch.

  3. 3This custom checkbox works with a mouse. Which change makes it usable from a keyboard and a screen reader?
    TypeScript (TSX)
    <span className="check" onClick={() => setAgreed(!agreed)}>
      {agreed ? <CheckIcon /> : null} I agree to the terms
    </span>
    Show the answer

    Answer A. A native checkbox is focusable, toggles on Space, and is announced as a checkbox with its state and its label's text. tabIndex={0} only puts the span in the Tab order: Space still does nothing and a screen reader still hears no role or state. A role on its own announces a checkbox that the keyboard can neither reach nor toggle.

  4. 4A search page keeps its filters (city, dates, price cap) in component state. A user copies the address of the filtered results and sends it to a colleague. What does the colleague see?
    Show the answer

    Answer D. Component state lives in the sender's open tab and is not part of the address, so the link carries none of it and the page opens with its defaults. Filters, search terms and page numbers belong in the URL, where a reload, the back button and a shared link all keep them. Nothing errors, which is why this goes unnoticed until someone shares a link.

  5. 5The signup form uses clientOk and the API uses serverOk, written by different agents. Which username gets a green check in the form and then a 400 from the server?
    TypeScript
    const clientOk = (name: string) => /^[A-Za-z0-9_]{3,20}$/.test(name);
    const serverOk = (name: string) => /^[a-z0-9_]{3,15}$/.test(name);
    Show the answer

    Answer B. The client allows capitals and up to 20 characters, the server only lowercase and up to 15, so any name with a capital passes the form and fails the API. maya okafor is the tempting pick, but the space fails both patterns, so the form stops it before sending. One shared rule, or the server's per-field error shown next to the input, closes the gap.

  6. 6A user changes their display name on the settings page and saves. The save succeeds, but the header keeps showing the old name until they reload. Where is the bug?
    Show the answer

    Answer C. A reload shows the new name, so the server has it. The header shows a client-side copy of server state with no rule for refreshing it, and the save should update or invalidate that copy. The URL would not help: a display name is server state, and the URL is for things like filters and page numbers.

  7. 7A hotel booking form runs four checks in the browser. Which one can stay in the browser only, without letting a user break anything?
    Show the answer

    Answer A. The far-off date warning protects nothing: the server accepts the booking either way, so a user who skips it gains nothing. Capacity, availability and ownership each protect the hotel or another guest, and a request sent by hand skips every browser check, so each must be enforced again on the server.

You understand it when you can

Drill

An agent built a checkout page that computes the discounted price in the browser and posts the final amount to the server, and it hides the refund button from users who are not admins. Find how a user pays less than the listed price and how a non-admin issues a refund.

Topics

The Untrusted Client
Everything in a browser or app can be read and changed by its user, so every rule that matters is enforced on the server.
Where State Lives
Server state, client state, URL state and caches, with a single source of truth for each value.
Rendering Models
Server-rendered, client-rendered and hybrid pages, and what each costs in speed, search visibility and complexity.
UI States
Treating each screen as a state machine with loading, empty, error, partial and success states.
Accessibility
Semantic markup, keyboard navigation, contrast and screen-reader support, so the interface works for everyone.
APIs Shaped for Interfaces
Designing server responses around what screens need, avoiding both over-fetching and chatty clients.

Further reading

Start here

Short reads

Watch

Books

  • Web Application Security: Exploitation and Countermeasures for Modern Web Applications. Andrew Hoffman, 2024, 2nd edition.

    Walks through recon, attack and defense for modern web apps, including server-side rendering and GraphQL. It shows why browser-side authorization and embedded secrets are exposed to anyone with devtools.

  • Form Design Patterns. Adam Silver, 2018.

    Builds real forms (checkout, login, upload) accessibly, with detailed guidance on validation and error messages. This matters when client-side checks must match what the server will accept.

Primary sources