Sub topic 17
Inspecting traffic with curl and DevTools
This chapter assumes you have read the earlier chapters on URLs, DNS, HTTP messages, status codes, headers, cookies, and caching. You should be comfortable running commands in a terminal and opening a browser. The goal is to turn that knowledge into a repeatable debugging routine.
Why inspect traffic
Most web bugs are disagreements between what you think was sent and what was actually sent. A form posts to the wrong path. A cookie is never stored. A cached file is stale. A request is blocked by CORS. Reading the real messages replaces guessing with evidence.
Two tools cover most cases:
curlis a command-line HTTP client. It sends exactly the request you describe and shows you the raw result. It has no page rendering, no cache, and no cookie jar unless you ask for one.- Browser DevTools are the inspector built into the browser. They show what the browser actually did, including caching, redirects, cookies, and cross-origin checks.
Using both gives you a comparison. If curl succeeds and the browser fails, the cause is usually a browser-only rule such as CORS, cookies, or the cache.
Watching an exchange with curl
The -v flag prints the request and response headers.
curl -v https://example.com/The output mixes three kinds of lines:
| Prefix | Meaning |
|---|---|
| `*` | Information from curl itself, such as DNS results, the TCP connection, and the TLS handshake |
| `>` | Lines curl sent to the server (the request) |
| `<` | Lines the server sent back (the response) |
Read the output from top to bottom and you see the same order the earlier chapters described: name lookup, connection, TLS, request, response.
Useful curl options
| Option | Effect |
|---|---|
| `-I` | Send a `HEAD` request and print only the response headers |
| `-i` | Include response headers in the output along with the body |
| `-s` | Silent mode. Hides the progress meter |
| `-o file` | Write the body to a file instead of the terminal |
| `-L` | Follow redirects (`301`, `302`, `307`, `308`) |
| `-X METHOD` | Set the request method |
| `-H "Name: value"` | Add or replace a request header |
| `-d data` | Send a request body. This makes the method `POST` unless you change it |
| `-b` and `-c` | Read cookies from, and save cookies to, a file |
| `-w format` | Print values such as the status code or timings after the transfer |
| `--resolve host:port:ip` | Force a hostname to map to a specific IP address |
Combine options to ask narrow questions. This command prints only the status code:
curl -s -o /dev/null -w "%{http_code}\n" https://example.com/This one follows redirects and prints the final URL and the number of redirects:
curl -sL -o /dev/null -w "%{url_effective} after %{num_redirects} redirects\n" http://example.com/Reproducing requests by hand
You can build any request from the earlier chapters. To send a custom header and a JSON body to a local server:
curl -v -X POST http://localhost:3000/items \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"name":"pen"}'If you want to see the server side of this, run the small Node.js server from the earlier chapter. It echoes the method and path of each request.
import { createServer } from "node:http";
const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(`You requested ${req.method} ${req.url}\n`);
});
server.listen(3000);Save it as server.mjs, run node server.mjs, and call it from another terminal:
curl -i "http://localhost:3000/search?q=http"The response body is You requested GET /search?q=http. Notice that the path and query string arrive together in req.url. The fragment never arrives, because browsers do not send it to the server.
Testing caching with curl
curl has no cache, so it is a clean way to check what a server says about caching. Request the headers and look for Cache-Control, ETag, and Last-Modified:
curl -sI https://example.com/logo.pngThen replay a conditional request using the ETag value you saw:
curl -i https://example.com/logo.png -H 'If-None-Match: "v1"'A 304 Not Modified response with no body means the validator matched. A 200 with a body means the validator did not match, or the server ignores conditional requests.
Testing cookies with curl
By default curl discards cookies between runs. Use a cookie jar to keep them:
curl -c jar.txt -b jar.txt -v https://example.com/login
curl -c jar.txt -b jar.txt -v https://example.com/accountIn the verbose output, look for Set-Cookie in the first response and a Cookie line in the second request. If the cookie is missing from the second request, check its Domain, Path, and Secure attributes against the URL you used.
Inspecting traffic in browser DevTools
Open DevTools with F12, or Ctrl+Shift+I (Cmd+Option+I on macOS). The Network panel records requests made while it is open, so open it first and then reload the page.
Reading the request list
Each row is one request. Useful columns are Name, Status, Type, Size, and Time. Right-click the header row to add more, such as Protocol (which shows http/1.1, h2, or h3) and Domain.
Filters narrow the list by type, such as Fetch/XHR, JS, CSS, Img, and Doc. The search box filters by URL text.
Reading one request
Click a row to see its details:
- Headers: the request line, the request headers, and the response headers. The browser may show a "Provisional headers" notice if the request never completed.
- Payload: the query parameters and request body.
- Preview and Response: the body, either formatted or raw.
- Cookies: the cookies sent and received, with their attributes. Rejected cookies are usually flagged with a reason.
- Timing: a breakdown of the request into stages.
The Timing tab lines up with the earlier chapters. Stages include queueing, DNS lookup, initial connection, SSL (the TLS handshake), waiting for the first byte (often shown as TTFB), and content download. A long wait for the first byte points at the server. A long DNS or connection stage points at the network.
Settings that change what you see
- Disable cache (checked while DevTools is open) makes the browser skip its cache. Use it to see what a first-time visitor gets. Clear it when you want to test caching.
- Preserve log keeps requests across page navigations and redirects. Without it, the list clears on each navigation and you lose the redirect chain.
- Throttling simulates slower networks.
Recognizing cache behavior
The Size column tells you where a response came from. A value such as (memory cache) or (disk cache) means the browser did not contact the server at all, because the stored copy was still fresh. A small size with status 304 means the browser revalidated and the server confirmed the copy was valid.
A debugging routine
When a page misbehaves, work from the outside in.
- Open the Network panel with Preserve log on, and reproduce the problem.
- Find the failing request. Sort by Status, or filter by Fetch/XHR if the failure is from JavaScript.
- Read the status code.
4xxmeans the request was wrong or not allowed.5xxmeans the server failed. - Read the request headers. Check the method, path,
Content-Type,Cookie, andAuthorization. - Read the response headers. Check
Content-Type,Set-Cookie,Cache-Control,Locationfor redirects, and anyAccess-Control-*headers. - Right-click the request and choose Copy as cURL. Paste it in a terminal and run it.
- Change one thing at a time in
curluntil the behavior changes.
The Copy as cURL step is the most useful link between the two tools. It reproduces the browser's exact request, including cookies and headers. If the copied command works but your own code fails, the difference is in what your code sends.
Common symptoms and likely causes
| Symptom | Where to look | Likely cause |
|---|---|---|
| Console says a request was blocked by CORS policy | Response headers of the request, and the preflight `OPTIONS` request | Missing or mismatched `Access-Control-Allow-Origin`, or the preflight did not return a success status |
| `curl` works, `fetch` fails | Console, then Network | CORS. The server answered, but the browser refused to expose the response to the page |
| Cookie never sent | Cookies tab, and `Set-Cookie` attributes | `Secure` on an HTTP page, wrong `Path` or `Domain`, or `SameSite` blocking a cross-site request |
| Old content after a deploy | Size column and `Cache-Control` | A long `max-age` on a file whose URL did not change |
| Redirect loop | `Location` headers with Preserve log | Two rules redirecting to each other, often HTTP to HTTPS behind a proxy |
| Garbled text | `Content-Type` header | Missing or wrong `charset` |
| Certificate error | `curl -v` TLS lines | Expired certificate, wrong hostname, or an incomplete certificate chain |
| Slow page, fast `curl` | Timing tab | Many requests, large scripts, or rendering cost rather than the server |
Edge cases
- CORS and
curl. CORS is enforced by browsers, not by servers or bycurl. A server that omits CORS headers still answerscurlnormally. This is whycurlcannot reproduce a CORS failure, though it can show you the missing headers. - Preflight requests. For some cross-origin requests, the browser first sends an
OPTIONSrequest. You can imitate it withcurl -i -X OPTIONS -H "Origin: https://app.example" -H "Access-Control-Request-Method: POST" https://api.example.com/items. - HTTP version.
curlnegotiates the version itself. Use--http1.1or--http2to force one, and look at the Protocol column in DevTools to see what the browser used. Under HTTP/2 and HTTP/3, headers are shown in lowercase and the request line has pseudo-headers such as:method. - Compressed bodies. Browsers send
Accept-Encodingand decompress automatically.curldoes not request compression unless you add--compressed, so body sizes can differ between the tools. - User-Agent. Some servers vary their response by
User-Agent. Add-A "Mozilla/5.0"tocurlif a site treats it differently from a browser. - Self-signed certificates.
curl -kskips certificate checks. Use it only against a local test server, never to silence a real certificate problem. - Requests that never appear. If DevTools shows nothing, the request may have failed before it was sent, for example from a DNS failure or a blocked mixed-content request. The Console usually names the reason.
Exercise
A page loads a script from /app.js. After you deploy a fix, users still run the old script. In DevTools, the Size column for /app.js shows (disk cache). What does that tell you, which response header most likely caused it, and how could you confirm with curl?
Show answer
The browser used its stored copy and never contacted the server, so the cached response was still considered fresh. The most likely cause is a long Cache-Control: max-age=... on a URL that did not change. Confirm by running curl -sI https://your-site/app.js and reading the Cache-Control and ETag headers. The usual fix is to give each build a new URL, such as app.3f9a1c.js, or to use a short max-age with revalidation.
Exercise
A fetch call to https://api.example.com/items fails in the browser with a CORS error, but curl https://api.example.com/items returns the JSON correctly. Why is this not a contradiction, and what would you check?
Show answer
CORS is enforced by the browser. The server returned the data, so curl shows it, but the browser withholds the response from the page unless the response allows the page's origin. Check the response headers for Access-Control-Allow-Origin using curl -i -H "Origin: https://your-page-origin" https://api.example.com/items, and check the OPTIONS preflight request in the Network panel if the request uses a non-simple method or custom headers.
Exercise
Write a curl command that follows redirects from http://example.com/ and prints only the final URL and the final status code.
Show answer
curl -sL -o /dev/null -w "%{url_effective} %{http_code}\n" http://example.com/