The Network tab breaks a request into phases and shows which layer is slow, while a HAR is a JSON record of all the page's network activity. In Playwright, slow network is emulated for Chromium through CDP, and offline through context.setOffline(), which works in every browser. An exported HAR is checked before sharing: response bodies and tokens in URLs remain. A HAR used as a stable backend ages with the API.
Networking · Testing
On the developer’s desk everything works, but on a train the "no connection" banner never appears. How do you reproduce such a network?
A test that runs in a fast office network checks the most favourable case. Real users have slow 3G, drops, offline and long responses. The Network tab in DevTools shows where exactly the time goes, and network emulation lets you reproduce bad conditions at home and lock them into a test. This lesson covers reading Network, what a HAR is, and how to slow down, cut and record the network in Playwright.
How it works and why. Every request on the Network tab passes through phases, and a long phase points at a specific layer. So you read the breakdown first and only then decide whether the cause is in the network, the server or the page itself.
Request phases on the Timing tab
Figure 1. A long phase tells where to look: the queue, the connection, the server or the download.
What else is in the tab.
Filters (Fetch/XHR, WS, Doc) and search across response bodies.
Preserve log keeps the list across redirects and navigation, Disable cache turns the cache off while DevTools is open.
Columns Status, Protocol (h2, h3), Initiator (who created the request), Time.
For WebSocket a separate Messages tab with frames in both directions.
The request context menu: Copy as cURL, to repeat it in a terminal.
HAR. HTTP Archive is a JSON record of all the page’s network activity: requests, responses, timings. It is exported from DevTools ("Export HAR (sanitized)" or "Save all as HAR (sanitized)") and attached to a bug instead of a screenshot. By default Chrome exports a "sanitized" HAR without the Cookie, Set-Cookie and Authorization headers, but response bodies and tokens in URLs remain, so check the file before sharing it. Playwright can record and replay the same format.
Example: a slow network and offline in Playwright. Playwright has no built-in network throttling. For Chromium it is done through a CDP session. In the CDP protocol the Network.emulateNetworkConditions command is marked deprecated in favour of the experimental Network.emulateNetworkConditionsByRule and Network.overrideNetworkState, but it is still available. Offline is emulated by context.setOffline(), which works in every browser.
Slows one request, works in every browser, but it is not the network: the handler simply waits.
CDP throttling
Slows the whole page like DevTools, but only in Chromium and through a protocol that changes.
Figure 2. Choose by purpose: one request or the whole page, one browser or all of them.
Individual requests are slowed in page.route: a delay before route.continue(). More realistic is at the OS or proxy level: Network Link Conditioner (macOS), tc netem (Linux), Toxiproxy as a proxy with latency and drop "toxics". On such a network you check not just "it works" but the spinner, timeouts, the error message, retry and recovery without duplicated actions.
Example: a HAR as a stable backend for a UI test. The file is recorded once on a real environment, then UI tests replay the answers from the file. Tests are fast and independent of data, but the file ages along with the API.
// recording: the HAR is written when the context closesconst context = await browser.newContext({
recordHar: { path: 'hars/orders.har', urlFilter: '**/api/**' },
});
// ... the scenario ...await context.close();
// replay without the real backendawait page.routeFromHAR('hars/orders.har', {
url: '**/api/**',
notFound: 'abort', // an unknown request fails at once
});
Limits and alternatives. Browser throttling changes speed but not the behaviour of a real network: no packet loss, no Wi-Fi to mobile switch, no heavy jitter. A HAR holds one snapshot, so it will not show a change in the API schema: you still need a few e2e tests without mocks. For mobile apps and non-browser clients these tools do not fit: use a proxy or a device network emulator.
Typical mistakes.
Measuring speed with DevTools open and Disable cache on, then drawing conclusions about users.
Forgetting await context.close() so the HAR is not written.
Handing a HAR to a colleague or vendor without checking response bodies and tokens in URLs.
Leaving CDP throttling in a test for Firefox or WebKit: newCDPSession does not work there.
Checking only that the banner appeared and not recovery after the network returns.
Check yourself
On the Timing tab the Waiting (TTFB) phase is long. What does it mean and where do you look next?
Answer
The client sent the request and waits long for the first byte: a slow server, backend or database. Next look at server logs and traces and check whether the delay is stable. A long DNS or SSL would point to the network and a new connection.
How does context.setOffline(true) differ from CDP throttling?
Answer
setOffline switches the context’s network off entirely and works in every browser. CDP throttling keeps the network but adds latency and limits throughput, and works only in Chromium.
Is it safe to hand a HAR from a bug report to outsiders?
Answer
Not without a check. The DevTools export strips Cookie, Set-Cookie and Authorization by default, but response bodies and tokens in URLs remain, so the file is reviewed and cleaned.
Related lessons: “Intercepting and mocking requests, proxy tools”, “Diagnosing network failures: curl, dig and error classes”, “HTTP/1.1, HTTP/2 and HTTP/3: what changed”.
In an interview.Junior: In Network I look at status, body, headers and Timing to see where the time goes. A HAR is a JSON record of the network, attached to bugs. I check offline in DevTools. Middle/Senior: In Playwright I make a slow network through CDP in Chromium, offline through setOffline, and slow single requests in route. I know the CDP command is marked deprecated, so I keep it in one place. I record and replay a HAR for stable UI tests, but clean it before sharing and do not use it in place of e2e without mocks.
Intercepting and mocking requests, proxy tools
In a browser the response is replaced by page.route, while for a mobile or desktop client a proxy sits between it and the server. A route handler calls fulfill, continue or abort: abort models a network failure, and fulfill with 503 is a server response, so both are tested. HTTPS through a proxy needs a trusted root certificate, and certificate pinning blocks it. Mocks do not replace a few end-to-end tests.
Networking · Testing
You need to check how a mobile app behaves when the backend returns 500, and you cannot change the backend. What do you do?
A real backend rarely breaks on demand. To check a 500, a slow response or a lost connection, the response is replaced between the client and the server. For a browser the test itself does it, for a mobile app or a desktop client a proxy is needed. This lesson covers both approaches, the difference between "cut" and "answer with an error", and why proxies and HTTPS do not get along without a certificate.
How it works and why.page.route(url, handler) (or context.route for all pages of a context) puts a handler on requests that match a pattern. The handler decides one of three things: route.fulfill() returns its own response, route.continue() passes the request on (changing headers or body if needed), route.abort(code) cuts it with a network error. route.fetch() performs the real request so you can change the response and return it via fulfill. Abort codes include connectionrefused, connectionreset, timedout, namenotresolved, internetdisconnected, failed and others.
// a network failure: fetch ends with a TypeError, Network shows failedawait page.route('**/api/orders', (route) => route.abort('connectionrefused'));
// a server answer with an error: status 503 and a bodyawait page.route('**/api/orders', (route) =>
route.fulfill({ status: 503, json: { error: 'unavailable' } }),
);
// a real request, but a changed responseawait page.route('**/api/profile', async (route) => {
const response = await route.fetch();
const body = await response.json();
body.plan = 'expired';
await route.fulfill({ response, json: body });
});
// slowing one requestawait page.route('**/api/report', async (route) => {
awaitnewPromise((r) => setTimeout(r, 5000));
await route.continue();
});
abort and fulfill are different cases.abort models a network failure: in the browser fetch ends with a TypeError, Network shows failed, and there is no response at all. fulfill({ status: 503 }) is a server answer with an error code: the client got a status and a body. An app usually handles them in different branches, so test both.
Where to intercept
Interception in a test
Playwright page.route: only the test’s browser, code next to the assertion, easy to repeat in CI.
A proxy tool
Charles, Fiddler, Proxyman, mitmproxy: any client including mobile, a trusted certificate is needed.
Figure 1. The two approaches complement each other: the test locks in a scenario, a proxy lets you explore any client.
Proxy tools. They sit between the client and the server and work with any client: a mobile app, a desktop app, an SDK. Charles, Fiddler and Proxyman have a graphical interface, traffic viewing and editing, replacing a response with a local file or another host. mitmproxy works from a terminal or web interface and is driven by Python scripts, so it automates well.
# addon.py: reply from the proxy for one endpoint: the request never reaches the backend
from mitmproxy import http
def request(flow: http.HTTPFlow) -> None:
if flow.request.pretty_url.endswith("/api/orders"):
flow.response = http.Response.make(
503,
b'{"error": "unavailable"}',
{"Content-Type": "application/json"},
)
# run: mitmdump -s addon.py
# on the device: proxy host:8080, the certificate from http://mitm.it
Why HTTPS needs a certificate. To read or change encrypted traffic, the proxy acts as a man in the middle: it signs certificates for hosts with its own root certificate. The client must trust that root or it shows an error. So the root is added to the device’s trusted ones. On Android, apps targeting API 24+ (Android 7.0) do not trust user roots unless their network security config allows them, and on iOS the root is also switched on in the certificate trust settings. Certificate pinning blocks such traffic completely.
What must line up for a proxy to see HTTPS
Figure 2. If any step is broken, the app refuses to work through the proxy.
Typical scenarios. Replace a backend response without changing code; reproduce a 500 or a slow response on mobile; see what exactly an SDK sends; check that the app does not send extra data. For an app with pinning, use a test build without pinning rather than bypassing protection in the production build.
Limits and alternatives. Replacing always hides the real integration: a mock returns what you invented, not what the backend would. So mocks supplement a few end-to-end tests without mocks, not replace them. If you need to replay many services’ responses, contract tests and a dedicated mock server beat manual replacement through a proxy. A proxy adds its own latency and sometimes changes behaviour (the HTTP version, for example), so performance measurements through it are not representative.
Typical mistakes.
Testing only fulfill with 500 and not the network error (abort).
Replacing all integration tests with mocks and missing that the API changed its schema.
Registering page.route after goto, when the request has already left.
Leaving the proxy root trusted on a test device after work.
Not knowing that pinning blocks a proxy and hunting for the error in the proxy settings.
Check yourself
How do route.abort('connectionrefused') and route.fulfill({ status: 503 }) differ for the UI?
Answer
The first simulates a network failure: no response, fetch ends with a TypeError. The second is a server response with status 503. An app usually handles these differently, so test both.
A mobile app does not work through the proxy although the certificate is installed on the phone. Name two causes.
Answer
An Android app with targetSdkVersion 24+ does not trust user roots without permission in the network security config, or it has certificate pinning, which blocks a proxy. On iOS the root also has to be switched on in the trust settings.
Why do mocks not replace all integration tests?
Answer
A mock returns what you put in and will not show that the real backend changed schema or behaviour. A few end-to-end tests without replacement are needed.
Related lessons: “DevTools Network, HAR, throttling and offline”, “Diagnosing network failures: curl, dig and error classes”, “TCP handshake, TLS 1.3 and certificates”.
In an interview.Junior: In Playwright page.route lets me replace a response (fulfill), pass it (continue) or cut it (abort). For mobile apps there are proxies such as Charles, Fiddler or mitmproxy. Middle/Senior: I separate a network failure from an error response and test both. With route.fetch I change only the needed field of a real response. HTTPS through a proxy needs a trusted root; on Android 7+ that depends on the network security config, and pinning blocks interception, so tests need a separate build. I supplement mocks with a few tests without replacement.
Diagnosing network failures: curl, dig and error classes
A network failure is narrowed to a layer by following the request order: DNS, TCP, TLS, HTTP, application, stopping at the first that fails. ENOTFOUND points to DNS, ECONNREFUSED to a port nobody listens on, a connection timeout to dropped packets; 502 and 504 come from a proxy or load balancer. curl -w values are cumulative, so a stage's duration is the difference of adjacent values. A retry hides the cause.
Networking · Testing
A CI test fails with "network error" once in ten runs. Where do you start: the test code or the network?
The message "network error" says nothing: it can be DNS, a port, a certificate, a proxy or the application itself. Someone who can quickly narrow a failure to a layer does not guess and does not cure with a retry what a retry only hides. This lesson gives a diagnosis order, a table of symptoms and a set of commands to check them.
How it works and why. A request goes through a sequence of steps and each can fail on its own: a name becomes an IP, a TCP connection is made, TLS is negotiated, HTTP flows, the application answers. A failure at an early step makes later ones unreachable, so you go in request order, bottom up, and stop at the first layer that does not work.
Diagnosis by layer
Figure 1. The first layer that fails is where to look; checking the rest is pointless.
Symptom
Layer and typical cause
ENOTFOUND, ERR_NAME_NOT_RESOLVED
DNS: a typo in the name, no record, a resolver or VPN
ECONNREFUSED
TCP: nobody listens on the port (service not started, wrong port, listens on 127.0.0.1 only)
Timeout with no answer (ETIMEDOUT)
TCP/network: a firewall drops packets, the host is unreachable
ECONNRESET, socket hang up
The other side cut the connection: a process crash, idle timeout, overload
ERR_CERT_*, UNABLE_TO_VERIFY_LEAF_SIGNATURE
TLS: an expired, self-signed or incomplete chain, a name mismatch
502 Bad Gateway
The proxy got an invalid response or could not connect to the upstream
503 Service Unavailable
The service is unavailable or overloaded (no healthy backends)
504 Gateway Timeout
The proxy did not get an upstream answer within its timeout
Important: 502 and 504 come from a proxy or balancer (503 often too, but the application itself can return it), so the connection to it works and the problem is behind it. The response body (nginx or CDN HTML instead of JSON) and the Server and Via headers show who returned it.
Tools.
curl -v https://example.com/health # DNS, TLS, request and response headers
curl -i https://example.com/health # status and response headers (Server, Via)
curl --resolve example.com:443:203.0.113.10 https://example.com
# bypass DNS, force an IP
dig +short example.com A # what DNS says
dig @1.1.1.1 example.com # another resolver
nc -vz example.com 443 # is the port open
ping example.com # ICMP may be disabled
traceroute example.com # on Windows: tracert
# Windows PowerShell: is the port open
Test-NetConnection -ComputerName example.com -Port 443
Example: where exactly the time goes. The -w variables in curl are cumulative: each counts from the start of the request, not from the previous stage. So tcp includes DNS and tls includes TCP. The duration of a single stage is the difference between neighbouring values.
curl -sS -o /dev/null -w \
"dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" \
https://example.com/health
# illustrative output, values are cumulative (from the start of the request)# dns=0.012 tcp=0.045 tls=0.130 ttfb=1.210 total=1.260
From this output: DNS 12 ms; TCP connect 45 − 12 = 33 ms; TLS 130 − 45 = 85 ms; backend wait (ttfb − tls) 1210 − 130 = 1080 ms; body download (total − ttfb) 50 ms. The slow part here is the backend, not the network path: no point spending time on DNS. A large dns would point at the resolver, a large total − ttfb at a long body download.
Approach to a flaky network. First look for a pattern: time of day, a particular runner or region, the first request after idle (a cold connection, DNS), exactly N seconds (a match with a timeout on some node). Then add to the test log the URL, time, status, x-request-id and a trace or HAR so the next failure is explainable. A retry does not cure the cause but hides it, so it is enabled deliberately and only after diagnosis. In CI keep explicit client timeouts, keep-alive and a connection pool.
Limits and alternatives.ping shows only ICMP, which is often blocked, so no reply proves nothing. nslookup and dig query a resolver directly, while the application may use its own cache or system settings, so the result can differ from what the test sees. From a container or a CI runner the network may differ from a laptop: run diagnosis where the test fails.
Typical mistakes.
Reading time_connect as the TCP duration without subtracting DNS.
Adding a retry instead of finding the cause.
Taking 502 and 504 for an application error rather than a proxy or upstream one.
Diagnosing from a laptop when only the CI runner fails.
Not logging the request id and later failing to find the request in server logs.
Check yourself
curl -w shows tcp=0.045 tls=0.130. How long did the TLS negotiation take?
Answer
0.130 − 0.045 = 0.085 s, that is 85 ms. curl variables are cumulative, so a stage’s duration is the difference between neighbouring values.
The API answers 504 with an nginx HTML page instead of JSON. Where do you look?
Answer
The proxy returned it, so the connection to it works and the upstream did not answer within the proxy timeout. Look at backend response time, the proxy timeout and the upstream logs.
How does ECONNREFUSED differ from a timeout with no answer?
Answer
ECONNREFUSED comes quickly: the host answered that nobody listens on the port. A timeout means no answer at all: a firewall drops packets or the host is unreachable.
Related lessons: “DNS: name resolution, records, TTL and cache”, “TCP handshake, TLS 1.3 and certificates”, “Proxies, load balancers, CDNs and timeouts”.
In an interview.Junior: I go by layers: DNS, connection, TLS, HTTP, application. I read the error code and status and use curl -v and dig. Middle/Senior: I tell errors apart by layer (ENOTFOUND, ECONNREFUSED, ECONNRESET, certificate, 502/503/504) and know that a proxy returns 502 and 504. I read curl timings as cumulative and compute differences. For a flaky network I look for a pattern, log request id and trace, and enable a retry only after diagnosis and with explicit timeouts.