FE·19
Frontend Networking
HTTP as the browser sees it: HTTP/1.1, HTTP/2, HTTP/3 and QUIC; caching and validators; cookies; the same-origin policy, CORS and preflights; credentials and compression; and the real-time options from polling to WebTransport.
Start here: how the frontend talks to servers
An HTTP exchange, up close
Everything a web page loads travels as HTTP: a request, then a response. With curl -v you can see both. Here a frontend asks an order API for order 42 (> lines are sent, < lines received):
> GET /api/orders/42 HTTP/1.1
> Host: localhost:8067
> User-Agent: curl/8.5.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Cache-Control: no-cache
< ETag: "v1"
< Date: Thu, 29 Oct 2026 08:27:24 GMT
<
{"id":42,"status":"cooking"}
A request is a method (what to do), a path (to what), headers (extra information as Name: value lines) and, for some methods, a body. A response is a status code, headers, and a body. That's the whole protocol; everything else in this chapter is about particular headers and how browsers use them.
Methods and status codes
| Method | Meaning | Body? | Safe to repeat? |
|---|---|---|---|
GET |
fetch something | no | yes |
POST |
create something / submit | yes | no (two POSTs may create two orders) |
PUT |
replace something at this URL | yes | yes (same result each time) |
PATCH |
change part of something | yes | depends |
DELETE |
remove something | usually no | yes |
Placing an order with POST:
$ curl -i -X POST http://localhost:8067/api/orders -H 'Content-Type: application/json' -d '{"dish":"Masala dosa","qty":2}'
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/orders/42
{"id":42,"dish":"Masala dosa","qty":2,"status":"placed"}
Status codes come in families: 2xx success (200 OK, 201 Created, 204 No Content), 3xx look elsewhere (301/308 moved, 304 not modified), 4xx the client's fault (400 bad request, 401 not logged in, 403 not allowed, 404 not found, 409 conflict, 422 invalid data, 429 too many requests), 5xx the server's fault (500 error, 502/503/504 a gateway or server unavailable). Your frontend code should handle each family differently: show the data, follow, tell the user what to fix, or retry later.
HTTP has no memory: cookies
HTTP is stateless: each request stands alone, and the server doesn't remember the previous one. So how does a site know you're logged in? With cookies. When you log in, the server's response includes a header like:
Set-Cookie: sid=abc123; Path=/; HttpOnly; Secure; SameSite=Lax
The browser stores it and automatically adds Cookie: sid=abc123 to every later request to that site. The server looks the session id up and knows who you are. The attributes after the value are security controls (HttpOnly: JavaScript can't read it; Secure: only sent over HTTPS; SameSite: limits sending it with requests started by other sites), and the lab shows each one at work.
Caching: not asking twice
Downloading the same file on every visit wastes time and data. Browsers keep a cache, and the server says, per response, how long a copy stays good, with the Cache-Control header. Think of a fridge with use-by dates:
Cache-Control |
Meaning | Typical use |
|---|---|---|
max-age=3600 |
use the stored copy for an hour without asking | images, fonts |
public, max-age=31536000, immutable |
keep for a year; it will never change | versioned files like app.3f9a1c.js |
no-cache |
you may store it, but ask the server before each use | HTML pages, API data |
no-store |
don't store it at all | private, sensitive data |
"Asking the server" is cheap when the response carries an ETag (a version label). The browser sends it back as If-None-Match: "v1", and if nothing changed, the server replies 304 Not Modified with no body. The lab watches all four policies on a real second visit: two files weren't requested at all, one cost a 304 of about 300 bytes, and only the no-store file was downloaded again.
The standard pattern that follows: put a content hash in every static file's name (app.3f9a1c.js; build tools do this, chapter 30), cache those for a year, and serve the HTML that references them with no-cache, so a new deploy is picked up on the next visit.
Smaller and fewer: compression and connections
Text compresses well. The browser advertises what it can decode (Chromium sends Accept-Encoding: gzip, deflate, br, zstd) and the server picks one, labelling it Content-Encoding: br. React's 625 KB DOM library shrinks to 14–18% of its size (lab). Connections matter too: HTTP/1.1 sends one request at a time per connection and browsers open at most six connections per host, while HTTP/2 and HTTP/3 send many requests at once over one connection. In the lab, 24 slow requests took 2 seconds over HTTP/1.1 and 0.56 seconds over HTTP/2.
Cross-origin requests and CORS
Chapter 12's same-origin policy lets a page send requests anywhere but read responses only from its own origin. Modern apps often call APIs on a different origin (app.example.com calling api.example.com), so the API must opt in with CORS (Cross-Origin Resource Sharing) headers:
Access-Control-Allow-Origin: https://app.example.com
For requests that a plain HTML form couldn't already send (a JSON body, a DELETE, a custom header), the browser first asks permission with a preflight: an OPTIONS request describing the real one. Only if the server's answer allows it does the real request go out. Two facts beginners trip over: CORS errors appear in the browser console but are fixed on the server; and CORS protects the user's data in other sites, not your server (anyone can call your API with curl).
Getting updates without asking: real-time options
Sometimes the server has news (an order is ready, a chat message arrived). Options, from simplest to most capable:
| Technique | How it works | Analogy |
|---|---|---|
| Polling | ask every few seconds: "anything new?" | phoning the restaurant every five minutes |
| Long polling | ask, and the server holds the reply until there is news | staying on the line until they have news |
| Server-Sent Events (SSE) | one long-lived response the server keeps writing events into | a radio station you tune into |
| WebSocket | a two-way channel; both sides send messages at any time | a phone call |
| WebTransport | multiple streams and datagrams over HTTP/3 | several phone lines at once |
Choose the simplest that works: most "live updates" are server-to-client and fit SSE, which reconnects automatically and resumes from the last event (lab); chat, collaborative editing and games need WebSocket.
How deep to go in frontend networking
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name methods, status families, headers, cookies, caching and CORS |
| L2 | Call APIs correctly: handle statuses, set credentials, choose cache headers, use SSE or WebSocket |
| L3 | Explain HTTP/1.1 vs 2 vs 3, the cache's freshness and validation model, cookie attributes and SameSite, CORS preflight and credentials |
| L4 | Diagnose CORS failures, stale caches, missing cookies, head-of-line blocking and dropped real-time connections from the Network panel and server logs |
| L5 | Design an app's caching, auth-cookie, API-origin and real-time strategy |
| L6 | Operate it at scale: CDN caching rules, protocol rollout, connection limits, real-time fan-out |
HTTP versions
HTTP semantics in one page
All HTTP versions share the same semantics (RFC 9110): a request with a method, a target, headers and an optional body, and a response with a status code, headers and a body. The versions differ only in how those messages travel over the wire.
GET /api/orders?page=2 HTTP/1.1
Host: shop.example.com
Accept: application/json
Accept-Encoding: gzip, br, zstd
Cookie: session=abc123
If-None-Match: "v42"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Encoding: br
Cache-Control: private, max-age=60
ETag: "v43"
Vary: Accept-Encoding
{"items":[…]}
| Method | Safe (no side effects) | Idempotent | Typical use |
|---|---|---|---|
| GET | ✓ | ✓ | Read |
| HEAD | ✓ | ✓ | Headers only |
| OPTIONS | ✓ | ✓ | CORS preflight, capabilities |
| PUT | ✓ | Replace a resource | |
| DELETE | ✓ | Remove | |
| POST | ✗ | Create, or any action | |
| PATCH | ✗ (unless designed to be) | Partial update |
Status families: 1xx informational (103 Early Hints lets the server send Link: preload headers before the real response is ready), 2xx success, 3xx redirection (301/308 permanent, 302/303/307 temporary, 304 Not Modified), 4xx client errors (400, 401 unauthenticated, 403 forbidden, 404, 409 conflict, 422 validation, 429 rate-limited), and 5xx server errors (500, 502 bad gateway, 503 unavailable, 504 gateway timeout). Vol. 3's HTTP API chapter goes deeper into designing APIs with these.
HTTP/1.1
HTTP/1.1 (1997, now RFC 9112) is a text protocol over TCP: request line, headers, blank line, body. It introduced persistent connections (keep-alive, Vol. 1 ch. 9), the mandatory Host header (so many sites can share one IP), chunked transfer encoding, and caching validators.
Its central limitation is head-of-line blocking at the application layer: one connection carries one request at a time. (Pipelining existed in theory but was broken in practice and never enabled.) Browsers work around it by opening up to 6 connections per host, each paying its own TCP and TLS handshakes and slow start. Old performance "best practices" were workarounds for exactly this limit: domain sharding (assets on static1., static2. to get more connections), concatenating all JS and CSS into single files, and image sprites. With HTTP/2, these are counterproductive.
HTTP/2
HTTP/2 (2015, RFC 9113) keeps the semantics but changes the transport:
- Binary framing: messages are split into frames (HEADERS, DATA, SETTINGS, WINDOW_UPDATE, RST_STREAM…).
- Multiplexing: many concurrent streams share one TCP connection, with frames interleaved. There's no more one-request-at-a-time limit, so one connection per origin is enough.
- Header compression (HPACK): headers repeat heavily between requests (cookies, user agent). HPACK uses static and dynamic tables plus Huffman coding (Vol. 1 ch. 4) to shrink them dramatically.
- Stream prioritisation: the original dependency-tree scheme was complex and widely ignored. It was replaced by the simpler Extensible Priorities (
priorityheader, RFC 9218), which browsers set from resource type andfetchpriority. - Flow control per stream and per connection (Vol. 1 ch. 9's ideas, at the application layer).
- Server push was removed by browsers (Chrome disabled it in 2022) because it rarely helped.
103 Early Hintspluspreloadreplaced it.
Browsers support HTTP/2 only over TLS, negotiated during the TLS handshake through ALPN (h2).
The remaining problem is TCP head-of-line blocking. All streams share one TCP byte stream, so a single lost packet stalls every stream until it's retransmitted, even streams whose data arrived fine. TCP must deliver bytes in order (Vol. 1 ch. 9). On lossy mobile networks, HTTP/2 can perform worse than six HTTP/1.1 connections.
HTTP/3 and QUIC
HTTP/3 (RFC 9114, 2022) runs over QUIC (RFC 9000), a new transport built on UDP that implements in user space what TCP does in the kernel, and more:
- Independent streams: loss on one stream doesn't block the others, which removes TCP's head-of-line blocking.
- Faster handshakes: transport and TLS 1.3 setup are combined into 1 RTT, and 0-RTT on resumption (with the replay caveats from Vol. 1 ch. 9).
- Connection migration: connections are identified by a connection ID, not the 4-tuple, so a phone switching from Wi-Fi to cellular keeps its connection.
- Encrypted by default, including most transport headers, so middleboxes can't ossify the protocol.
- QPACK header compression, designed to tolerate out-of-order delivery.
- Congestion control runs in user space (Cubic or BBR, Vol. 1 ch. 9), so it can evolve with app releases instead of OS kernels.
Discovery: a browser first connects over TCP (HTTP/1.1 or HTTP/2), and the server advertises HTTP/3 with an Alt-Svc: h3=":443" header, or through a DNS HTTPS record (Vol. 1 ch. 9). The next requests race QUIC against TCP. About a third of web traffic now uses HTTP/3, especially through big CDNs (Cloudflare, Google, Akamai, Fastly). Some corporate networks block UDP 443, and browsers fall back to TCP.
| HTTP/1.1 | HTTP/2 | HTTP/3 | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC (UDP) |
| Concurrency | 1 request/conn (~6 conns/host) | Multiplexed streams, 1 conn | Multiplexed streams, 1 conn |
| HOL blocking | Application + TCP | TCP | None at transport |
| Handshake (new) | TCP 1 RTT + TLS 1–2 RTT | Same | 1 RTT combined (0-RTT resumed) |
| Header compression | None | HPACK | QPACK |
| Encryption | Optional | Required by browsers | Always |
On the server side, you rarely implement these yourself. A reverse proxy or CDN (Nginx, Envoy, Caddy, Cloudflare) terminates HTTP/2 and HTTP/3 and speaks HTTP/1.1 or HTTP/2 to your Spring, Go or Rust services.
Caching
The HTTP cache
The browser's HTTP cache (and every shared cache in between: CDNs, proxies) stores responses so later requests can skip the network entirely or revalidate cheaply. The rules come from response headers (RFC 9111):
Cache-Control directive |
Meaning |
|---|---|
max-age=N |
Fresh for N seconds: serve from the cache without asking the server |
s-maxage=N |
Freshness for shared caches (CDNs) only, overriding max-age there |
no-cache |
May be stored, but must revalidate every time before use (not "don't cache") |
no-store |
Don't store at all (sensitive data) |
private |
Only the browser may cache it, not CDNs (personalised responses) |
public |
Shared caches may store it, even for authenticated requests |
immutable |
Never revalidate while fresh, even on reload |
must-revalidate |
Once stale, must revalidate. Don't serve stale data on error |
stale-while-revalidate=N |
Serve stale content for up to N s while refreshing in the background |
stale-if-error=N |
Serve stale content if the origin errors |
Freshness: a response is fresh while its age is below max-age, and fresh responses are used with no request at all. Once stale, the cache must revalidate with a conditional request (below). Without explicit headers, browsers apply heuristic freshness, often 10% of the time since Last-Modified, which surprises people. Always set Cache-Control explicitly.
Vary lists request headers that change the response (Vary: Accept-Encoding, Vary: Accept-Language). The cache keys entries on them. Vary: Cookie or Vary: * effectively disables shared caching.
The standard strategy for web apps:
# HTML: always get the latest (it references versioned assets)
Cache-Control: no-cache (+ ETag for cheap 304s)
# Fingerprinted static assets: app.3f9a1c.js, logo.8b2e.svg — content-hashed file names
Cache-Control: public, max-age=31536000, immutable (cache for a year; a new build = a new name)
# API responses: per-endpoint decision
Cache-Control: private, max-age=0, must-revalidate (personal data)
Cache-Control: public, s-maxage=60, stale-while-revalidate=300 (public catalogue via CDN)
# Secrets: account pages, tokens
Cache-Control: no-store
The cache-busting principle: never change a file at a URL that's cached for a long time. Change the URL instead. Bundlers put content hashes into file names (chapter 30) so this happens automatically.
ETags and conditional requests
When a cached response is stale, the browser revalidates it instead of downloading it again:
- The server sent a validator with the original response:
ETag: "v43"(an opaque version identifier, often a content hash) and/orLast-Modified: <date>. - The browser asks:
If-None-Match: "v43"(orIf-Modified-Since: <date>). - If nothing changed, the server replies
304 Not Modifiedwith no body. The browser reuses its copy and updates its freshness. If it did change, the server sends200with the new body and a new ETag.
GET /api/catalog → 200, ETag: "a1b2", body 180 KB
… later, stale …
GET /api/catalog
If-None-Match: "a1b2" → 304 Not Modified, no body (a few hundred bytes)
ETags have weak (W/"a1b2", semantically equivalent) and strong forms. Conditional requests also prevent lost updates for writes: PUT /doc/7 with If-Match: "v5" fails with 412 Precondition Failed if someone else changed the document first. That's optimistic concurrency control, the HTTP equivalent of a version column (Vol. 4) and of CAS (Vol. 1 ch. 8). On the backend: Spring's ShallowEtagHeaderFilter or explicit ResponseEntity.eTag(), Go's http.ServeContent, which handles conditional requests for you.
Compression
Text responses (HTML, CSS, JS, JSON, SVG) compress very well, often by 70–90%:
| Encoding | Notes |
|---|---|
gzip |
Universal; DEFLATE = LZ77 + Huffman (Vol. 1 ch. 4) |
br (Brotli) |
15–25% smaller than gzip for web content; a built-in dictionary of common web strings. Precompress static assets at the maximum level (11) |
zstd (Zstandard) |
Very fast at good ratios; supported in Chromium and Firefox, good for dynamic responses |
| Compression dictionaries | Use-As-Dictionary / Available-Dictionary: use the previous version of a file as a dictionary for the next, so updates ship as tiny diffs (newer, Chromium) |
Negotiation: the browser sends Accept-Encoding: gzip, deflate, br, zstd, and the server picks one and replies with Content-Encoding, plus Vary: Accept-Encoding. Don't compress already-compressed formats (JPEG, PNG, WebP, AVIF, woff2, zip). Precompress static assets at build time and compress dynamic responses at the proxy or CDN. Security note: compressing responses that mix secrets with attacker-controlled input enabled the BREACH attack. CSRF tokens should be masked per response.
Cookies
How cookies work
A cookie is a small name–value pair the server asks the browser to store and send back automatically on later requests to matching URLs:
HTTP/1.1 200 OK
Set-Cookie: session=7f3a…; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400
Set-Cookie: theme=dark; Path=/; Max-Age=31536000; SameSite=Lax
GET /account HTTP/1.1
Cookie: session=7f3a…; theme=dark
| Attribute | Effect |
|---|---|
Domain=example.com |
Also sent to subdomains. Omit it to restrict the cookie to the exact host (safer) |
Path=/admin |
Only for URLs under that path (not a security boundary) |
Expires / Max-Age |
Persistent cookie. Without them it's a session cookie, cleared when the browser session ends (though "restore tabs" often keeps them) |
Secure |
Only sent over HTTPS |
HttpOnly |
Not readable from JavaScript (document.cookie). An XSS attack can't steal it, though it can still use it by making requests |
SameSite |
Whether it's sent on cross-site requests (next section) |
Partitioned (CHIPS) |
Third-party cookie stored separately per top-level site |
Prefixes __Host- / __Secure- |
__Host- requires Secure, Path=/ and no Domain, which locks the cookie to its host and stops subdomains from overwriting it |
For session cookies, use: __Host-session=…; Path=/; Secure; HttpOnly; SameSite=Lax.
Cookies are sent on every matching request, including images and static assets, so keep them small. Serve static assets from a cookieless domain, or more simply a CDN. The browser limits are about 4 KB per cookie and around 50+ cookies per domain.
SameSite and third-party cookies
Same-site means the same scheme plus registrable domain (chapter 12). The SameSite attribute controls whether a cookie goes with requests initiated from other sites:
| Value | Sent on cross-site requests? | Effect |
|---|---|---|
Strict |
Never (not even when following a link to your site from elsewhere) | Strongest CSRF protection; the user arrives logged out from external links |
Lax (the browser default when unset) |
Only on top-level GET navigations (clicking a link) | Blocks cross-site POSTs, iframes and fetches: a good default |
None (requires Secure) |
Always | Needed for genuine cross-site use: embedded widgets, SSO flows, third-party APIs |
Third-party cookies (cookies of a site embedded in a different top-level site) enabled cross-site tracking. Safari and Firefox block them by default. Chrome changed course in 2024–2025 and abandoned its plan to phase them out, so they still work there by default. Design as if they're unavailable: use first-party cookies, use Partitioned (CHIPS) for legitimate embedded state, use the Storage Access API for embedded content the user interacts with, and use FedCM for federated login.
Cross-origin access
The same-origin policy for reads
Chapter 12 introduced the same-origin policy. Precisely, for network responses: a script from origin A can send a request to origin B (through fetch, a form or an image), but it can't read B's response unless B allows it through CORS. Embedding is allowed (<img>, <script>, <link rel=stylesheet>, <video>, <iframe>), but the page can't inspect the embedded content: it can't read pixels from a cross-origin image drawn to a canvas ("tainted canvas"), or a cross-origin iframe's DOM.
The SOP protects ambient authority. The user's cookies for bank.example are attached to requests made by any site. If an evil page could read those responses, it could read your bank balance. Note that the SOP stops reading, not sending. CSRF (chapter 28) exploits the sending side.
CORS
Cross-Origin Resource Sharing lets a server opt in to letting specific other origins read its responses. The browser enforces it. The server only declares the policy.
# Request from https://app.example.com to https://api.example.com
GET /orders HTTP/1.1
Origin: https://app.example.com
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com # exactly this origin may read (or * for public data)
Access-Control-Allow-Credentials: true # needed if the request includes cookies
Access-Control-Expose-Headers: X-Total-Count, ETag # response headers JS may read beyond the safelist
Vary: Origin # important when the value depends on the request
Rules that trip people up:
- CORS is enforced by browsers only.
curl, Postman, mobile apps and other servers ignore it. CORS isn't authentication or an API firewall. It's a browser-side protection for users. - With credentials (cookies or HTTP auth:
fetch(..., { credentials: "include" })), the server must not use*. It must echo a specific origin and sendAllow-Credentials: true. - Don't blindly reflect the
Originheader with credentials allowed. That lets any site read authenticated responses. Check against an allowlist. Watch for loose regexes:example.com.evil.commatching "contains example.com". - A CORS failure gives the page an opaque
TypeError: Failed to fetch. The actual reason is only in the browser console, deliberately, so pages can't use it to probe. mode: "no-cors"doesn't bypass CORS. It produces an opaque response you can't read, which is only useful for caching or fire-and-forget requests in service workers.
Server configuration examples:
@Configuration
class CorsConfig implements WebMvcConfigurer {
@Override public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com") // explicit allowlist
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.allowedHeaders("Content-Type", "Authorization", "Idempotency-Key")
.exposedHeaders("ETag", "X-Total-Count")
.allowCredentials(true)
.maxAge(600); // cache preflights for 10 min
}
}
// With Spring Security, also enable http.cors(Customizer.withDefaults()) so preflights aren't rejected.
handler := cors.New(cors.Options{
AllowedOrigins: []string{"https://app.example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
ExposedHeaders: []string{"ETag"},
AllowCredentials: true,
MaxAge: 600,
}).Handler(mux)
use tower_http::cors::CorsLayer;
use http::{HeaderValue, Method, header};
let cors = CorsLayer::new()
.allow_origin("https://app.example.com".parse::<HeaderValue>()?)
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
.allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
.allow_credentials(true)
.max_age(std::time::Duration::from_secs(600));
let app = Router::new().nest("/api", api).layer(cors);
# Often simpler to avoid CORS entirely: serve app and API from the SAME origin via a reverse proxy
location /api/ { proxy_pass http://backend:8080/; } # app at https://example.com, API at https://example.com/api
The easiest CORS fix is often not needing CORS: serve the frontend and API from the same origin through a reverse proxy or the frontend framework's server (a BFF, chapter 24), or use the dev server's proxy during development.
Preflight requests
"Non-simple" cross-origin requests could have effects a pre-CORS server never expected, such as a cross-site DELETE or a JSON POST with an Authorization header. So before sending one, the browser asks permission with an OPTIONS preflight:
A request is simple (no preflight) only if it's a GET, HEAD or POST, with only CORS-safelisted headers (Accept, Accept-Language, Content-Language, and Content-Type limited to text/plain, multipart/form-data or application/x-www-form-urlencoded). That means every JSON POST and every request with Authorization gets preflighted.
Preflights cost a full round trip. Mitigations: Access-Control-Max-Age caches the result (browsers cap it at 2 hours in Chromium and 24 hours in Firefox), use a same-origin API, and make sure the server answers OPTIONS quickly without requiring authentication (preflights never carry cookies or Authorization). A classic bug is an auth filter that rejects the preflight with 401, which makes every cross-origin call fail.
Credentials
Fetch's credentials option controls whether cookies, HTTP authentication and TLS client certificates are included:
credentials |
Same-origin | Cross-origin |
|---|---|---|
"omit" |
Never | Never |
"same-origin" (default) |
Included | Not included |
"include" |
Included | Included (needs CORS with Allow-Credentials and a specific origin, and cookies with SameSite=None; Secure) |
Cookies or bearer tokens? Two common ways to authenticate a browser app to an API:
| HttpOnly session cookie | Bearer token in JS (Authorization: Bearer …) |
|
|---|---|---|
| XSS steals it? | No (JS can't read it), though XSS can still make requests | Yes, if stored in localStorage or memory that XSS can reach |
| CSRF risk? | Yes: mitigate with SameSite + CSRF tokens | No (not sent automatically) |
| Cross-origin APIs | Needs CORS with credentials, SameSite=None |
Easy |
| Recommended for SPAs | BFF pattern: the browser holds a session cookie, the backend holds the OAuth tokens (chapter 28) | Short-lived access tokens in memory, if you must |
Chapter 28 covers OAuth 2.0, OIDC and PKCE, and why current guidance (the OAuth 2.0 for Browser-Based Apps BCP) recommends the BFF approach.
Real-time communication
Polling and long polling
Ways for the server to get new data to the browser, from simplest to most capable:
- Polling:
setInterval(() => fetch("/api/status"), 5000). It's simple and works through everything, but it's wasteful (most responses say nothing changed), and latency equals the interval. Fine for slowly changing data. Add jitter, back off when the tab is hidden (visibilitychange), and use ETags so unchanged responses are cheap 304s. - Long polling: the client makes a request, the server holds it open until there's news or a timeout (say 30 s), then responds, and the client immediately sends the next request. It gives near-real-time updates over plain HTTP and was the basis of early chat apps (Comet). It costs one held request per client, and messages can be lost in the gap between requests unless you use cursors.
SSE and WebSocket
Chapter 17 covered the APIs. The network-level view:
- SSE: one long-lived HTTP response streaming
text/event-stream. On HTTP/2 and HTTP/3 it's just another multiplexed stream. It works through proxies and CDNs, provided they don't buffer it: setX-Accel-Buffering: nofor Nginx, and disable compression buffering. Watch out for proxy and load-balancer idle timeouts, and send comment heartbeats. - WebSocket: an HTTP/1.1
Upgradehandshake (101 Switching Protocols), then a different protocol on the same TCP connection. RFC 8441 bootstraps WebSockets over HTTP/2 streams, and RFC 9220 over HTTP/3, though support is uneven. Load balancers must support upgrades and long-lived connections, with sticky routing if per-connection server state matters.
WebTransport
WebTransport is a newer API over HTTP/3 and QUIC. It offers multiple bidirectional and unidirectional streams (with no head-of-line blocking between them), plus unreliable datagrams (UDP-like: fire and forget, for latest-state-wins data such as game positions or live media), all on one connection with built-in congestion control:
const wt = new WebTransport("https://game.example.com:4433/session");
await wt.ready;
const writer = wt.datagrams.writable.getWriter();
writer.write(new Uint8Array([/* player position */])); // unreliable, unordered
const stream = await wt.createBidirectionalStream(); // reliable, ordered
It ships in Chromium and Firefox, and Safari has been adding it. Server support is still maturing (quic-go/webtransport-go, aioquic, and some CDNs). It's aimed at multiplayer games, live streaming (Media over QUIC), and anything that needs WebSocket-like flexibility without TCP's head-of-line blocking. WebRTC remains the option for peer-to-peer audio, video and data channels.
Choosing a real-time transport
| Need | Choose |
|---|---|
| Occasional updates, simplest operations | Polling (with ETag + backoff) |
| Server → client stream: notifications, dashboards, LLM token streaming | SSE (or fetch with a streamed body) |
| Two-way, low-latency messaging: chat, collaboration, trading UI | WebSocket |
| Many independent streams, unreliable datagrams, games and media | WebTransport |
| Peer-to-peer calls and screen sharing | WebRTC |
| Cross-tab sync within one browser | BroadcastChannel (chapter 17) |
Whatever you choose, plan for reconnection, resumption (cursors or last-event IDs), heartbeats, authentication, backpressure, and fan-out across server instances (a pub/sub backbone such as Redis, NATS or Kafka, Vol. 5).
Lab: the network, observed from both ends
Each experiment pairs Chromium 153 (via Playwright) with a small Node server that logs exactly what arrived. Seeing both sides is the fastest way to understand caching, CORS and cookies: the browser's view alone hides most of what happens.
Experiment 1: HTTP/1.1 versus HTTP/2
A page fires 24 fetch requests at once to an endpoint that takes 500 ms to answer. The same Node handler served it over plain HTTP/1.1 and over HTTP/2 with TLS (http2.createSecureServer, self-signed certificate):
HTTP/1.1 24 requests that each take 500 ms on the server: all done in 2044 ms (nextHopProtocol: http/1.1)
HTTP/2 over TLS 24 requests that each take 500 ms on the server: all done in 560 ms (nextHopProtocol: h2)
HTTP/1.1 can carry only one outstanding request per connection, and Chromium opens at most six connections per host, so 24 requests ran in four waves of six: 4 × 500 ms. HTTP/2 multiplexes all 24 as concurrent streams on one connection. This is why bundling and domain sharding were HTTP/1.1-era optimisations, and why on HTTP/2 and HTTP/3 many smaller files are fine. (Browsers only speak HTTP/2 over TLS, which is why the test needed a certificate; nextHopProtocol in Resource Timing tells you what each request actually used.)
Experiment 2: four caching policies on a second visit
One HTML page (served no-cache) loads four identical 1,650-byte scripts with different Cache-Control headers, each with an ETag. The server logged every request; then the page was visited again by following a link:
first visit:
/max-age.js → 200 (1650 bytes)
/no-cache.js → 200 (1650 bytes)
/no-store.js → 200 (1650 bytes)
/app.3f9a1c.js → 200 (1650 bytes)
second visit:
/no-cache.js If-None-Match: "938f16508da7" → 304 Not Modified (no body)
/no-store.js → 200 (1650 bytes)
resource timing: /max-age.js: transferSize 0 | /no-cache.js: transferSize 300 | /no-store.js: transferSize 1950 | /app.3f9a1c.js: transferSize 0
max-age=3600andmax-age=31536000, immutablenever reached the server: served from the cache,transferSize0.no-cachecost a round trip but only about 300 bytes of headers: the ETag matched, the server answered 304.no-storewas downloaded in full again (1,950 bytes including headers).
Two details worth knowing. A reload behaves differently from a navigation: it revalidates max-age resources too (except those marked immutable), which is exactly why immutable exists. And no-cache without a validator (ETag or Last-Modified) can't produce a 304, so it degrades to a full download each time. Check your server sends one.
Experiment 3: compression algorithms on a real bundle
React DOM's production client build (625,168 bytes), compressed with each algorithm Chromium accepts (Accept-Encoding: gzip, deflate, br, zstd), in Node 22's zlib (medians of five runs):
original 625168 bytes
gzip level 6 111376 bytes 17.8% | compress 12.4 ms | decompress 2.3 ms
gzip level 9 110507 bytes 17.7% | compress 61.9 ms | decompress 2.3 ms
brotli quality 5 105082 bytes 16.8% | compress 12.7 ms | decompress 1.8 ms
brotli quality 11 89698 bytes 14.3% | compress 953.7 ms | decompress 1.3 ms
zstd level 3 121605 bytes 19.5% | compress 3.1 ms | decompress 1.5 ms
zstd level 19 92294 bytes 14.8% | compress 223.9 ms | decompress 1.6 ms
The trade-off is compression time on the server against bytes over the network; decompression is cheap for all of them. So: precompress static assets at build time with Brotli 11 (a second of CPU once, 20% fewer bytes than gzip forever), and for dynamic responses compressed on every request use fast settings (Brotli 4–5 or zstd 3). Don't compress already-compressed formats (JPEG, PNG, WebP, video, woff2): it costs CPU and saves nothing.
Experiment 4: CORS, preflights and credentials
An app on http://localhost:8062 calls an API on http://127.0.0.1:8063 (a different origin). For each call, what the page saw and what the API server saw:
simple GET page: status 200 server: GET /a
POST JSON (needs preflight) page: status 200 server: OPTIONS /b (ACR-Method: POST, ACR-Headers: content-type) | POST /b
POST JSON again (preflight cached) page: status 200 server: POST /b
POST form-encoded (simple) page: status 200 server: POST /c
DELETE with custom header page: status 200 server: OPTIONS /d (ACR-Method: DELETE, ACR-Headers: x-trace-id) | DELETE /d
log in (sets a cookie) page: status 200 server: GET /login
credentialed GET, ACAO: * page: TypeError: Failed to fetch server: GET /star Cookie: sid=abc123
credentialed GET, exact origin + credentials page: status 200 server: GET /cred Cookie: sid=abc123
GET without credentials page: status 200 server: GET /cred
- A simple request (GET, HEAD, or POST with a form-style content type, no custom headers) goes straight out; it's no more powerful than an HTML form, so CORS only governs reading the response.
- A JSON body, a
DELETE/PUT/PATCH, or a custom header triggers a preflightOPTIONSthat names the method and headers. The real request is sent only if the answer allows them.Access-Control-Max-Age: 600let Chromium cache the preflight, so the second JSON POST went out alone (Chromium caps the cache at two hours). Preflights add a full round trip; on high-latency mobile networks they're a real cost, which is one reason to serve the API from the same origin through a reverse proxy. - Credentialed requests (
credentials: "include", which sends cookies) need the server to name the exact origin and sendAccess-Control-Allow-Credentials: true; the wildcard*is refused. Note the server still received the cookie on the failing/starrequest and could have acted on it. Only the reading was blocked.
Experiment 5: what SameSite does to cookies
A "bank" on localhost:8064 sets four cookies at login. Then a different site (127.0.0.1:8065) embeds an image from the bank, calls it with fetch, has the user click a link to it, and auto-submits a hidden form to it. The bank logged which cookies arrived each time:
document.cookie on the bank's own page: s_strict=1; s_lax=1; s_none=1 (s_http is HttpOnly: invisible to JS)
request to the bank cookies the browser sent
GET /same-site (from the bank itself) s_strict=1; s_lax=1; s_none=1; s_http=1
GET /img (an <img> on the other site) s_none=1
GET /fetch (fetch from the other site) s_none=1
GET /nav (link clicked on other site) s_lax=1; s_none=1; s_http=1
POST /transfer (form on the other site) s_none=1
HttpOnlyhids_httpfromdocument.cookie, so an XSS bug can't read the session cookie directly.Strictcookies went only with same-site requests: not even when the user followed a link from another site (which is whyStrictsession cookies make users appear logged out after clicking a link in an email).Lax(the browsers' default whenSameSiteis unspecified) added top-levelGETnavigations, so links work, but not the cross-site formPOST, the image or the fetch. That single default eliminated most classic CSRF attacks, like this hidden "transfer" form.None(which requiresSecure) went everywhere. It's needed for genuine cross-site embeds (a payment widget, an SSO iframe) and is exactly what third-party cookie blocking targets.
Experiment 6: Server-Sent Events surviving a dropped connection
A server streams order events with ids, and deliberately drops the connection while sending event 3:
server: connection 1, Last-Event-ID: (none)
page: event id 1 {"order":1,"status":"ready"}
page: event id 2 {"order":2,"status":"ready"}
page: error, readyState 0 (0 = reconnecting)
server: connection 2, Last-Event-ID: 2
page: event id 3 {"order":3,"status":"ready"}
page: event id 4 … 6
The browser's EventSource noticed the drop, waited the retry: 300 milliseconds the server asked for, reconnected by itself, and sent Last-Event-ID: 2, so the server resumed from event 3: the one lost in transit was re-sent, and the page saw every event once, in order. With a WebSocket you'd write all of that yourself (reconnect with backoff, track the last message, resume). The catch: under HTTP/1.1 each EventSource holds one of the six per-host connections open; over HTTP/2 they're just streams.
Try it yourself
- In experiment 2, reload instead of navigating. Which requests change? Then add
immutabletomax-age.jsand reload again. - Make the API in experiment 4 forget to answer
OPTIONS. What exactly does the console say, and what does the server log show? - Change the bank's session cookie to
SameSite=Strictand log in via a link from another site. What does the user experience, and how do sites work around it? - Write a minimal WebSocket chat with the
wspackage, then kill the server mid-conversation. What do you need to add to match SSE's automatic resume?
Revision sheet: frontend networking
Key ideas
- HTTP semantics (methods, status codes, headers, content negotiation, caching, conditional requests) are the same across versions; the versions differ in framing and transport.
- HTTP/1.1: text, one outstanding request per connection, about six connections per host. HTTP/2: binary frames, multiplexed streams, HPACK header compression, one TCP connection (TCP head-of-line blocking under loss). HTTP/3: QUIC over UDP, per-stream loss recovery, 1-RTT (0-RTT resumption) handshakes, connection migration; advertised with
Alt-Svcor DNS HTTPS records. - Caching: freshness (
max-age,s-maxage,immutable) then validation (ETag/If-None-Match,Last-Modified/If-Modified-Since→ 304);no-cacherevalidates,no-storenever stores;Varysplits cache entries;stale-while-revalidateserves stale while refreshing. Hash static file names and cache them for a year. - Compression: negotiated via
Accept-Encoding/Content-Encoding; precompress static assets with Brotli 11; fast levels for dynamic content. - Cookies:
Domain,Path,Expires/Max-Age,Secure,HttpOnly,SameSite(Lax default),Partitioned(CHIPS);__Host-prefix for locked-down session cookies. - CORS: the server opts in with
Access-Control-Allow-Origin; non-simple requests are preflighted (OPTIONS, cached byAccess-Control-Max-Age); credentials require an exact origin plusAllow-Credentials: true;Access-Control-Expose-Headersfor reading custom response headers. - Real time: polling, long polling, SSE (auto-reconnect,
Last-Event-ID), WebSocket (bidirectional, you build reconnection), WebTransport (streams and datagrams over HTTP/3).
Numbers to remember
- 6 connections per host on HTTP/1.1 (24 × 500 ms requests: 2,044 ms vs 560 ms on HTTP/2 in the lab).
- Cookie size about 4 KB; preflight cache capped at 2 hours in Chromium (
Access-Control-Max-Age). - Brotli 11 on a 625 KB bundle: 14.3% of original vs gzip's 17.8%.
- One year =
max-age=31536000.
Pitfalls
- Treating CORS as server security; fixing CORS errors in frontend code.
Access-Control-Allow-Origin: *with credentials; reflecting anyOriginback with credentials allowed (a vulnerability).no-cachewithout ETag/Last-Modified; caching HTML for long periods; forgettingVary: Accept-EncodingorVary: Originat CDNs.- Session cookies without
HttpOnly,Secureand aSameSitechoice. - Assuming
fetchrejects on HTTP errors; no timeouts or retries with backoff. - WebSockets without heartbeats, reconnection and resume.
Glossary
- Idempotent: repeating the request has the same effect as doing it once (GET, PUT, DELETE).
- Validator: an
ETagorLast-Modifiedvalue used for conditional requests. - Preflight: the
OPTIONSrequest asking permission for a non-simple cross-origin request. - Multiplexing: interleaving many requests' frames on one connection.
- Head-of-line blocking: a lost or slow item delaying everything queued behind it.
- SameSite: a cookie attribute controlling whether it's sent with cross-site requests.