Lesson 5 of 18How software works
How the Web Works
Trace what happens from typing a URL to seeing a page, and name every piece along the way.
"What happens when you type a URL into your browser and press Enter?" is one of the most famous interview questions in software, because the answer touches almost everything: networking, servers, security, and how browsers draw pages. It is also the map for everything else you will build. Every frontend, backend and database you write later plugs into a spot on this map.
Clients and servers
The web is a conversation between two kinds of computer. A client asks for things: your browser, a phone app, or a script. A server is a computer (usually in a data centre) running a program that waits for requests and sends back answers. "Server" means both the machine and the program on it.
A web app usually splits into three parts:
- The frontend is everything that runs on the client: the HTML, CSS and JavaScript your browser downloads. It is what the user sees and clicks.
- The backend is code that runs on the server. It checks who you are, applies the rules ("you cannot withdraw more than you have"), and talks to the database.
- The database stores data permanently and lets the backend search it quickly: users, posts, orders.
Where does each job usually live?
Anatomy of a URL
A URL (uniform resource locator) is an address for one thing on the web. Each part has a job:
https://shop.example.com:443/products/shoes?size=42&color=red#reviews
└─┬─┘ └──────┬───────┘ └┬┘ └─────┬──────┘ └───────┬────────┘ └──┬──┘
scheme host port path query fragment- Scheme: which protocol to use.
httpsis the secure version ofhttp. - Host: which computer to talk to, written as a domain name.
- Port: which program on that computer. HTTPS uses 443 by default and HTTP uses 80, so you rarely see it typed.
- Path: which resource on the server, like a file path.
- Query: extra options as
key=valuepairs after a?, joined with&. - Fragment: a spot inside the page after
#. It never leaves your browser; the server does not see it.
JavaScript has a built-in URL class that splits a URL for you:
Press Run (⌘ Enter) to see what happens.Python's standard library does the same with urllib.parse:
Press Run (⌘ Enter) to see what happens.https://example.com/docs?lang=en#install. Which part does the server not receive?Find the host in a URL
Before your browser can do a DNS lookup, it has to pull the host out of the URL. Write a function that does that.
"https://www.example.com/blog?page=2" → "www.example.com"
"http://localhost:3000/api" → "localhost"
"https://Shop.Example.com#top" → "shop.example.com"Rules:
- Every input starts with a scheme followed by
://. - The host ends at the first
/,?or#, or at the end of the string. - Drop a port (
:3000) if there is one. - Host names are not case sensitive, so return it in lowercase.
DNS: names to numbers
Computers on the internet find each other by IP address (internet protocol address), not by name. An IPv4 address is four numbers from 0 to 255, like 93.184.215.14. There are only about 4.3 billion of those, so the newer IPv6 uses much longer addresses like 2606:2800:21f:cb07:6820:80da:af6b:8b2c. One special address, 127.0.0.1 (also called localhost), always means "this same computer". You will use it constantly when you run servers on your own machine.
Humans prefer names, so the internet has a phone book called DNS (domain name system). When you type shop.example.com, your browser needs its IP address first:
- It checks its own cache, then asks your operating system, which has a cache too.
- If nobody remembers, the question goes to a DNS resolver, usually run by your internet provider or a public service like
1.1.1.1or8.8.8.8. - The resolver asks a root server "who handles
.com?", then the.comservers "who handlesexample.com?", then that domain's own name server "what is the address ofshop.example.com?". - The answer comes back and is cached for a while (its TTL, time to live), so the next lookup is instant.
Your resolver has nothing cached. Put the DNS lookup in order.
- Tap the steps below in the right order.
Connecting: TCP and TLS
With an IP address in hand, the browser opens a connection. Data on the internet travels in small packets that can arrive out of order or get lost. TCP (transmission control protocol) fixes that: it numbers the packets, resends lost ones, and puts them back in order, so both sides see a clean stream of bytes. Setting up a TCP connection takes a quick three-message handshake.
Then comes TLS (transport layer security), the "S" in HTTPS. TLS does two things. It encrypts everything, so anyone in between (the café Wi-Fi, your internet provider) sees only noise. And it checks the server's certificate, a signed document proving the server really is shop.example.com and not an impostor. That is what the padlock in the address bar means.
Request, response, render
Over that secure connection the browser sends an HTTP request: a short text message saying "GET me /products/shoes". The server's program decides what to send, maybe asks the database, and replies with an HTTP response: a status code (200 means OK), some headers, and a body, usually HTML. HTTP and APIs, two lessons on, covers HTTP in detail.
Here is the whole journey:
You type shop.example.com/products/shoes and press Enter. The browser splits the URL into its parts.
The same story as a sequence diagram, which reads top to bottom in time. Each arrow is one message:
IP for shop.example.com?
What the browser does with HTML, CSS and JavaScript
The browser now has text. Turning it into a page takes a few steps:
- Parse HTML into the DOM (document object model): a tree of objects, one per element, that JavaScript can read and change.
- Parse CSS into style rules and work out which rules apply to which element.
- Layout: calculate where every box goes and how big it is.
- Paint: fill in the pixels.
- Run JavaScript, which can change the DOM. Any change triggers layout and paint again for the parts affected.
This small page becomes the tree below it:
<html>
<body>
<h1>Shoes</h1>
<ul>
<li>Runner</li>
<li>Hiker</li>
</ul>
<button>Add to cart</button>
</body>
</html>The browser reads the HTML from the top and builds a tree. html is the root. (It adds an empty head even if you leave it out.)
Watching a page load in DevTools
Everything above happens on every page load, and your browser will show it to you. The Network tab in DevTools is the tool you will open most often when something on a web page is broken or slow, so learn it now. Open DevTools with F12, or Cmd+Option+I on a Mac and Ctrl+Shift+I on Windows and Linux, then pick the Network tab and reload the page. The examples here use Chrome; Firefox and Safari have the same tab with slightly different labels.
Before you reload, tick two boxes at the top:
- Preserve log keeps the list when the page navigates or redirects. Without it, a login that redirects wipes the very request you wanted to see.
- Disable cache makes the browser fetch everything fresh while DevTools is open, so you see what a first-time visitor sees. Untick it when you want to check that caching works.
Each row is one request. The columns that matter:
| Column | What it tells you |
|---|---|
| Name | The file or endpoint. Hover for the full URL. |
| Status | The HTTP status code. Red rows are failures, including requests that never got a response at all. |
| Type | document, script, stylesheet, fetch, xhr, img, font. |
| Initiator | What caused this request: the HTML parser, a script (with the line number), or a redirect. |
| Size | Bytes transferred. (memory cache) or (disk cache) means it never touched the network. |
| Time | Total time from start to last byte. |
| Waterfall | A bar per request on a shared timeline, so you can see what waited for what. |
The type filter buttons along the top (All, Fetch/XHR, JS, CSS, Img and so on) are how you cut a page with 150 requests down to the 4 API calls you care about.
Click any row to open its details. Headers shows the request URL, method, status, and both sets of headers: this is where you check whether the Authorization header or the cookie was actually sent. Payload shows the query string and request body. Preview and Response show what came back, which is where the real error message often hides behind a generic "Something went wrong" in the UI. Timing breaks that one request into phases:
Time spent before anything goes on the wire. Long stalls on many requests usually mean too many requests competing for the same connections.
Three shapes in the waterfall are worth recognising:
- A staircase. Each request starts only when the one before it finishes. Often that is a script that fetches A, waits, then fetches B using a value from A. Sometimes the dependency is real; often the requests could run at the same time.
- One very long bar with everything else waiting. A blocking script or a slow API call that the page needs before it can show anything.
- A red row with
(failed)orCORS errorin the Status column. Your code never got a response: the browser blocked it (CORS, see below), the DNS lookup failed, or the server refused the connection. The Console tab usually has the matching error message.
Two more features you will use weekly. The throttling dropdown (it says "No throttling") slows the network down to a phone on a weak signal, which is how you find out your page is unusable on a train. And right-click any request and choose Copy as cURL to get a terminal command that repeats it exactly, headers and cookies included, so you can replay it, share it in a bug report, or check whether the problem is in the browser or the server. HTTP and APIs shows you how to read and write curl commands.
Match each thing you see in the Network tab to what it most likely means.
HTTP versions you will see
Add the Protocol column in the Network tab (right-click any column header and tick it) and you will see values like http/1.1, h2 and h3. Those are the three versions of HTTP in use today. Networking You Will Actually Debug compares them properly; for this lesson you only need the shape of it:
- HTTP/1.1 sends one request at a time on a connection, so browsers open several connections to the same host, about six, and requests queue behind each other. That is where long Stalled bars come from.
- HTTP/2 (
h2) sends many requests at once over one connection. Most sites and CDNs use it. - HTTP/3 (
h3) does the same over QUIC on UDP, and handles lost packets better on poor networks.
The practical point: the methods, headers, status codes and cookies are identical in all three, so your application code does not change. You will mostly meet the difference when reading performance advice. Old tricks for HTTP/1.1, like merging all images into one big "sprite" file to save requests, matter much less on HTTP/2 and HTTP/3. Also, your local dev server usually speaks plain http/1.1, so a page can behave a little differently on your laptop than in production behind a CDN.
Cookies and sessions: how a site remembers you
HTTP and APIs explains that HTTP has no memory and that cookies are one answer. Here is what actually happens, because login bugs are some of the most common tickets on any web team.
The password crosses the wire once, inside TLS.
The ID in the cookie is the key to the account, so a stolen session cookie is as good as a stolen password until it expires. That is why the attributes on Set-Cookie matter:
| Attribute | What it does |
|---|---|
HttpOnly | JavaScript on the page cannot read the cookie, so an injected script cannot steal it. |
Secure | Only sent over HTTPS, never plain HTTP. |
SameSite=Lax or Strict | Not sent on most requests started by other sites, which blocks a classic attack where another site makes your browser submit a form to yours. None means always send (requires Secure). |
Max-Age or Expires | When it dies. With neither, it is a session cookie that lasts until the browser decides the session is over. |
Domain and Path | Which hosts and paths receive it. Leave Domain out and only the exact host that set it gets it back. |
Chrome treats a cookie with no SameSite as Lax, but browsers have not always agreed on that default, so set it explicitly. To see a site's cookies, open the Application tab in Chrome (Storage in Firefox and Safari) and look under Cookies. You can read every attribute there, and delete a cookie to test what happens when a session is lost.
Logging out should delete the session on the server, not only the cookie in the browser. If the server just tells the browser to forget the cookie, anyone who copied it earlier can still use it. Some apps skip the session store and put signed data directly in the cookie or a token. That saves a lookup per request, but then the server cannot easily cancel one session early, which is the trade-off behind the cookie vs token debates you will hear. The Security Habits for Developers lesson and the framework tracks go further.
The same-origin policy
The browser runs code from thousands of sites, and you are logged in to some of them in other tabs. Without a rule, a page on evil.example could ask your bank's API for your balance, and your browser would kindly attach your bank cookie. The same-origin policy is that rule: a page's JavaScript can only read responses and pages from its own origin.
An origin is three things together: scheme, host and port. All three must match. A different subdomain is a different origin, http and https are different origins, and so are two ports on localhost. That last one is why your React app on localhost:3000 cannot read your API on localhost:8000 until the API allows it. JavaScript's URL class computes the origin for you:
Press Run (⌘ Enter) to see what happens.The last one is the same origin because 443 is already the default port for https, so writing it changes nothing.
What the policy blocks and allows surprises people:
- Blocked: JavaScript reading a response from another origin with
fetch, and reading the contents of another origin's page inside aniframe. - Allowed: showing images from other origins, loading their scripts and stylesheets, linking to them, and submitting forms to them. The web would not work otherwise.
- The subtle part: a cross-origin request is often still sent. The browser just refuses to hand the response to your code. So the policy protects reading, not doing. A request that changes something on the server can still arrive, which is exactly the gap that
SameSitecookies and CSRF tokens close.
Servers can relax the rule for chosen origins with CORS, which HTTP and APIs covers in one paragraph. Remember the split: the browser enforces the policy, but the fix for a CORS error lives on the server.
One more distinction seniors keep straight: origin vs site. A site is roughly the scheme plus the main domain, so shop.example.com and api.example.com are same-site but cross-origin. The same-origin policy uses origins. SameSite cookies, as the name says, use sites. That is why a cookie for example.com can be sent to your API on a subdomain even though the page's JavaScript still needs CORS to read the API's response.
What does this print?
console.log(new URL("http://example.com:80/a?b=1").origin)http://localhost:5173 and calls your API on http://localhost:8000. The Console shows a CORS error. What is going on?- client / server
- The client asks (a browser or app). The server waits for requests and answers them.
- URL
- An address with a scheme, host, optional port, path, query and fragment.
- DNS
- The internet's phone book. Turns a domain name into an IP address.
- IP address
- The number that identifies a computer on a network, like
93.184.215.14.127.0.0.1means this computer. - TLS
- Encryption plus identity checking via certificates. The S in HTTPS.
- DOM
- The tree of objects a browser builds from HTML. JavaScript changes the page by changing the DOM.
- Network tab
- The DevTools panel that lists every request a page makes, with status, size, timing and headers.
- session cookie
- A cookie holding a random ID that the server maps to a logged-in user. Protect it with HttpOnly, Secure and SameSite.
- origin
- Scheme, host and port together, like
https://shop.example.com. The same-origin policy compares origins. - same-origin policy
- The browser rule that a page's JavaScript can only read responses and pages from its own origin.