← Back to dashboard
networkingtoolingfreshReader view (for NotebookLM)

Networking Integration Guide

What is networking, as a working model?

The real model

Almost all of it is someone else's infrastructure, so the real skill is proving which layer is lying.

The DNS rule that resolves most tickets: dig @<authoritative-ns> gives truth, dig @1.1.1.1 gives reach — right at the NS and wrong at 1.1.1.1 means a TTL is still counting down, so wait, because lowering a TTL is not retroactive and re-editing resets nothing. The TLS rule: the most common production bug is a server that serves the leaf but omits the intermediate, which browsers rescue via AIA fetching and curl and mobile SDKs do not, so 'works in Chrome, fails in the app' is a chain problem — and NODE_TLS_REJECT_UNAUTHORIZED=0 turns it into a permanent MITM hole. For codeAmani the two live edges are the deploy path (Porkbun registrar → apex A record because CNAME is illegal at the apex → CAA record or issuance fails → Cloudflare Full (strict) so the origin hop is verified too) and the callback endpoints: M-Pesa and Stripe are inbound signature-verification problems, but any admin field that accepts a callback URL is an outbound SSRF sink where 169.254.169.254 is one fetch away. Two 2026 facts change the defaults: Vercel is still IPv4-only and does not advertise HTTP/3, so on Kenya-targeted builds the HTTP/3 win (no TCP head-of-line blocking on lossy radio, connections that survive a tower change) only arrives with Cloudflare proxied in front; and certificate lifetimes are capped at 200 days now and 47 by 2029, so what you monitor is a blocked renewal (CAA, a redirected /.well-known/acme-challenge path), not '30 days left'. Every extra third-party origin still costs a fresh DNS+TCP+TLS round trip, roughly a second at 300ms RTT.

Eight things you reach for first

Not a protocol tour — the handful of concepts and commands that actually localise a fault.

Text
███╗   ██╗███████╗████████╗██╗    ██╗ ██████╗ ██████╗ ██╗  ██╗██╗███╗   ██╗ ██████╗
████╗  ██║██╔════╝╚══██╔══╝██║    ██║██╔═══██╗██╔══██╗██║ ██╔╝██║████╗  ██║██╔════╝
██╔██╗ ██║█████╗     ██║   ██║ █╗ ██║██║   ██║██████╔╝█████╔╝ ██║██╔██╗ ██║██║  ███╗
██║╚██╗██║██╔══╝     ██║   ██║███╗██║██║   ██║██╔══██╗██╔═██╗ ██║██║╚██╗██║██║   ██║
██║ ╚████║███████╗   ██║   ╚███╔███╔╝╚██████╔╝██║  ██║██║  ██╗██║██║ ╚████║╚██████╔╝
╚═╝  ╚═══╝╚══════╝   ╚═╝    ╚══╝╚══╝  ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝

Networking Integration Guide

Focus: The working model of TCP/IP, addressing, DNS, TLS and HTTP/1.1–3 that an application developer needs, plus the long-lived connection patterns (WebSockets, SSE), CORS, local tunnels, WSL networking, the diagnostic commands that prove which layer is failing, and the defensive posture for network-layer risk (open ports, weak TLS, DNS hijacking, SSRF, MITM).

Overview

This is a topic guide, not an SDK. The three npm packages in the frontmatter are the ones the runnable examples use: undici for the SSRF-safe fetch, and ws with @vercel/functions for WebSockets on Vercel. The real deliverable is a mental model plus a toolbox. Reach for it when:

  • a deploy "works locally" but not in production;
  • a domain resolves for you but not for your users;
  • a certificate is valid in the browser but curl rejects it;
  • a realtime feature drops connections;
  • a webhook receiver needs a public URL on your laptop;
  • an endpoint has to make an outbound call to a URL it did not choose.

Two models describe the same stack. The OSI seven-layer model is the vocabulary (people say "layer 7" and "layer 4"). The TCP/IP four-layer model is what actually ships. Talk in OSI terms and debug in TCP/IP terms.

TCP/IP layerOSI layersWhat lives hereWhat breaks
Link1–2 Physical, Data LinkEthernet, Wi-Fi, MAC addresses, ARP / NDPCable/radio, MTU, local LAN only
Internet3 NetworkIPv4/IPv6, ICMP, routing, NATWrong route, firewall drop, no IPv6 path
Transport4 TransportTCP (ordered, reliable), UDP (datagrams; QUIC runs on it)Port closed, RST, SYN timeout
Application5–7 Session, Presentation, ApplicationDNS, TLS, HTTP/1.1, HTTP/2, HTTP/3, WebSocketBad record, expired cert, 4xx/5xx

A request can fail at every arrow in that diagram, and each failure has its own symptom. The rest of this guide walks them in order.

What changed since the last review (2026-08-23 → 2026-10-20)

AreaWasNow
Vercel IPv6Guide said Vercel publishes AAAA for youWrong. Vercel docs: "we do not support IPv6 yet". You cannot point an AAAA record at Vercel
Vercel HTTP/3Guide said "Vercel serves HTTP/3 by default"Not documented, and not advertised. Vercel's encryption docs list TLS 1.2/1.3 only, and vercel.com sends no Alt-Svc header (checked 2026-10-20). Cloudflare offers HTTP/3 on every plan
Vercel realtimeNo WebSockets on Functions; use a third-party serviceWebSockets on Vercel Functions, public beta (2026-06-22). Requires Fluid compute. Next.js uses upgradeWebSocket() from @vercel/functions ≥ 3.10.0
Vercel Edge runtimeA normal optionVercel recommends migrating from edge to Node.js, and from Next.js 16.3 runtime = 'edge' is no longer supported. Both run on Fluid compute with Active CPU pricing
Cert lifetimes398 days maxCA/B Forum SC-081: 200 days max from 2026-03-15, 100 from 2027-03-15, 47 from 2029-03-15. Let's Encrypt classic profile: 64 days from 2027-02-10, 45 days from 2028-02-16
SNI privacySNI is always cleartextECH is RFC 9849 (March 2026). Vercel enables it automatically, and browsers use it when the domain's HTTPS DNS record carries the config
TLS key exchangeClassical ECDHEPost-quantum hybrid X25519MLKEM768 is offered by Vercel and Cloudflare and negotiated by current Chrome, Firefox and Safari
StandardsRFC 8499 (DNS terms), RFC 7489 (DMARC), OWASP A10:2021 SSRFRFC 9499 obsoletes 8499. RFC 9989 (May 2026, Standards Track) obsoletes 7489. OWASP Top 10:2025 folds SSRF into A01 Broken Access Control
WSLNot coveredMirrored networking mode (networkingMode=mirrored, Windows 11 22H2+)
TunnelsOne line about ngrokngrok, Cloudflare Tunnel and Tailscale Serve/Funnel compared, with free-tier limits

Official Documentation

ResourceURL
MDN — HTTP overviewhttps://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview
MDN — Transport Layer Securityhttps://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security
MDN — CORShttps://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
MDN — Using server-sent eventshttps://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
MDN — WebSocket APIhttps://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
RFC 9293 — TCPhttps://www.rfc-editor.org/rfc/rfc9293
RFC 1035 — DNShttps://www.rfc-editor.org/rfc/rfc1035
RFC 9499 — DNS terminology (obsoletes 8499)https://www.rfc-editor.org/rfc/rfc9499
RFC 8446 — TLS 1.3https://www.rfc-editor.org/rfc/rfc8446
RFC 9849 — TLS Encrypted Client Hellohttps://www.rfc-editor.org/rfc/rfc9849
RFC 9110 — HTTP semanticshttps://www.rfc-editor.org/rfc/rfc9110
RFC 9113 — HTTP/2https://www.rfc-editor.org/rfc/rfc9113
RFC 9000 — QUIChttps://www.rfc-editor.org/rfc/rfc9000
RFC 9114 — HTTP/3https://www.rfc-editor.org/rfc/rfc9114
RFC 6455 — WebSocket protocolhttps://www.rfc-editor.org/rfc/rfc6455
RFC 9460 — SVCB / HTTPS recordshttps://www.rfc-editor.org/rfc/rfc9460
RFC 8659 — CAAhttps://www.rfc-editor.org/rfc/rfc8659
IANA — Service names and port numbershttps://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
OWASP — SSRF prevention cheat sheethttps://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html
Mozilla SSL Configuration Generatorhttps://ssl-config.mozilla.org/
Vercel — WebSocketshttps://vercel.com/docs/functions/websockets
Vercel — Encryption and TLShttps://vercel.com/docs/cdn-security/encryption
Vercel — Troubleshooting domains (IPv6, CAA)https://vercel.com/docs/domains/troubleshooting
Microsoft — WSL networkinghttps://learn.microsoft.com/en-us/windows/wsl/networking
Cloudflare — Quick Tunnelshttps://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/
ngrok — Free plan limitshttps://ngrok.com/docs/pricing-limits/free-plan-limits
Tailscale — Funnelhttps://tailscale.com/kb/1223/funnel
BIND 9 manpages (dig)https://bind9.readthedocs.io/en/latest/manpages.html
curl manualhttps://curl.se/docs/manpage.html

Setup — the diagnostics toolbox

Install the tools first. Every section below assumes you have them.

Bash
# Debian / Ubuntu / WSL
sudo apt update && sudo apt install -y dnsutils curl iproute2 net-tools traceroute mtr-tiny nmap openssl

# macOS (Homebrew): dig comes from the bind formula; the OpenSSL formula is openssl@3
brew install bind curl nmap openssl@3 mtr
PowerShell
# Windows: nslookup, tracert and netstat ship with the OS.
# The PowerShell equivalents give richer output and are easier to script:
Resolve-DnsName tech-stack.codeamanilabs.org -Type A
Test-NetConnection tech-stack.codeamanilabs.org -Port 443
Get-NetTCPConnection -State Listen | Sort-Object LocalPort

Tool versions checked on 2026-10-20: curl 8.23.0, Homebrew bind 9.20.29, openssl@3 3.5.9, mtr 0.96, cloudflared 2026.10.2, Tailscale 1.104.1, ngrok agent 3.39.11.

Pinned npm versions for the TypeScript examples (all type-checked with tsc --strict):

Bash
npm i undici@8.12.3 ws@8.22.0 @vercel/functions@3.10.1
npm i -D typescript@7.0.2 @types/node@26.6.5 @types/ws@8.18.2

Non-secret settings the examples read. These are not credentials, so they belong in your env config, not the secrets vault:

SettingExample valueUsed by
APP_ORIGINhttps://app.example.comexamples/ws-route.ts Origin check
Outbound host allowlistapi.stripe.com, api.safaricom.co.ke, sandbox.safaricom.co.keexamples/safe-fetch.ts (allowHosts)

Installing nmap is fine. Running it is not automatically fine. See Scanning, authorized only.


IP addressing, CIDR, subnets, NAT, IPv6

An IPv4 address is 32 bits (203.0.113.10). An IPv6 address is 128 bits (2001:db8::1). CIDR notation (RFC 4632) adds a prefix length: the first N bits are the network, and the rest identify hosts inside it.

CIDRNetmaskUsable IPv4 hostsTypical use
/32255.255.255.2551A single host: firewall rules, allowlists
/24255.255.255.0254One small subnet / VPC subnet
/16255.255.0.065,534A VPC
/8255.0.0.016,777,21410.0.0.0/8 private space
/00.0.0.0everythingDefault route; "any source" in a security group

Every IPv4 subnet has two addresses you cannot give to hosts: the all-zeros network address and the all-ones broadcast address. That is why a /24 has 254 usable hosts, not 256. IPv6 has no broadcast, and the standard LAN subnet is a /64.

Ranges that must never be reachable from user input

An SSRF guard denies these ranges. Learn them; they come back in the security section and in examples/safe-fetch.ts.

RangeRFCMeaning
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16RFC 1918Private IPv4
127.0.0.0/8, ::1/128RFC 1122 / 4291Loopback
169.254.0.0/16, fe80::/10RFC 3927 / 4291Link-local. Includes 169.254.169.254, the cloud metadata endpoint
100.64.0.0/10RFC 6598Carrier-grade NAT shared space
fc00::/7RFC 4193IPv6 unique local addresses
64:ff9b::/96RFC 6052NAT64 well-known prefix, which can embed a private IPv4 address
0.0.0.0/8RFC 1122"This network". 0.0.0.0 often reaches localhost

NAT and CGNAT

Network Address Translation lets many private addresses share one public address. The NAT device rewrites the source IP and port and keeps a translation table. Three consequences matter to application code:

  • Inbound connections do not work by default. You cannot dial a device behind NAT. A rider's phone on a mobile network is almost always behind CGNAT, so it has to start the connection itself. That is why webhooks push to your public HTTPS endpoint, and why testing webhooks locally needs a tunnel.
  • The socket's remote address is not the client. Behind NAT and a CDN, req.socket.remoteAddress is the edge server. Read the forwarded header your platform sets, and trust it only because the platform sets it. On Vercel, that is x-forwarded-for / x-real-ip.
  • Rate limiting by IP punishes shared exits. A whole carrier or office can share one public IP. Key rate limits on the user or API key wherever you have an identity.

IPv6: who actually serves it

LayerIPv6?Source
Vercel (custom domains)No. You can create an AAAA record in Vercel DNS, but "we do not support IPv6 yet", so you cannot point an AAAA at Vercelvercel.com/docs/domains/troubleshooting#ipv6-support
Cloudflare (proxied records)Yes, on by default. Only Enterprise can turn it offdevelopers.cloudflare.com/network/ipv6-compatibility
WSL 2Only in mirrored networking modelearn.microsoft.com/windows/wsl/networking

IPv6-only clients still reach IPv4-only origins such as Vercel, because their carrier runs NAT64/DNS64 and translates. That adds a hop you do not control. If dual-stack reachability matters, put Cloudflare in front: the proxied hostname gets an AAAA, and Cloudflare talks IPv4 to Vercel. See the Cloudflare + Vercel note.


Ports and sockets

A socket is the five-tuple {protocol, source IP, source port, destination IP, destination port}. A server binds and listens on a well-known port; a client connects from an ephemeral port. IANA (RFC 6335) splits the port space into three ranges:

  • System: 0–1023
  • User/Registered: 1024–49151
  • Dynamic/ephemeral: 49152–65535, never assigned
PortServiceNote
22SSHKeys only, never password auth. Better: no public 22 at all (Tailscale SSH or Cloudflare Access)
25 / 465 / 587SMTP / SMTPS / submission587 is the modern submission port; many hosts block outbound 25
53DNSUDP first, TCP fallback for large responses (RFC 7766)
80HTTPKeep it open only to redirect to HTTPS and to serve ACME HTTP-01. Vercel answers 308
443HTTPSTCP for HTTP/1.1 and HTTP/2, UDP for HTTP/3/QUIC
853DNS-over-TLSRFC 7858
3000Next.js devLocal only
5432PostgresSupabase / Neon. Never open it to 0.0.0.0/0
6379RedisTreat as internal-only

Two rules prevent most self-inflicted outages:

  1. Bind to 127.0.0.1 for anything that does not need to be public. On a cloud VM, a service bound to 0.0.0.0 is on the internet as soon as the security group allows it.
  2. Open ports are inventory. You cannot defend a listener you did not know existed. Check with ss -tlnp (Linux) or Get-NetTCPConnection -State Listen (Windows).

DNS

DNS turns a name into an address (RFC 1035; terminology in RFC 9499). Four roles are involved, and mixing them up causes most "it works for me" reports.

A record only changes on the authoritative nameserver. Everything between it and the user is a cache. "DNS propagation" is not a push. It is recursive resolvers around the world expiring their cached copy once the record's TTL runs out. That is the whole mechanism, and it leads to the operational rule below.

Record types

TypePoints atNotes
AIPv4 addressApex domains on Vercel use an A record. Copy the value from Settings → Domains; Vercel's KB still cites 76.76.21.21
AAAAIPv6 addressNot usable for Vercel origins (IPv4-only). Cloudflare adds one automatically for proxied names
CNAMEAnother nameCannot share a name with other records, and cannot sit at the zone apex (RFC 1034 §3.6.2). Providers work around this with CNAME flattening / ALIAS / ANAME. Vercel subdomain targets are per-project and end in a dot (absolute)
MXMail exchanger + priorityLower number wins (RFC 5321). Vercel provides no mail service
TXTArbitrary textOwnership proofs, SPF (RFC 7208), DKIM (RFC 6376), DMARC (RFC 9989, May 2026, which obsoletes RFC 7489)
CAAWhich CAs may issue for this nameRFC 8659: issue / issuewild / iodef. CAA lookups follow CNAMEs and climb to parent names
NSDelegation to authoritative serversChanging these at the registrar moves the whole zone (24–48 h)
SOAZone metadataSerial, refresh, negative-cache TTL
SRVService host and portFor protocols that need port discovery
HTTPS / SVCBConnection hints before the first requestRFC 9460: ALPN (h3), IP hints, and the ECH config browsers need to encrypt SNI
PTRReverse: address → nameLives in the IP owner's zone, not yours

Two TXT records everyone gets wrong. SPF must be one TXT record per domain; two v=spf1 records is a permanent error. DMARC lives at _dmarc.example.com, not at the apex.

The TTL rule

Lower the TTL before you change anything.

Bash
# 1. ~24 h before a cutover: drop TTL to 60–300 s on the records you will change,
#    then wait for the OLD TTL to fully elapse.
# 2. Make the change.
# 3. Verify from multiple resolvers.
# 4. Once stable, raise TTL back to 3600+.

You cannot shorten a TTL after the fact. A resolver that cached the old record with an 86400 s TTL will keep it for up to a day, whatever you do next. That is why a rushed DNS cutover becomes a multi-hour outage and a planned one goes unnoticed. Vercel DNS defaults to a 60 s TTL; the allowed range is 30 s to 86400 s.

Diagnosing DNS

Bash
# What does the authoritative server say? (bypasses every cache: the ground truth)
dig +short NS codeamanilabs.org
dig @<authoritative-ns> tech-stack.codeamanilabs.org A

# What does the world see? Query specific public resolvers.
dig @1.1.1.1 tech-stack.codeamanilabs.org A +short
dig @8.8.8.8 tech-stack.codeamanilabs.org A +short

# Full delegation path, root → TLD → authoritative
dig +trace tech-stack.codeamanilabs.org

# Other record types
dig codeamanilabs.org MX +short
dig codeamanilabs.org CAA +short
dig codeamanilabs.org HTTPS +short
dig _dmarc.codeamanilabs.org TXT +short
PowerShell
Resolve-DnsName tech-stack.codeamanilabs.org -Type A -Server 1.1.1.1
Clear-DnsClientCache   # flushes the local stub cache only, not the recursive resolver

If dig @<authoritative-ns> is right but dig @1.1.1.1 is wrong, you are waiting on TTL. Do nothing. If the authoritative answer itself is wrong, fix the record. This one test separates "be patient" from "act", and it is the most useful thing in this guide.


TLS and HTTPS

TLS 1.3 (RFC 8446) authenticates the server, agrees on keys, and encrypts everything that follows. A full handshake takes one round trip before application data. A resumed session can send 0-RTT early data, but that data can be replayed, so never put a non-idempotent request in 0-RTT.

Four fields in ClientHello do most of the work:

  • SNI (RFC 6066) sends the hostname so one IP can serve many certificates. It is sent in cleartext unless ECH (RFC 9849) is in use. With ECH, the real ClientHello is encrypted under a key published in the domain's HTTPS DNS record, and observers see only a shared public name. Vercel enables ECH automatically, and observers see vercel-ech.com.
  • ALPN (RFC 7301) agrees on h2, http/1.1 or h3 inside the handshake. Finding out about HTTP/2 costs no extra round trip.
  • key_share is sent in the first flight, which is why TLS 1.3 needs 1 RTT where TLS 1.2 needed 2. Current browsers (Chrome 131+, Firefox 132+, Safari 26+) offer the post-quantum hybrid X25519MLKEM768, and Vercel and Cloudflare accept it. The hybrid key share is larger, so the first flight is a few hundred bytes bigger. That matters little except on the lossiest links.

Certificates: what validation actually checks

A certificate is trusted only if all of these hold. If any one fails, validation fails hard, and the error message rarely says which check failed.

  1. Chain of trust: leaf → intermediate(s) → a root in the client's trust store. The most common production TLS bug is a server that sends the leaf but leaves out the intermediate. Browsers often cover for it by fetching the intermediate themselves (AIA fetching); curl, Node and mobile SDKs do not. Symptom: "works in Chrome, fails in the app".
  2. Hostname match: the requested name must appear in the certificate's Subject Alternative Name list (RFC 9525). Clients no longer match on the legacy Common Name.
  3. Validity window: notBefore ≤ now ≤ notAfter. Expiry is an outage, so renewal must be automated.
  4. Transparency: modern browsers require Certificate Transparency SCTs.

Certificate lifetimes are collapsing — automate or break

Date (issuance)Max publicly-trusted TLS cert lifetimeSource
until 2026-03-14398 daysCA/B Forum Baseline Requirements
from 2026-03-15200 daysBallot SC-081v3
from 2027-03-15100 daysSC-081v3
from 2029-03-1547 days (domain-validation reuse: 10 days)SC-081v3

Let's Encrypt, which Vercel uses, has its own schedule:

  • 2026-05-13: the opt-in tlsserver profile issues 45-day certificates.
  • 2027-02-10: the default classic profile drops to 64 days, with 10-day authorization reuse.
  • 2028-02-16: classic drops to 45 days, with 7-hour authorization reuse.
  • shortlived (6-day certificates) is also available.

Let's Encrypt recommends ACME Renewal Information (ARI) for timing renewals. Without ARI, renew at about two-thirds of a certificate's lifetime, not on a fixed 60-day timer.

On Vercel, Netlify, Cloudflare and Render this is handled for you. Your part is making sure renewal cannot be blocked:

  • CAA must allow the platform's CA.
  • /.well-known/acme-challenge/* must reach the platform on port 80. Do not put a proxy redirect, auth or cache on that path.
  • Wildcards need DNS-01, so use Vercel nameservers or delegate _acme-challenge.

Monitor for failed renewal, not for "30 days left": examples/cert-check.mts exits non-zero when less than a quarter of a certificate's lifetime remains.

Bash
# Full handshake detail: chain, SANs, protocol, cipher, key-exchange group
openssl s_client -connect tech-stack.codeamanilabs.org:443 \
  -servername tech-stack.codeamanilabs.org -showcerts </dev/null

# Just the dates and names
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName

# Programmatic: chain + SAN + days left, exit 1 on failure (Node >= 23.6 runs .mts directly)
node networking/examples/cert-check.mts tech-stack.codeamanilabs.org

Hardening checklist

  • TLS 1.2 minimum, 1.3 preferred. Vercel serves only TLS 1.2/1.3 with forward-secret AEAD ciphers. If you run your own TLS, generate the config with https://ssl-config.mozilla.org/ instead of hand-writing cipher strings.
  • HSTS. Vercel sends Strict-Transport-Security: max-age=63072000 on custom domains (subdomain-scoped; no includeSubDomains). Add includeSubDomains; preload through custom headers only when you are certain every subdomain is HTTPS, because preload is hard to undo.
  • CAA records. Publish which CAs may issue. For Vercel, that is 0 issue "letsencrypt.org" (plus issuewild if you use wildcards). A Vercel CNAME target brings Vercel's own CAA policy with it.
  • Never disable verification to "fix" a TLS error. Setting NODE_TLS_REJECT_UNAUTHORIZED=0, running curl -k, or passing rejectUnauthorized: false turns a certificate bug into a permanent MITM hole. Fix the chain instead.

HTTP/1.1, HTTP/2, HTTP/3

HTTP/1.1HTTP/2 (RFC 9113)HTTP/3 (RFC 9114)
TransportTCPTCPQUIC over UDP (RFC 9000)
FramingTextBinary framesBinary frames on QUIC streams
ConcurrencyOne request in flight per connection; browsers open ~6 per originMultiplexed streams on one connectionMultiplexed, independent streams
Head-of-line blockingAt the request levelGone at the HTTP level, still there at the TCP level: one lost segment stalls every streamGone: a lost packet stalls only its own stream
Header compressionNoneHPACKQPACK
HandshakeTCP + TLS separatelyTCP + TLS separatelyTLS 1.3 built into the QUIC handshake
Connection migrationNoNoYes: the connection ID survives an IP change
DiscoverydefaultALPN h2Alt-Svc: h3=":443" header, or a DNS HTTPS record

A client cannot negotiate HTTP/3 in-band on its first connection the way it can h2, because HTTP/3 uses a different transport. It learns about HTTP/3 from an Alt-Svc response header (RFC 7838) or from an HTTPS/SVCB DNS record (RFC 9460) that advertises alpn=h3.

Who serves h3 for codeAmani today:

  • Cloudflare: available on all plans via the HTTP/3 toggle. www.cloudflare.com returns alt-svc: h3=":443"; ma=86400.
  • Vercel: not documented, and no Alt-Svc on vercel.com or tech-stack.codeamanilabs.org (checked 2026-10-20).

If HTTP/3 matters, for example for Kenya-targeted traffic, put Cloudflare in front.

Bash
# Which protocol did you actually get?
curl -sI --http2 https://example.com -o /dev/null -w "%{http_version}\n"
curl -sI --http3-only https://example.com -o /dev/null -w "%{http_version}\n"   # needs an HTTP/3-capable curl

# Is HTTP/3 advertised?
curl -sI https://example.com | grep -i alt-svc
dig example.com HTTPS +short

# Timing breakdown: where the milliseconds go
curl -s -o /dev/null -w "dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" https://example.com

That last command is the most useful one-liner in this document. In one request it tells you whether a "slow site" complaint is a DNS problem, a TCP round-trip problem, a TLS problem, or an origin problem.


Long-lived connections: WebSockets and SSE

Server-Sent EventsWebSocket (RFC 6455)
DirectionServer → client onlyBidirectional
WirePlain HTTP response, Content-Type: text/event-streamHTTP GET + Upgrade: websocket, then framed TCP
ReconnectBuilt in. EventSource reconnects and resends the last id: as Last-Event-ID; retry: sets the delayYou write it: backoff, resubscribe, reload state
Proxies / middleboxesPass through like any HTTP response (send Cache-Control: no-transform)Some corporate proxies break the upgrade
Browser limit6 per browser + domain over HTTP/1.1; negotiated (default 100) over HTTP/2No per-domain cap of note
CORSApplies (EventSource with withCredentials)Does not apply. Check Origin yourself
FitToken streaming (AI), live feeds, order statusChat, collaboration, games, presence

Pick SSE unless you genuinely need client → server messages on the same channel. For codeAmani's main realtime cases (streaming Claude output, M-Pesa payment status, dispatch updates), the client's messages can go over ordinary POSTs. On a flaky mobile link, SSE's built-in resume is worth more than a bidirectional channel. See examples/sse-route.ts.

WebSockets on Vercel Functions (public beta)

Vercel announced WebSocket support for Functions on 2026-06-22 as a public beta on all plans. Python support followed on 2026-07-23. The rules, from https://vercel.com/docs/functions/websockets:

  • Requires Fluid compute. It is the default for projects created on or after 2025-04-23.
  • Next.js has no upgrade API. Use upgradeWebSocket() from @vercel/functions ≥ 3.10.0, with ws (≥ 8) as a peer dependency. See examples/ws-route.ts. Standalone Node servers (Express, Hono, h3), Nitro/Nuxt, Bun's Bun.serve() and Python ASGI/WSGI also work.
  • The upgrade request is a normal request. Routing Middleware, rewrites, Firewall rules and rate limits all apply to it. Authenticate here, before upgrading.
  • Each connection is pinned to one function instance. One instance can serve many connections. A reconnect may land on a different instance, or on the new deployment after a deploy, so keep rooms, presence and counters in an external store (Redis from the Marketplace), never in memory.
  • The socket closes at the function's maximum duration. The client must reconnect with backoff.
  • Billing follows the normal Function model. Under Active CPU pricing you pay for message processing, not idle connection time, plus Fast Data Transfer / Fast Origin Transfer.
  • Connect to wss:// directly. Vercel redirects HTTP to HTTPS with a 308, and the WebSocket handshake does not follow redirects.

The Edge runtime is on its way out

Vercel's docs now say: "We recommend migrating from edge to Node.js for improved performance and reliability. Both runtimes run on Fluid compute with Active CPU pricing", and "Starting in Next.js 16.3, setting runtime = 'edge' is no longer supported." (Current Next.js: 16.4.2.)

For networking code, that means you can use node:net, node:tls, node:dns and undici dispatchers in route handlers. Those are exactly what safe-fetch.ts and cert-check.mts need, and the Edge runtime never offered them. Remove export const runtime = 'edge' when you touch a route.


CORS

CORS is a browser rule. It decides whether page JavaScript may read a cross-origin response. It is not server-side access control: curl ignores it completely, so never rely on it in place of authentication.

  • Simple requests (GET/HEAD/POST, only safelisted headers, Content-Type limited to application/x-www-form-urlencoded, multipart/form-data or text/plain) go straight out. Anything else is preflighted with an OPTIONS request. A JSON POST is preflighted.
  • Credentials and * don't mix. With cookies or Authorization, Access-Control-Allow-Origin (and -Headers, -Methods, -Expose-Headers) must name an explicit origin. A * makes the browser block the response.
  • Reflecting an allowlisted origin means you must also send Vary: Origin, or a CDN will cache one origin's answer for everybody.
  • Access-Control-Max-Age defaults to 5 s, and each browser caps it at an internal maximum. Set it, but don't expect long caching.
  • WebSockets are not covered by CORS. Check the Origin header in the upgrade handler (cross-site WebSocket hijacking).
TypeScript
// Minimal allowlist CORS for a Next.js route handler (Node.js runtime).
const ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);

export function corsHeaders(origin: string | null): Record<string, string> {
  if (!origin || !ALLOWED.has(origin)) return { Vary: "Origin" };
  return {
    "Access-Control-Allow-Origin": origin,
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Max-Age": "600",
    Vary: "Origin",
  };
}

export async function OPTIONS(request: Request): Promise<Response> {
  return new Response(null, { status: 204, headers: corsHeaders(request.headers.get("origin")) });
}

CDNs and the edge

A CDN terminates TLS at a point of presence (PoP) close to the user, serves cacheable responses from there, and keeps warm connections open back to the origin. The win is not only bytes; it is round trips. On a 3G link with 200–400 ms RTT, moving the TLS handshake from a US origin to a nearby PoP saves more wall-clock time than any payload optimisation.

Bash
curl -sI https://tech-stack.codeamanilabs.org | grep -Ei "cf-ray|cf-cache-status|x-vercel-cache|x-vercel-id|age|cache-control"
HeaderMeaning
x-vercel-cache: HIT / MISS / STALEVercel CDN cache outcome
x-vercel-id: iad1::…Vercel region(s) that handled the request
cf-cache-status: HIT / MISS / DYNAMIC / BYPASSCloudflare cache outcome
cf-ray: …-NBOCloudflare ray ID; the suffix is the PoP's IATA code (NBO = Nairobi)
ageSeconds the response has been in cache

When a name is proxied through Cloudflare (orange cloud), dig returns Cloudflare's anycast address, not your origin. That is expected, not a misconfiguration. Vercel's apex IPs are anycast too. See cloudflare for SSL modes. Use Full (strict) so the Cloudflare ↔ origin hop is also verified.


Local tunnels: ngrok, Cloudflare Tunnel, Tailscale

M-Pesa (Daraja) and Stripe call your HTTPS URL. A laptop behind NAT has no such URL, so a tunnel opens an outbound connection to a relay and accepts traffic back through it.

ngrok (agent 3.39.x)Cloudflare Quick TunnelCloudflare named TunnelTailscale Funnel
Commandngrok http 3000cloudflared tunnel --url http://localhost:3000cloudflared tunnel run <name>tailscale funnel --bg 3000
URLFree: one assigned dev domain (*.ngrok-free.app); custom domains are paidRandom *.trycloudflare.com, new every runYour own hostname on a Cloudflare zone<machine>.<tailnet>.ts.net
AccountRequired (authtoken)NoneCloudflare account + zoneTailscale account; MagicDNS + HTTPS + funnel node attribute
LimitsFree: 3 endpoints, 1 GB/month out, 20,000 HTTP requests/month (4,000/min), 5,000 TCP conns/month200 in-flight requests (then 429), no SSE, no uptime guaranteeProduction-gradePorts 443/8443/10000 only, TLS only, non-configurable bandwidth limits
Browser interstitialYes on free. Skip with the ngrok-skip-browser-warning header (any value) or a non-browser User-Agent; API callers are unaffectedNoNoNo
Best forDaraja/Stripe webhook dev, request inspector at http://127.0.0.1:4040Throwaway demo of a pageStaging hooks, internal tools on your domainSharing from a box already on your tailnet
Bash
# ngrok: one-time auth, then expose port 3000
ngrok config add-authtoken <your-ngrok-authtoken>
ngrok http 3000
# Pin to your free dev domain so the Daraja CallBackURL doesn't change every run
ngrok http 3000 --url https://<your-assigned-name>.ngrok-free.app

# Cloudflare named tunnel (locally managed)
cloudflared tunnel login
cloudflared tunnel create codeamani-dev
cloudflared tunnel route dns codeamani-dev hooks-dev.example.com
cloudflared tunnel run codeamani-dev

# Tailscale: private to your tailnet (Serve) vs public (Funnel)
tailscale serve --bg 3000      # tailnet only
tailscale funnel --bg 3000     # public internet
tailscale funnel status
tailscale funnel reset

Tunnel rules:

  • A tunnel URL is a public endpoint. Anyone who learns it can hit your dev server. Verify webhook signatures locally exactly as you do in production, and stop the tunnel when you are done.
  • Never point a production webhook at a tunnel. Register the deployed URL.
  • Cloudflare Quick Tunnels do not support SSE. Use ngrok or a named tunnel for streaming routes.
  • Daraja's callback URL must be HTTPS and publicly reachable. All four tools give you that.

Firewalls

Default-deny inbound. Allow only what a service needs, from only where it needs it.

WhereToolRule of thumb
Cloud VMProvider security group / firewallInbound 443 (+80 for redirect/ACME) from anywhere; 22 from nowhere (use Tailscale SSH or Cloudflare Access); DB ports from the app subnet only
Linux hostufw / nftablesufw default deny incoming && ufw allow 443/tcp && ufw enable. Docker-published ports bypass ufw because Docker writes its own iptables rules, so bind containers to 127.0.0.1:
VercelVercel Firewall (WAF, rate limits, IP blocks)Rules also apply to WebSocket upgrade requests
CloudflareWAF / rate limiting / AccessPut admin surfaces behind Access instead of an "unguessable" path
Windows / WSLWindows Defender Firewall + Hyper-V firewallWSL 2.0.9+ on Windows 11 22H2+ filters WSL traffic through the Hyper-V firewall by default
Managed PostgresSupabase / Neon network restrictionsAllowlist egress IPs; TLS required

WSL networking (Windows dev boxes)

WSL 2 runs in a lightweight VM. The networking mode decides how Windows, Linux and your LAN see each other.

NAT (default)Mirrored (recommended)
Enabledefault.wslconfig → [wsl2] networkingMode=mirrored, then wsl --shutdown
Requires—Windows 11 22H2+
Windows → Linux serverlocalhost works (localhostForwarding=true)localhost works
Linux → Windows serverUse the host IP: ip route show | grep -i default | awk '{ print $3}'127.0.0.1 works (::1 does not)
IPv6 inside LinuxNoYes
VPN compatibilityOften brokenImproved
LAN → WSL (phone testing)netsh interface portproxy to the VM IP, which changes on restartDirect, once a Hyper-V firewall rule allows it

Related .wslconfig keys (all [wsl2], Windows 11 22H2+):

  • dnsTunneling (default true): answers DNS through Windows. Fixes most VPN DNS breakage.
  • firewall (default true): Windows and Hyper-V firewall rules filter WSL traffic.
  • autoProxy (default true): inherits the Windows HTTP proxy.

Mirrored-only extras go under [experimental]: ignoredPorts and hostAddressLoopback. A ready file is in reference/wslconfig-mirrored.ini. Other networkingMode values: none, nat, bridged (deprecated since WSL 2.4.5), consomme (formerly virtioproxy; NAT falls back to it since WSL 2.3.25).

To let a phone on the same Wi-Fi load next dev running in mirrored-mode WSL, run next dev -H 0.0.0.0 and add a scoped Hyper-V firewall rule from an admin PowerShell:

PowerShell
New-NetFirewallHyperVRule -Name "NextDev" -DisplayName "Next dev 3000" -Direction Inbound `
  -VMCreatorId '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -Protocol TCP -LocalPorts 3000
# Remove it afterwards
Remove-NetFirewallHyperVRule -Name "NextDev"

Prefer a port-scoped rule over Microsoft's blanket Set-NetFirewallHyperVVMSetting … -DefaultInboundAction Allow. The blanket setting opens every WSL port to the LAN.


Diagnostics: which layer is lying?

Work bottom-up. Each command clears one layer, so the first failure tells you where the fault is.

Bash
# L3: is the host routable at all?
ping -c 4 1.1.1.1                  # raw IP: no DNS involved
traceroute -n example.com          # hop-by-hop path; * * * means filtered ICMP, not always a fault
mtr -rw example.com                # traceroute + loss stats over time (best for flaky links)

# L4: is the port open?
nc -vz example.com 443
# PowerShell: Test-NetConnection example.com -Port 443

# What is listening locally, and which process owns it?
ss -tlnp
ss -tunap | grep :5432

# L7: the full story of one request
curl -v https://example.com
curl -sSL -o /dev/null -w "%{http_code} %{num_redirects} %{url_effective}\n" http://example.com
SymptomMost likely layerNext command
Could not resolve hostDNSdig @1.1.1.1 <name> then dig @<authoritative-ns> <name>
Connection refusedTransport: nothing listeningss -tlnp on the host
Connection timed outFirewall / security group silently droppingtraceroute, then check the security group
certificate verify failed / UNABLE_TO_VERIFY_LEAF_SIGNATURETLS chainopenssl s_client -showcerts
ERR_TLS_CERT_ALTNAME_INVALIDHostname not in SANAdd the hostname to the platform's domain list
Works in browser, fails in curl/appMissing intermediate certificateServe the full chain
Right in dig @ns, wrong for usersDNS TTL still counting downWait; do not re-edit the record
WebSocket closes after a few minutes on VercelFunction max duration reachedExpected; reconnect with backoff
SSE works locally, never streams through a tunnelCloudflare Quick Tunnel (no SSE) or a buffering proxyUse ngrok/named tunnel; send Cache-Control: no-transform
Fast locally, slow in productionRTT / cache misscurl -w timing breakdown

Scanning, authorized only

nmap is a legitimate inventory tool for systems you own or have explicit written permission to test. Unauthorized port scanning is unlawful in many jurisdictions and breaks most providers' terms of service. Read https://nmap.org/book/legal-issues.html before pointing it anywhere.

Bash
# Legitimate use: audit YOUR OWN host's exposed surface from outside it.
nmap -Pn -p 1-1024 <your-own-host>
nmap --script ssl-enum-ciphers -p 443 <your-own-host>

Use the alternatives when you can. ss -tlnp on the box itself is faster and more accurate, and needs no permission conversation. Your cloud provider's security-group list is the authoritative answer to "what is exposed".


Network-layer risks and their mitigations

These are defensive measures only: each row is a risk you close on your own infrastructure.

RiskWhy it happensMitigation
Open ports / exposed servicesService bound to 0.0.0.0; a 0.0.0.0/0 rule left over from debugging; Docker bypassing ufwBind internal services to 127.0.0.1; default-deny inbound; audit with ss -tlnp; put admin surfaces behind Tailscale or Cloudflare Access
Weak / misconfigured TLSLegacy versions enabled; missing intermediate; renewal blockedTLS 1.2 minimum; serve the full chain; keep CAA and the ACME path clear; alert on failed renewal (cert-check.mts)
DNS hijacking (registrar/zone takeover)Registrar account compromise, or a stale CNAME to a deprovisioned host that an attacker re-claims2FA + registrar lock (porkbun); publish CAA; delete DNS records when you tear down what they point at
DNS spoofing / cache poisoningPlaintext UDP:53 answers are forgeable on hostile networksDNSSEC (RFC 4033) on your zone; DoH (RFC 8484) / DoT (RFC 7858) on clients you control
SSRF: server fetches an attacker-chosen URLAny endpoint that takes a URL: webhook-target config, image import, link unfurling, "test my callback"Host allowlist; validate the resolved IP inside the connection's own lookup; refuse redirects; https only. OWASP Top 10:2025 files this under A01 Broken Access Control. Detail below
Cross-site WebSocket hijackingCORS does not protect WebSockets; cookies ride along on the upgradeCheck Origin and authenticate the upgrade request
MITM on hostile networksPublic Wi-Fi, transparent proxies, captive portalsHTTPS everywhere + HSTS; never disable certificate verification
Credentials on the wirePostgres/Redis exposed publicly; API keys in query strings (they land in every access log)TLS on DB connections (sslmode=require or stricter); keys in Authorization headers, never in URLs
Forgotten tunnelsA dev tunnel left running exposes an unauthenticated local serverStop tunnels after use; verify webhook signatures even in dev
Amplification / volumetric abuseUnauthenticated endpoints that do real workRate limit at the edge (Vercel Firewall / Cloudflare); keep expensive routes behind auth

SSRF: the pattern that matters for webhook and callback endpoints

The dangerous shape is outbound traffic to a URL that a user supplied. From inside a cloud network, http://169.254.169.254/ and http://10.x.x.x/ are reachable and often unauthenticated. A naïve fetch(userUrl) hands an attacker your internal network.

The previous version of this guide resolved the hostname, checked the IP, then called fetch. That leaves a DNS-rebinding gap: the resolver can answer with a public IP for your check and a private one for the connection. examples/safe-fetch.ts closes the gap. It gives an undici Agent a custom connect.lookup, so the address that gets checked is the address that gets dialled:

TypeScript
// Excerpt from networking/examples/safe-fetch.ts (undici@8.12.3)
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
import { BlockList, isIP, type LookupFunction } from "node:net";
import { Agent, fetch } from "undici";

const DENY = new BlockList();
DENY.addSubnet("10.0.0.0", 8, "ipv4");
DENY.addSubnet("169.254.0.0", 16, "ipv4"); // cloud metadata
// ...the rest of the ranges table...
// Do NOT add ::ffff:0:0/96: BlockList already matches IPv4-mapped IPv6 against
// the IPv4 rules, and that rule would match every plain IPv4 address too.

const guardedLookup: LookupFunction = (hostname, options, callback) => {
  dnsLookup(hostname, { ...options, all: true }, (err, addresses: LookupAddress[]) => {
    if (err) return callback(err, "", 0);
    if (addresses.some((a) => DENY.check(a.address, isIP(a.address) === 6 ? "ipv6" : "ipv4"))) {
      return callback(new Error(`refusing to connect to ${hostname}`), "", 0);
    }
    if (options.all) return callback(null, addresses);
    return callback(null, addresses[0]!.address, addresses[0]!.family);
  });
};

const agent = new Agent({ connect: { lookup: guardedLookup, timeout: 5_000 } });

export async function safeFetch(rawUrl: string) {
  const url = new URL(rawUrl);
  if (url.protocol !== "https:") throw new Error("only https");
  const res = await fetch(url, { dispatcher: agent, redirect: "manual" });
  if (res.status >= 300 && res.status < 400) throw new Error("redirect refused");
  return res;
}

The full file also enforces:

  • a host allowlist;
  • no credentials in the URL and no non-default ports;
  • a check on literal-IP hosts (these skip lookup);
  • timeouts and a response-size cap.

Tested 2026-10-20: 169.254.169.254, localtest.me (resolves to 127.0.0.1), http: URLs and a 302 redirect are all refused, and https://example.com returns 200.

Application checks are defence in depth. The durable control is network egress policy: the request-handling process should be unable to reach internal ranges whatever the code does. Inbound webhooks are the mirror-image problem, handled by signature verification rather than URL validation; see webhooks and security.


codeAmani notes

The deploy path: Porkbun → Cloudflare → Vercel

This is the sequence that wires up a codeAmani property, and the order matters.

  1. Registrar. The name lives at Porkbun, and the porkbun-dns skill edits records programmatically. Registrar lock + 2FA on that account is the root of trust for the whole domain: whoever controls it controls your DNS, and therefore your certificates.
  2. DNS. Use either Porkbun's nameservers or Cloudflare's.
    • Apex → A record with the value from Vercel Settings → Domains (the KB still cites 76.76.21.21).
    • Subdomain → CNAME to the per-project Vercel target. Copy it exactly, including the trailing dot.
    • No AAAA to Vercel. Vercel is IPv4-only.
  3. TLS. Vercel issues and renews certificates automatically through Let's Encrypt (HTTP-01; DNS-01 for wildcards). If you publish CAA, include 0 issue "letsencrypt.org". Keep /.well-known/acme-challenge/* reaching Vercel on port 80 with no proxy redirect or cache, or renewal will fail as lifetimes shrink.
  4. Verify before declaring done. dig @<authoritative-ns> for truth, dig @1.1.1.1 for reach, and node networking/examples/cert-check.mts <host> for the chain. A green dashboard and a wrong CAA record look the same until the first renewal.

If you proxy through Cloudflare in front of Vercel:

  • Set SSL mode to Full (strict).
  • Make sure the ACME challenge path is not cached or redirected (Vercel's reverse-proxy requirements).
  • Proxying also gives you HTTP/3 (toggle on) and IPv6, which Vercel alone does not serve.

Realtime on Vercel

  • Default to SSE from a Node.js route handler for streaming AI output and payment/dispatch status (examples/sse-route.ts).
  • Use WebSockets on Vercel Functions (beta) only for genuinely bidirectional features. State goes in Redis/Postgres, never in instance memory, and clients reconnect with backoff (examples/ws-route.ts). It is a beta, so keep a fallback (SSE + POST) for anything payment-critical.
  • Drop runtime = 'edge' wherever you touch a route. Next.js 16.3+ ignores it, and Vercel recommends Node.js on Fluid compute.

Security

  • Secrets stay server-side. Tunnel authtokens, API keys and resolver config live in .env.local, Vercel env vars or Hazina, never in NEXT_PUBLIC_*. The SSRF host allowlist and APP_ORIGIN are configuration, not secrets.
  • The M-Pesa and Stripe endpoints show both problems at once.
    • Inbound, they are unauthenticated public HTTPS endpoints. They must verify a signature before doing any work (Stripe signing secret; Daraja callback validation) and must be idempotent on retry.
    • Outbound, any admin screen that lets someone type a callback or webhook URL is an SSRF sink. Run those URLs through safeFetch.
    • Daraja requires an HTTPS callback, so local testing goes through ngrok or a named Cloudflare tunnel.
  • Never widen the database to debug. Supabase and Neon connections are TLS-enforced and IP-scoped for a reason. A temporary 0.0.0.0/0 rule outlives the debugging session that created it.
  • Delete DNS records when you delete what they point to. A CNAME left pointing at a torn-down preview host is a subdomain takeover waiting for someone to claim the name.

Kenya-targeted projects: the bandwidth angle

On 2G/3G links, latency and packet loss decide whether an app feels usable, not throughput. Round trips are the budget.

  • HTTP/3 helps here, but you only get it through Cloudflare.
    • QUIC removes TCP-level head-of-line blocking, so one lost packet stalls one stream instead of every response.
    • Connection migration keeps a rider's connection alive across a tower or Wi-Fi → data handover.
    • Vercel does not advertise h3, so proxy Kenya-facing hostnames through Cloudflare with HTTP/3 on, and confirm with curl -sI … | grep -i alt-svc.
  • Reuse connections; avoid extra origins. Every new origin costs a fresh DNS lookup, TCP handshake and TLS handshake, which is about three round trips before the first byte. At 300 ms RTT that is roughly 1 s per extra domain. Self-host fonts and scripts, and preconnect only the origins you cannot remove.
  • Prefer SSE plus POST over WebSockets for mobile realtime. EventSource resumes on its own after a drop by sending Last-Event-ID. A WebSocket needs hand-written reconnect logic, and half-open TCP connections on mobile radio need heartbeats (see ws-route.ts).
  • Mobile clients are behind CGNAT. They cannot receive inbound connections, and many share one public IP. Push to them with webhooks or SSE, and never rate-limit East African mobile traffic by raw IP.
  • Do not assume an end-to-end IPv6 path. Vercel is IPv4-only, so IPv6-only handsets reach it through their carrier's NAT64. Cloudflare in front gives a native AAAA.
  • Cache aggressively at the edge. A Cloudflare PoP in Nairobi (cf-ray suffix NBO) plus long Cache-Control on hashed static assets means they cross the ocean once. Cloudflare R2 has no egress fees (cloudflare).
  • Measure from the user's side. Run the curl -w timing probe through a throttled profile; see PATTERNS.md.

Troubleshooting

IssueFix
Record changed but users still see the old valueTTL has not expired. Confirm with dig @<authoritative-ns>, then wait; re-editing changes nothing
CNAME rejected at the apexNot allowed in DNS. Use an A record, or the provider's ALIAS/ANAME/flattening
Want AAAA for a Vercel domainNot supported by Vercel. Proxy through Cloudflare for IPv6
Certificate issuance/renewal failsCheck dig <domain> CAA +noall +answer (and parents); check that /.well-known/acme-challenge/ reaches Vercel on :80 without redirects; for wildcards, check _acme-challenge delegation
curl says certificate verify failed, browser is fineServer omits the intermediate. Serve the full chain
ERR_SSL_PROTOCOL_ERROR on a proxied domainCloudflare SSL mode vs origin mismatch; use Full (strict). On one network only: TLS inspection or a filter on that network
Webhook works in production, never fires locallyDev box is behind NAT. Tunnel it (ngrok http 3000) and register the HTTPS URL
ngrok URL returns an HTML warning page to a webhook testFree-plan interstitial. Send ngrok-skip-browser-warning: 1 (real API callers aren't affected)
SSE stream never arrives through trycloudflare.comQuick Tunnels don't support SSE. Use ngrok or a named tunnel
WebSocket handshake fails on ws:// / http://Vercel 308-redirects to HTTPS and WebSockets don't follow redirects. Use wss://
WebSocket state lost after reconnect/deployConnections pin to one instance; reconnects may land elsewhere. Move state to Redis
runtime = 'edge' route suddenly runs on NodeExpected on Next.js ≥ 16.3. Remove the export
CORS error only when logged inAccess-Control-Allow-Origin: * with credentials. Reflect the allowlisted origin and add Vary: Origin
WSL can't reach a Windows service on localhostNAT mode. Switch to networkingMode=mirrored, or use the host IP from ip route
Phone on Wi-Fi can't reach next dev in WSLBind -H 0.0.0.0, use mirrored mode, and add a port-scoped New-NetFirewallHyperVRule
.wslconfig edit has no effectwsl --shutdown, or wait ~8 s after closing every distro shell
traceroute shows * * * for the last hopsICMP filtered; normal for cloud hosts. Test the port with nc -vz instead
Two v=spf1 TXT records on one domainPermanent SPF error. Merge into one
ss shows nothing but the service "is running"It bound to 127.0.0.1 inside a container's namespace. Check the bind address and Docker's publish flags