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:
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:
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.

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:
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:
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:
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}`);
}Output

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:
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.

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:
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.
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));
}Output
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:
<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:
<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.