Skip to content

How a Web App Works

Summary

Follows a request from the browser to the server and back, covering routes, API endpoints, HTTP methods and status codes, JSON and webhooks, so the reader can picture every part their agent builds.

Concepts Covered

This chapter covers the following 15 concepts from the learning graph:

Concept Concept Impact Score
Terminal and Command Line 399
Reading Code 483
Codebase 473
Web Application 992
Client and Server 844
Browser Front End 24
Back-End Server 549
HTTP Request 270
HTTP Methods 3
HTTP Status Codes 13
URL and Route 225
API Endpoint 218
JSON 6
REST API 1
Webhook 13

Prerequisites

This chapter builds on concepts from:


A Ticket to the Kitchen

A family sits down at a diner on a Friday night. The father orders a cheeseburger, medium, no onions. The waiter doesn't walk into the kitchen and explain this to the cook. Instead she writes it on a ticket in a shorthand the kitchen knows, "CB MED NO ON," and clips the ticket to a rail above the grill. A few minutes later a plate comes up through the window with the ticket tucked under it, and she carries it to the table.

Sometimes the plate doesn't come. The kitchen is out of the fish, so the waiter comes back and says so. Sometimes the father has ordered something the diner has never served, and the waiter tells him that before the ticket ever reaches the rail. Either way, the family never sees the kitchen. They see the menu, the waiter and the food.

Later, the place gets busy and the family moves to the bar to wait for a bigger table. The host hands them a plastic buzzer. Nobody has to keep walking up to ask whether the table is ready. When it is, the buzzer goes off in the father's hand.

The Trip Behind the Button

Sawyer waving welcome By the end of this chapter you'll read a route handler without knowing JavaScript, and test a door into your app the way a stranger would. You'll also spot the endpoints that need a lock. For each part of the trip, ask: gate or wall?

Every web app works like this diner. There is a front room you see and a kitchen you don't. Tickets in a fixed format carry orders between them, a short answer says whether the order worked, and now and then a buzzer tells you something happened without your asking. Your AI agent built all of these parts for your app. This chapter names each one and follows a single order from the moment a member taps a button to the moment the answer comes back. Once you can picture that trip, you can ask your agent better questions about where something lives and what happens when it breaks.

The Front Room and the Kitchen

A web application is a program that people use through a web browser. Some of its code runs in the browser, and the rest runs on a computer somewhere else that the browser talks to over the internet. Gmail, an online bank and the dating-safety app are all web applications. A plain web page shows the same thing to everyone. A web application remembers who you are, takes what you type or upload, does work with it, and shows you something made for you.

This split between the two halves has a name. Client and server is the arrangement where one program, the client, asks for something and another program, the server, does the work and answers. In the diner, the waiter is the client and the kitchen is the server. A client starts every conversation, and one server can answer thousands of clients at once.

In a web application the client is the browser front end: the screens, buttons and forms that run inside the member's own web browser, on their own phone or laptop. When a member opens the dating-safety app, their browser downloads the front end's code and runs it. That code draws the upload form, the "Run checks" button and the results page. Chapter 3 covers the tools it's built with.

The server half is the back-end server: the code that runs on a computer the builder controls, receives requests from browsers, does the work, and sends back answers. In the dating-safety app the back end is an Express server, hosted on a service called Railway. That's where the eight checks run. The back end talks to the database, holds the keys for the paid outside services, and decides who may see what.

Here is where each part of the dating-safety app lives. Pay most attention to the last column.

Part of the app Where it runs Who controls that machine
Upload form, "Run checks" button, results page Browser front end The member
Deciding which member is signed in and what they may see Back-end server The builder
The eight checks and the trust score Back-end server The builder
Calls to AI models, image search, people search, SMS vendors Back-end server The builder
Database of members, scans and results Postgres, reached only by the back end The builder
Photos Private storage, reached through links the back end hands out The builder
Card payments Stripe's servers Stripe

Why the Split Matters

Everything in the browser front end runs on a machine the member controls. Anyone can open the browser's built-in developer tools, read the front end's code, change it, and send the server any request they like. Hiding a button on the screen doesn't stop anyone from sending the request the button would have sent.

So the back end has to treat every request as a stranger at the kitchen door. Hiding other members' scans on the results page protects nobody on its own. A scan stays private only when the server refuses to hand it to anyone but its owner.

Picture a Stranger Holding the Phone

Sawyer thinking it over Here's a test for any rule in your app. Imagine the member's phone in a stranger's hands, with the developer tools open. The rules that still hold are the ones the server enforces, and those are the only ones that count.

Here is a short worked example. Suppose the agent builds a "Delete account" button and shows it only to signed-in members. Consider two versions of the server code behind it.

  1. Version A deletes whichever account number arrives in the request. In normal use the button only ever sends the member's own number, so it works. Anyone who sends the request by hand with a different number deletes a stranger's account.
  2. Version B ignores any account number in the request and deletes the account of the member the server knows is signed in. A hand-made request can only delete the sender's own account.

Both versions look identical on screen, and both pass a quick click-through test. Only Version B is safe, and the difference lives entirely on the server. Chapter 7 covers server-side checks in depth.

Tell your agent

"Make a table of every screen in this app. For each screen, list the actions a member can take there, and for each action, name the server code that checks whether this member is allowed to do it. Mark any action where the only check happens in the browser."

One Order, Start to Finish

Now we can follow one order. A member, call her Dana, has uploaded three photos and a screenshot of a conversation with a match. She taps "Run checks." Here is what happens.

  1. Dana's browser front end writes a request and sends it over the internet to the back end.
  2. On the server, the back end reads the request, works out which code should handle it, and checks that Dana is signed in and owns this scan.
  3. The back end runs the eight checks in parallel, calling outside services.
  4. It adds up a trust score and writes the results to the database.
  5. It sends a response back to the browser: a short code that says how it went, plus the results.
  6. Back in Dana's browser, the front end reads the response and draws the results page.

To keep the trip simple, this chapter has the server wait for all eight checks before it answers. Chapter 3 shows why most apps answer at once and finish the checks in the background. The next few sections name each piece of the trip.

The Request

An HTTP request is a message a client sends to a server, in the format the web uses, asking the server to do one thing. HTTP (Hypertext Transfer Protocol) is the agreed set of rules browsers and servers use to talk to each other: the diner's ticket format. Every request has the same four parts, in the same order:

  • a method, which says what kind of thing the client wants done;
  • an address, which says what it wants it done to;
  • headers, short labeled notes such as which member is signed in and what format the body is in;
  • an optional body, which carries data such as form fields or uploaded files.

Here is roughly the request Dana's browser sends when she taps the button. You never type this; the browser writes it. Scan number 4821 is made up for the example, and the session value is shortened.

POST /api/scans/4821/run HTTP/1.1
Host: app.example.com
Cookie: session=7f3c9a...
Content-Type: application/json

{"source": "results-page"}

The first line holds the method (POST) and the address (/api/scans/4821/run). Next come three headers. Host names the website. Cookie carries a session value, a pass the server handed Dana's browser when she signed in, so the server can tell who is asking. Content-Type says the body is written in JSON, a format explained below. After a blank line comes the body.

When something goes wrong, reading the request is often the fastest way to see why. Every browser's developer tools have a Network tab that lists each request the page sends. Your agent can read the same information from the server's logs.

URLs and Routes

A URL (Uniform Resource Locator) is the full address of something on the web, such as https://app.example.com/api/scans/4821/run. It names the website (app.example.com) and then a path on that website (/api/scans/4821/run).

A route is a rule in the back-end code that matches a method and a pattern of paths to the piece of code that handles them. The dating-safety app's server has a route for POST /api/scans/:scanId/run. Its :scanId part is a blank to fill in. When Dana's request arrives, the server finds this route, fills in the blank with 4821, and runs the code attached to it. A request that matches no route gets turned away, like an order for a dish the diner doesn't serve.

Front ends have routes too. When Dana's address bar shows https://app.example.com/scans/4821, that's a front-end route: it decides which screen to draw. The paths that start with /api in this app are back-end routes: they decide which server code runs. When your agent says "route," it's worth asking which kind it means.

API Endpoints

An API endpoint is one route on a server that a program is meant to call, together with the rules for what it expects and what it returns. API stands for Application Programming Interface, a fixed way for one program to ask another for something. Dana's browser is a program, and POST /api/scans/4821/run is an endpoint it calls.

Each endpoint is a promise: send me this kind of request, and I'll send back this kind of answer. Here are some endpoints an app like this would have. This list is illustrative.

Endpoint What it does Who should be allowed
POST /api/scans Start a new scan Any signed-in member
POST /api/scans/:scanId/photos Upload a photo to a scan The member who owns the scan
POST /api/scans/:scanId/run Run the eight checks The member who owns the scan
GET /api/scans/:scanId Fetch a scan and its results The member who owns the scan
GET /api/scans List all of my scans Any signed-in member, seeing only their own
DELETE /api/scans/:scanId Delete a scan and its photos The member who owns the scan
POST /api/webhooks/stripe Hear from Stripe that a payment went through Stripe only

Most of the risk shows up in the right-hand column. Every endpoint is a door into the kitchen, and each door needs its own lock. A list of endpoints is a list of every way in, which makes it one of the most useful documents an app can have. Chapter 16 shows how an endpoint added for convenience can become a security problem.

HTTP Methods

HTTP methods are the small set of verbs a request can use to say what kind of action it wants. The address says what thing; the method says what to do to it. Five methods cover nearly everything.

Method Meaning Dating-safety example
GET Read something, change nothing Fetch the results of scan 4821
POST Create something or start an action Start a scan, run its checks
PUT Replace something whole Replace a member's saved settings
PATCH Change part of something Change only the member's display name
DELETE Remove something Delete scan 4821 and its photos

One path can mean different things with different methods: GET /api/scans/4821 reads a scan, and DELETE /api/scans/4821 destroys it. A route is matched on both, so a request with the right path and the wrong method doesn't reach the code you expect. The author once lost hours to exactly that, a story Chapter 12 tells.

A GET request should never change anything. Browsers, link previews in chat apps and search engines all send GET requests on their own, without anyone clicking. If a GET endpoint deletes or sends something, a link preview can trigger it.

A Link That Deletes

Sawyer raising a caution Agents sometimes build an "unsubscribe" or "delete" link as a plain GET, because a link is the easiest thing to put in an email. A chat app's preview can then fire it before anyone clicks. When your agent adds a link that changes data, ask it to make the link open a page with a button that sends a POST or DELETE.

REST APIs

A REST API is a set of endpoints organized around things, called resources, where the URL names the thing and the HTTP method names the action. The pattern comes from Roy Fielding's 2000 doctoral thesis. The endpoint table above mostly follows it: /api/scans/4821 is the thing, and GET or DELETE says what to do to it. A path like /api/deleteScan?id=4821 breaks the pattern by putting the action in the address. You don't need to enforce REST. Its value is that predictable endpoints make an odd one easier to spot.

Use the step-through below to follow Dana's request from tap to results page, and predict what happens at each stop.

Diagram: Follow One Request

Run the Follow One Request MicroSim Fullscreen

Follow One Request

Type: microsim sim-id: follow-one-request
Library: p5.js
Status: Specified
Bloom Level: Understand
Bloom Verb: explain
Learning Objective: The learner will explain what happens at each of seven stops as one "Run checks" request travels from the browser front end to the back-end server and back, by predicting the correct outcome at 6 of 7 stops.

Prerequisites: web application, client and server, browser front end, back-end server, HTTP request, HTTP method, URL, route, API endpoint, JSON, status code (all defined in the sections above and in "JSON: The Shape of the Answer" and "Status Codes: How Did It Go?" below).

Evidence of Mastery: At each of seven stops, before the request moves on, the learner picks one of three statements as what happens next. A pick is correct when it matches the correct statement in Content. Mastery is 6 of 7 correct on the first attempt. Clicking parts of the picture to read their labels is exploration, not evidence.

Misconceptions: (1) The front end runs the checks. (2) Hiding a button in the browser stops the request. (3) The server trusts the scan number the browser sends without checking who owns it. (4) A response with a page drawn on screen means the request worked.

Instructional Rationale: Understand-level explanation needs the learner to say what each part does in its own words. Predicting the next event at each stop, then seeing it, forces the learner to hold a model of the whole trip rather than memorize names.

Content:

The picture shows two zones, labeled "Dana's browser (the member controls this)" and "The back-end server (the builder controls this)," with the internet between them. Three boxes beside the server are labeled "Database," "Outside services (8 checks)" and "Private photo storage." A ticket labeled "Request" moves between the zones.

Stop Where What the learner sees Option A Option B Option C Correct Why (feedback)
1 Browser Dana taps "Run checks" The browser runs the eight checks itself The front end writes a POST request to /api/scans/4821/run and sends it The browser asks the database directly for results B The front end only asks. The work happens on the server.
2 Internet The request travels with a Cookie header The cookie tells the server which member is signed in The cookie holds Dana's password The cookie holds the scan results A The session cookie lets the server recognize Dana without her password.
3 Server The request arrives with path /api/scans/4821/run and method POST The server picks a route at random The server matches the path and method to the route POST /api/scans/:scanId/run and fills in 4821 The server runs every route it has B Routes match on both path and method.
4 Server The route's code starts It runs the checks on scan 4821 straight away It checks that Dana is signed in and that scan 4821 belongs to her It asks the browser whether Dana owns the scan B The server can't trust the browser, so it checks ownership itself.
5 Server and outside services The checks run The eight checks run one after another, and a slow vendor blocks the rest The eight checks run in parallel, and any check that fails to answer is marked "not checked" Any check that fails to answer is counted as passed B Parallel checks with a "not checked" result keep the score truthful.
6 Server The response is built The server sends status 200 and a JSON body with the score and eight results The server sends a finished web page as a picture The server sends nothing until Dana refreshes A The response is a status code plus data in JSON.
7 Browser The response arrives The front end draws the results page whatever the status code says The front end checks the status code first, then reads the JSON and draws the results The front end sends the results back to the server B A front end that skips the status code can show an error as if it were a result.

Clickable labels (exploration): clicking any zone or box shows its one-line definition from the chapter: browser front end, back-end server, database, outside services, private photo storage, route, endpoint.

Provenance: The request path, method, Cookie header and scan number 4821 are from the section "The Request" (the scan number is illustrative). The eight parallel checks and "not checked" result are from Chapter 1 and research/seed-notes.md. The status code and JSON body are from the sections "JSON: The Shape of the Answer" and "Status Codes: How Did It Go?"

Rules: Seven stops in fixed order 1 to 7. The request ticket moves to the next stop only after the learner picks an option and sees the feedback. A stop is correct when the first pick equals the Correct column.

Learner Activity:

  1. The learner sees stop 1 with three options and picks one.
  2. Feedback shows. The ticket animates to the next zone and the next stop appears.
  3. Steps 1 and 2 repeat through stop 7.
  4. A summary replays the whole trip in one pass, with each stop's correct statement shown as a caption.
  5. Free exploration unlocks: clicking any zone or box shows its definition.

Feedback: Seven stops, fixed order, one attempt each. Correct: "Right. " followed by the Why text. Incorrect: "Not quite. " followed by the correct statement and the Why text. The correct option is revealed after each pick. A running count "Stops correct: n of 7" is shown, with "Mastery reached" at 6 or more.

Starting State: Dana's browser shows a results page with a "Run checks" button and the request ticket blank. The prompt reads "Dana taps Run checks. What happens next?"

Chapter Anchors: The request is POST /api/scans/4821/run. The route is POST /api/scans/:scanId/run. Eight checks run in parallel. The response is status 200 with a JSON body. The chapter's trip has six steps in prose; the sim splits them into seven stops.

Tell your agent

"List every API endpoint this app's server has, with its method, its path, what it does and who is allowed to call it. Put the list in a file called docs/endpoints.md. Mark any endpoint that has no sign-in check, and any GET endpoint that changes data."

JSON: The Shape of the Answer

When the server sends an answer back, the answer has to be in a format the front end can read. Nearly every web app today uses the same one.

JSON (JavaScript Object Notation) is a plain-text format for structured data, made of named values in curly braces and lists in square brackets. A name goes in double quotes, followed by a colon and its value. A value can be text in quotes, a number, true or false, null for nothing, a list, or another group of named values.

Here is the body of the response the server sends back to Dana, trimmed to three of the eight checks. All numbers here are illustrative.

{
  "scanId": 4821,
  "score": 62,
  "checks": [
    {
      "name": "Photo search",
      "result": "fail",
      "detail": "The same photo appears on 3 other profiles under different names"
    },
    {
      "name": "Message patterns",
      "result": "pass",
      "detail": "No common scam phrases found"
    },
    {
      "name": "Phone lookup",
      "result": "not_checked",
      "detail": "The phone vendor did not answer within 10 seconds"
    }
  ]
}

Its outer braces hold three named values: scanId, score and checks. The value of checks is a list, and each item in it has a name, a result and a detail. Check three carries Chapter 1's "not checked" result, and the front end draws a gray label for it instead of a green or red one.

Think of the JSON as the app's answer, and the screen as only one way of showing it. Anything in the JSON reaches the member's browser, whether or not the results page shows it. Suppose a people-search vendor returns a home address, and the server copies the vendor's whole reply into the JSON. The page shows only "record matched," but the address has still reached the browser, where anyone can read it in the developer tools. The no-locate rule has to hold in the server's output, not in the page's layout. JSON that comes in from vendors needs checking too, which Chapter 9 covers.

Tell your agent

"Show me the exact JSON the server sends back for a finished scan, with every field. For each field, tell me whether the results page displays it. Flag any field that holds an address, workplace, location, phone number or anything the page doesn't need."

Status Codes: How Did It Go?

The waiter who comes back to say the kitchen is out of fish is giving a status report. HTTP status codes are the web's version: three-digit numbers at the start of every response that say whether the request worked and, if not, roughly why. The first digit tells you the family:

  • 2xx means it worked.
  • 3xx means the thing is somewhere else; go there instead.
  • 4xx means the client sent something wrong: a bad request, no sign-in, no permission, or a thing that doesn't exist.
  • 5xx means the server failed while trying.

Remember the 4xx and 5xx split above all. A 4xx says the problem is in the request, and a 5xx says it's in the kitchen. When a member reports "it didn't work," the code tells you which side to look at first. Here are the codes you'll meet most often.

Code Name Meaning in the dating-safety app
200 OK The checks ran and here are the results
201 Created A new scan was created
400 Bad Request The upload wasn't a photo, or a required field was missing
401 Unauthorized Nobody is signed in
403 Forbidden Someone is signed in but isn't allowed to do this
404 Not Found No such scan, or none this member may see
429 Too Many Requests The member hit the daily scan cap
500 Internal Server Error The server's own code crashed
502, 503, 504 Bad Gateway, Unavailable, Timeout The server is down, overloaded, or something in front of it gave up waiting

A Worked Case: 404 or 403?

Suppose Dana changes the number in a request from her own scan, 4821, to 4822, which belongs to another member. A 403 Forbidden would tell her the scan exists and she can't see it, and that is itself a leak: someone trying numbers one by one would learn which scans exist. A 404 Not Found gives away nothing. In the dating-safety app, the agent got this right. A member who asks for a scan that isn't theirs gets a 404, the same answer as for a scan that was never created. Chapter 7 returns to this rule.

Status codes also guard the no-false-all-clear rule from the front-end side. If the server crashes halfway through and sends a 500, a front end that ignores the code can draw an empty results page, and an empty page with no red flags reads as good news. The front end has to check the code first, and on anything other than a 2xx, say plainly that the checks didn't finish.

You can practice picking codes in the sim below.

Diagram: Status Code Picker

Run the Status Code Picker MicroSim Fullscreen

Status Code Picker

Type: microsim sim-id: status-code-picker
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: apply
Learning Objective: The learner will apply the meanings of nine HTTP status codes to choose the correct response for eight situations in the dating-safety app, with at least 7 of 8 correct.

Prerequisites: HTTP request, HTTP status codes, the 4xx and 5xx families, the 404-or-403 worked case, daily scan cap (all defined in the section "Status Codes: How Did It Go?" above).

Evidence of Mastery: For each of eight situation cards, the learner picks one status code from the nine on the code board. A pick is correct when it equals the Correct column in Content. Mastery is 7 of 8 correct on the first attempt. Reading the code board's definitions is exploration, not evidence.

Misconceptions: (1) Any error is a 500. (2) A member reaching another member's data should always get a 403. (3) A vendor failing means the server should send 200 with an empty result. (4) 401 and 403 mean the same thing.

Instructional Rationale: Apply-level use of a code system needs practice on situations the learner hasn't seen, with immediate feedback. Each card is written as something that happens to the app, not as a definition, so the learner has to map the event to the code.

Content:

Code board (always visible, each with its one-line meaning from the chapter's table): 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests, 500 Internal Server Error, 503 Service Unavailable.

Card Situation Correct Why (feedback)
1 Dana taps "Run checks" on her own scan and all eight checks finish 200 It worked, and the body holds the results.
2 Dana starts a new scan and the server creates it 201 A new thing was created.
3 Someone with no session cookie asks for scan 4821 401 Nobody is signed in.
4 Dana, signed in, asks for scan 4822, which belongs to another member 404 The app answers as if the scan doesn't exist, so it leaks nothing about other members' scans.
5 Dana, a viewer on a shared family account, tries to delete a scan; viewers may look but not delete 403 She is signed in and the scan is visible to her, but this action isn't allowed.
6 Dana uploads a spreadsheet where a photo should go 400 The request itself is wrong.
7 Dana starts her eleventh scan of the day and the daily cap is ten 429 She has hit a limit on how many requests she may make.
8 The server's own scoring code hits a bug and crashes before it can answer 500 The failure is in the server's code, not in the request.

Provenance: Card 4 and the 404 rule are from research/seed-notes.md ("a wrong ID returns 404, not 403") and the section "A Worked Case: 404 or 403?" The daily scan cap is from research/seed-notes.md; the number ten on card 7 is illustrative. Card 5's viewer role is from research/seed-notes.md (a viewer role exists); the shared family account is illustrative. Cards 1, 2, 3, 6 and 8 are illustrative. The sim must label illustrative cards "illustrative scenario."

Rules: Each card has exactly one correct code. 503 is on the board as a distractor and is correct for no card. A card is correct when the first pick equals the Correct column.

Learner Activity:

  1. The learner sees card 1 and the code board.
  2. The learner picks a code. Feedback shows, with the code's family (2xx, 4xx, 5xx) highlighted.
  3. Steps 1 and 2 repeat for cards 2 to 8.
  4. A summary shows all eight cards with the learner's pick and the correct code, grouped by family.

Feedback: Eight cards, fixed order 1 to 8, one attempt each. Correct: "Right. " followed by the Why text. Incorrect: "This one is [correct code] [name]. " followed by the Why text. If the learner picks 403 on card 4, add: "A 403 would tell Dana that scan 4822 exists." If the learner picks 200 on card 8, add: "Sending 200 for a crash can show an empty page that looks like good news." The score "n of 8 correct" is shown, with "Mastery reached" at 7 or more.

Starting State: Card 1 and the code board of nine codes. The prompt reads "What should the server send back?"

Chapter Anchors: Scan 4821 is Dana's and scan 4822 belongs to another member. The chapter's table lists 200, 201, 400, 401, 403, 404, 429, 500, and 502, 503, 504. A wrong scan ID returns 404, not 403.

Tell your agent

"Find every place in the front end that calls the server. For each one, tell me what the screen shows when the server answers with a 4xx or 5xx code. Flag any place where an error could show up as an empty list or a blank results page instead of an error message."

Webhooks: When the Server Gets a Call

So far every conversation has started in Dana's browser. Some news starts somewhere else. When Dana buys a pack of scans, the payment happens on Stripe's servers, and the app needs to hear about it so it can add the scans to her account. The app could ask Stripe every few seconds whether Dana has paid, like the family walking up to the host stand over and over. A better design is the buzzer.

A webhook is an HTTP request that an outside service sends to your server when something happens on its side, so your app hears about it without asking. You give the service the address of an endpoint on your server, and the service calls it each time an event happens. For this one conversation the roles flip: Stripe is the client, and your back end is the server.

Here is the order of events when Dana pays.

  1. Dana taps "Buy 5 scans." The front end asks the back end to start a payment, and the back end asks Stripe to open a checkout page.
  2. Dana types her card number on Stripe's page. The card number goes to Stripe and never touches the app's server.
  3. Stripe charges the card. When the charge succeeds, Stripe sends a POST request to the app's endpoint, /api/webhooks/stripe.
  4. The back end checks that the request came from Stripe, adds five scans to Dana's account, and answers with a 200.
  5. If Stripe doesn't get a 2xx answer, it tries again later, and keeps trying for up to three days.

Stripe's request looks like any other, with a JSON body describing the event. Here it is, heavily trimmed.

POST /api/webhooks/stripe HTTP/1.1
Host: app.example.com
Stripe-Signature: t=1762473600,v1=5257a8...
Content-Type: application/json

{
  "id": "evt_1Q8xYz...",
  "type": "checkout.session.completed",
  "data": { "object": { "amount_total": 1500, "currency": "usd" } }
}

Its type field names what happened. Amounts are in cents, so 1500 means fifteen dollars. The Stripe-Signature header is how the app knows the request came from Stripe and not from someone who found the address. Anyone on the internet can knock on this door, and checking the signature is the lock. Chapter 9 covers how that check works, and why the same event can arrive twice.

Webhooks are where money changes hands, so they are must-be-right parts. One that fails quietly means members pay and get nothing. One that trusts any caller means anyone can give themselves free scans. In the dating-safety app, the payment webhook had no automated test, a gap Chapter 10 picks up. Use the sim below to see what happens when parts of the webhook trip go wrong.

Diagram: Payment Webhook Trip

Run the Payment Webhook Trip MicroSim Fullscreen

Payment Webhook Trip

Type: microsim sim-id: payment-webhook-trip
Library: p5.js
Status: Specified
Bloom Level: Understand
Bloom Verb: infer
Learning Objective: The learner will infer the outcome for the member when one part of a Stripe payment webhook trip goes wrong, for five scenarios, with at least 4 of 5 correct.

Prerequisites: webhook, HTTP request, API endpoint, HTTP status codes, JSON, client and server (all defined in the sections above).

Evidence of Mastery: For each of five scenarios, the learner picks one of three outcomes before the trip plays. A pick is correct when it matches the Correct column in Content. Mastery is 4 of 5 correct on the first attempt. Playing the normal trip and clicking parts is exploration, not evidence.

Misconceptions: (1) The app asks Stripe whether the payment went through. (2) If the app is down when Stripe calls, the payment is lost forever. (3) Any request to the webhook address is from Stripe. (4) The app's server sees the card number.

Instructional Rationale: Understand-level inference asks the learner to reason from a model to a result they haven't been told. Changing one part of the trip at a time and predicting the result makes the learner use the direction of the call, the status code and the signature check, rather than recall a definition.

Content:

The picture shows three parties: "Dana's browser," "Stripe," and "The app's back-end server," with an arrow for each message. The normal trip has five steps, matching the numbered list in the chapter section "Webhooks: When the Server Gets a Call."

  1. Dana taps "Buy 5 scans," and the back end opens a Stripe checkout page.
  2. Dana enters her card on Stripe's page.
  3. Stripe charges the card and sends a POST to /api/webhooks/stripe.
  4. The back end checks the signature, adds 5 scans, and answers 200.
  5. If Stripe gets no 2xx answer, it retries later, for up to three days.
Scenario What changes Option A Option B Option C Correct Why (feedback)
1 Nothing changes Dana gets 5 scans after Stripe's webhook arrives Dana gets 5 scans when she refreshes the page, because the app asks Stripe Dana gets nothing until the builder adds the scans by hand A Stripe calls the app; the app doesn't have to ask.
2 The app's server is down for 20 minutes when Stripe sends the webhook The payment is lost and Dana never gets her scans Stripe gets no 2xx answer, retries later, and Dana gets her scans when the server is back Stripe refunds Dana automatically B Stripe retries until it gets a 2xx, for up to three days.
3 Someone who found the address sends a fake "checkout.session.completed" request with no valid signature, and the app checks signatures The app adds 5 scans to the sender's account The app rejects the request and adds nothing The app passes the request on to Stripe B The signature check is the lock on this door.
4 The same fake request arrives, and the app doesn't check signatures The app rejects the request The app adds 5 free scans to whatever account the fake request names Stripe blocks the fake request before it reaches the app B Without the check, anyone can knock and be let in.
5 The webhook code adds the scans, then crashes before answering, so Stripe gets a 500 Dana gets 5 scans once Dana gets 5 scans, and Stripe's retry may add 5 more unless the app remembers the event ID Dana gets no scans B Stripe retries on any non-2xx answer, so the same event can arrive twice. Chapter 9 covers how to handle that.

Clickable parts (exploration): clicking Dana's browser, Stripe, the back-end server, the webhook arrow or the 200 answer shows its one-line definition from the chapter.

Provenance: The trip, the endpoint /api/webhooks/stripe, the event type checkout.session.completed, the Stripe-Signature header and retries for up to three days are from the chapter section "Webhooks: When the Server Gets a Call," which follows Stripe's public webhook documentation. Scenario 2's 20 minutes is illustrative. Five scans per pack and fifteen dollars are illustrative. The sim must label scenarios 2 to 5 "illustrative scenario."

Rules: Five scenarios in fixed order 1 to 5. A scenario is correct when the first pick equals the Correct column. After each pick, the trip plays with the change applied, and the step where the trip differs from normal is highlighted.

Learner Activity:

  1. The learner presses Play and watches the normal five-step trip once.
  2. Scenario 1 appears with three options. The learner picks one.
  3. The trip plays with that scenario's change, and feedback shows.
  4. Steps 2 and 3 repeat for scenarios 2 to 5.
  5. A summary lists the five scenarios and which ones the learner got right.

Feedback: Five scenarios, fixed order, one attempt each. Correct: "Right. " followed by the Why text. Incorrect: "Not quite. " followed by the correct option and the Why text. The correct option is revealed after each pick. A running count "n of 5 correct" is shown, with "Mastery reached" at 4 or more.

Starting State: The three parties with no arrows drawn and a Play button. The prompt reads "Dana buys 5 scans. Who tells the app the payment went through?"

Chapter Anchors: The webhook endpoint is POST /api/webhooks/stripe. The event type is checkout.session.completed. The amount 1500 means fifteen dollars. Stripe retries for up to three days. The normal trip has five steps. Dana buys 5 scans.

Tell your agent

"Find every webhook endpoint in this app. For each one, tell me which service calls it and which events it handles. Tell me whether it checks that the request came from that service, and what status code it sends back when something goes wrong. Don't change anything yet."

Seeing It for Yourself Through Your Agent

You now have names for every part of the trip. To look at those parts in your own app, you don't need to write code. You need to know where the code lives, how to read a piece of it well enough to ask good questions, and what your agent is doing when it runs commands for you.

The Codebase

A codebase is the complete set of files that make up an app, kept together in one folder or a few. It holds the front-end code, the back-end code, the database setup, the settings, the tests and the notes. When your agent "makes a change," it is editing files in the codebase. When it commits, it is saving a snapshot of the codebase, which Chapter 5 covers.

Here is a typical layout for an app like the dating-safety app. It was written for this chapter, and your app's names will differ.

dating-safety-app/
├── client/                 the browser front end
│   └── src/
│       ├── pages/          one file per screen, such as the results page
│       └── api.js          the code that sends requests to the server
├── server/                 the back-end server
│   ├── index.js            starts the server and loads the routes
│   ├── routes/             one file per group of endpoints
│   │   ├── scans.js
│   │   └── webhooks.js
│   └── adapters/           one file per outside service
├── db/                     the database tables and the changes to them
├── tests/                  automated checks
├── package.json            the packages the app uses, and its commands
└── .env                    secret keys, kept out of git (Chapter 6)

The client folder is the front room and server is the kitchen. Inside server, routes is the kitchen's menu, one file per group of endpoints, and adapters holds the code that calls outside services.

Knowing the layout lets you ask better questions. Suppose a member writes in that the phone check always says "not checked." Asked "why is the phone check broken?", the agent may guess and change the first file that looks related. Instead, ask it to follow the trip one hop at a time. Start with the front-end code that draws the phone check's label. Then look at the endpoint that supplies the result, the route file that handles that endpoint, and the phone adapter it calls. Each hop is one file. Chapter 3 goes further and builds a map of your own app's parts.

Reading Code

Reading code is working out what a piece of source code takes in, what it does, what it gives back and what happens when something fails. You can do it without being able to write the code, the way you can follow a recipe and spot a missing step without being a chef. Four questions get you most of the way through any short piece of code.

  1. What comes in? The request, its path, its body, the signed-in member.
  2. What does it check? Sign-in, ownership, the shape of the input.
  3. What does it do? The main work, usually a few lines in the middle.
  4. What goes out, and what happens on failure? The status code and JSON it sends, on success and on each kind of failure.

Here is a route handler, the code attached to a route, for the endpoint Dana's browser called. It was written for this chapter in the style of the app.

router.post("/api/scans/:scanId/run", requireSignIn, async (req, res) => {
  const scan = await db.query.scans.findFirst({
    where: and(
      eq(scans.id, req.params.scanId),
      eq(scans.ownerId, req.user.id)
    ),
  });

  if (!scan) {
    return res.status(404).json({ error: "Scan not found" });
  }

  const results = await runAllChecks(scan);
  res.status(200).json({ scanId: scan.id, score: results.score, checks: results.checks });
});

Now apply the four questions.

Question Where in the code What it tells you
What comes in? router.post("/api/scans/:scanId/run", ...) and req.params.scanId, req.user.id A POST to this route, with the scan number from the path and the signed-in member from the session
What does it check? requireSignIn, and the two eq(...) lines Someone must be signed in, and the scan must have this ID and belong to this member
What does it do? runAllChecks(scan) Runs the checks; the detail lives in another function you can ask about
What goes out? res.status(404)... and res.status(200)... A 404 if the scan isn't this member's, otherwise a 200 with the score and checks in JSON

You didn't need to know JavaScript to fill in that table. The table also points at the next question: what happens inside runAllChecks when a vendor fails? That leads to the adapters and Chapter 9. If a route handler has no line that compares the record's owner to the signed-in member, take that to Chapter 7.

Count the Exits

Sawyer sharing a tip Want a fast start on any route handler? Find every line that sets a status code, such as res.status(404), because each one is a way out of the code. Ask your agent what leads to each exit, and whether any path ends with no answer at all.

The Terminal and the Command Line

Much of what your agent does happens in a terminal. A terminal is a window where you type text commands to the computer and read the text it prints back, instead of clicking icons. The command line is the line in that window where a command is typed, usually after a prompt such as $. You will see your agent run commands like these. Most are safe and routine.

Command What it does
ls Lists the files in the current folder
cat server/routes/scans.js Prints a file's contents
npm install Downloads the packages listed in package.json (Chapter 3)
npm run dev Starts the app on your own computer for testing
npm test Runs the automated tests (Chapter 10)
git status Shows which files have changed since the last save point (Chapter 5)
curl Sends an HTTP request from the terminal and prints the response

curl is worth knowing by name. It sends a request without a browser, so it skips the front end entirely, the same way an attacker would. Here, with the app running on the builder's own computer, the agent sends Dana's request with no session cookie. The -i option tells curl to print the status line and headers as well as the body.

$ curl -i -X POST http://localhost:3000/api/scans/4821/run
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8

{"error":"Sign in required"}

Line one is the command. localhost means "this computer," and 3000 is the port, the numbered door on this computer that the server listens at. The rest is the server's answer: a 401 status, a header saying the body is JSON, and a short JSON body. That one exchange proves the route refuses a request with no sign-in, checked on the server. If the answer had been a 200 with Dana's results, you would have found a must-be-right part with no lock on it, in ten seconds.

Some commands deserve a pause before you approve them, because they are one-way doors in Chapter 1's sense.

  • Anything with rm -rf, which deletes files and folders with no trash can.
  • Anything that changes or deletes database tables, such as DROP TABLE, or a database change script run against the live database (Chapter 11).
  • git push --force, which can overwrite saved work on GitHub (Chapter 5).
  • Anything that prints the contents of .env, the file of secret keys, which puts them in the agent's log and on your screen (Chapter 6).

Most agents ask before running commands, or can be set to. Chapter 4 covers how agents decide what to run.

Tell your agent

"Start the app on this computer. Before you send anything, show me which database and which outside-service keys it is using, and stop if any of them are the live ones. Then use curl to send a request to every endpoint in docs/endpoints.md with no sign-in at all, and show me each endpoint with the status code it returned. Put any endpoint that returns 200 without sign-in at the top of the list, other than public pages. Don't change any code."

Back to the Diner

That family at the diner never saw the kitchen, and they didn't need to. They trusted the waiter to carry the order in the right format and the kitchen to make only what was on the menu. They trusted the waiter to tell them when something was out, and the buzzer to go off when the table was ready.

A builder owns the kitchen, so they can't give their own app that much trust. When something goes wrong, ask your agent to follow the order one hop at a time, from the button to the route to the adapter, and show you where it broke. Chapter 3 names the tools your agent used to build each part.

Key Takeaways

  • Put every check that protects a member on the back-end server. The member can read and change anything in the browser front end, and can read every field of the JSON the server sends.
  • Keep a list of your API endpoints with who may call each one. Each is a way in and needs its own lock, and no GET request should change anything.
  • Read the status code first: a 4xx points at the request, a 5xx at the server. A front end that ignores it can show a failure as good news.
  • A webhook must prove it came from the service it claims to be from.
  • To find a problem, have the agent follow the request one file at a time, and use curl to test a route the way a stranger would.

You Can Follow the Order Now

Sawyer celebrating You can now trace one tap from the browser to a route, through the server and back as a status code and JSON. You can also read a route handler with four questions and test it with curl. Chapter 3 names the tools your agent used to build each of those parts.

See Annotated References