Networking Integration Guide
Technology: networking · Category: tooling · Last reviewed: 2026-10-20
Source: https://tech-stack.codeamanilabs.org/guide/networking
Insight:
Networking is the layer every codeAmani deploy silently depends on and nobody owns: a name resolves, a socket opens, a certificate validates, bytes move. Almost all of it is someone else's infrastructure (DNS caches you cannot flush, CAs you do not run, middleboxes you cannot see), so the practical skill is diagnosis, not construction. In 2026 the defaults moved under us. Certificates now live 200 days at most and are heading to 47. Vercel serves WebSockets from Node.js Functions and is retiring the Edge runtime. Vercel is still IPv4-only and does not advertise HTTP/3, so the "HTTP/3 everywhere" assumption only holds behind Cloudflare. Get DNS and TLS right and the Porkbun → Cloudflare → Vercel path is boring; get them wrong and every other layer reports a lie.
███╗ ██╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗██╗███╗ ██╗ ██████╗
████╗ ██║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝██║████╗ ██║██╔════╝
██╔██╗ ██║█████╗ ██║ ██║ █╗ ██║██║ ██║██████╔╝█████╔╝ ██║██╔██╗ ██║██║ ███╗
██║╚██╗██║██╔══╝ ██║ ██║███╗██║██║ ██║██╔══██╗██╔═██╗ ██║██║╚██╗██║██║ ██║
██║ ╚████║███████╗ ██║ ╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗██║██║ ╚████║╚██████╔╝
╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝
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
curlrejects 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 layer | OSI layers | What lives here | What breaks |
|---|---|---|---|
| Link | 1–2 Physical, Data Link | Ethernet, Wi-Fi, MAC addresses, ARP / NDP | Cable/radio, MTU, local LAN only |
| Internet | 3 Network | IPv4/IPv6, ICMP, routing, NAT | Wrong route, firewall drop, no IPv6 path |
| Transport | 4 Transport | TCP (ordered, reliable), UDP (datagrams; QUIC runs on it) | Port closed, RST, SYN timeout |
| Application | 5–7 Session, Presentation, Application | DNS, TLS, HTTP/1.1, HTTP/2, HTTP/3, WebSocket | Bad record, expired cert, 4xx/5xx |
flowchart LR
A["Browser<br/>https://app.example.com"] --> B["DNS resolve<br/>A / AAAA / CNAME / HTTPS"]
B --> C["TCP :443<br/>or QUIC over UDP :443"]
C --> D["TLS 1.3 handshake<br/>SNI (or ECH) · ALPN · cert chain"]
D --> E{"ALPN negotiated"}
E -->|"h2"| F["HTTP/2<br/>multiplexed over one TCP conn"]
E -->|"h3"| G["HTTP/3<br/>multiplexed over QUIC streams"]
E -->|"http/1.1"| H["HTTP/1.1<br/>one request in flight per conn"]
F --> I["CDN / edge PoP"]
G --> I
H --> I
I -->|"cache HIT"| J["Response from edge"]
I -->|"cache MISS"| K["Origin<br/>Vercel Function (Node.js) · Supabase · Neon"]
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)
| Area | Was | Now |
|---|---|---|
| Vercel IPv6 | Guide said Vercel publishes AAAA for you |
Wrong. Vercel docs: "we do not support IPv6 yet". You cannot point an AAAA record at Vercel |
| Vercel HTTP/3 | Guide 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 realtime | No WebSockets on Functions; use a third-party service | WebSockets on Vercel Functions, public beta (2026-06-22). Requires Fluid compute. Next.js uses upgradeWebSocket() from @vercel/functions ≥ 3.10.0 |
| Vercel Edge runtime | A normal option | Vercel 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 lifetimes | 398 days max | CA/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 privacy | SNI is always cleartext | ECH 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 exchange | Classical ECDHE | Post-quantum hybrid X25519MLKEM768 is offered by Vercel and Cloudflare and negotiated by current Chrome, Firefox and Safari |
| Standards | RFC 8499 (DNS terms), RFC 7489 (DMARC), OWASP A10:2021 SSRF | RFC 9499 obsoletes 8499. RFC 9989 (May 2026, Standards Track) obsoletes 7489. OWASP Top 10:2025 folds SSRF into A01 Broken Access Control |
| WSL | Not covered | Mirrored networking mode (networkingMode=mirrored, Windows 11 22H2+) |
| Tunnels | One line about ngrok | ngrok, Cloudflare Tunnel and Tailscale Serve/Funnel compared, with free-tier limits |
Official Documentation
Setup — the diagnostics toolbox
Install the tools first. Every section below assumes you have them.
# 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
# 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):
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:
| Setting | Example value | Used by |
|---|---|---|
APP_ORIGIN |
https://app.example.com |
examples/ws-route.ts Origin check |
| Outbound host allowlist | api.stripe.com, api.safaricom.co.ke, sandbox.safaricom.co.ke |
examples/safe-fetch.ts (allowHosts) |
Installing
nmapis 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.
| CIDR | Netmask | Usable IPv4 hosts | Typical use |
|---|---|---|---|
/32 |
255.255.255.255 | 1 | A single host: firewall rules, allowlists |
/24 |
255.255.255.0 | 254 | One small subnet / VPC subnet |
/16 |
255.255.0.0 | 65,534 | A VPC |
/8 |
255.0.0.0 | 16,777,214 | 10.0.0.0/8 private space |
/0 |
0.0.0.0 | everything | Default 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.
| Range | RFC | Meaning |
|---|---|---|
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 |
RFC 1918 | Private IPv4 |
127.0.0.0/8, ::1/128 |
RFC 1122 / 4291 | Loopback |
169.254.0.0/16, fe80::/10 |
RFC 3927 / 4291 | Link-local. Includes 169.254.169.254, the cloud metadata endpoint |
100.64.0.0/10 |
RFC 6598 | Carrier-grade NAT shared space |
fc00::/7 |
RFC 4193 | IPv6 unique local addresses |
64:ff9b::/96 |
RFC 6052 | NAT64 well-known prefix, which can embed a private IPv4 address |
0.0.0.0/8 |
RFC 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.remoteAddressis the edge server. Read the forwarded header your platform sets, and trust it only because the platform sets it. On Vercel, that isx-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
| Layer | IPv6? | 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 Vercel |
vercel.com/docs/domains/troubleshooting#ipv6-support |
| Cloudflare (proxied records) | Yes, on by default. Only Enterprise can turn it off | developers.cloudflare.com/network/ipv6-compatibility |
| WSL 2 | Only in mirrored networking mode | learn.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
| Port | Service | Note |
|---|---|---|
| 22 | SSH | Keys only, never password auth. Better: no public 22 at all (Tailscale SSH or Cloudflare Access) |
| 25 / 465 / 587 | SMTP / SMTPS / submission | 587 is the modern submission port; many hosts block outbound 25 |
| 53 | DNS | UDP first, TCP fallback for large responses (RFC 7766) |
| 80 | HTTP | Keep it open only to redirect to HTTPS and to serve ACME HTTP-01. Vercel answers 308 |
| 443 | HTTPS | TCP for HTTP/1.1 and HTTP/2, UDP for HTTP/3/QUIC |
| 853 | DNS-over-TLS | RFC 7858 |
| 3000 | Next.js dev | Local only |
| 5432 | Postgres | Supabase / Neon. Never open it to 0.0.0.0/0 |
| 6379 | Redis | Treat as internal-only |
Two rules prevent most self-inflicted outages:
- Bind to
127.0.0.1for anything that does not need to be public. On a cloud VM, a service bound to0.0.0.0is on the internet as soon as the security group allows it. - Open ports are inventory. You cannot defend a listener you did not know existed. Check with
ss -tlnp(Linux) orGet-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.
flowchart TD
A["Application<br/>getaddrinfo / fetch"] --> B["Stub resolver<br/>OS cache"]
B --> C["Recursive resolver<br/>ISP · 1.1.1.1 · 8.8.8.8<br/>owns the TTL cache"]
C -->|"cache miss"| D["Root servers<br/>. → 'ask .org'"]
D --> E["TLD servers<br/>.org → 'ask the zone's NS'"]
E --> F["Authoritative NS<br/>your zone: the only source of truth"]
F -->|"answer + TTL"| C
C -->|"cached answer"| B
B --> A
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
| Type | Points at | Notes |
|---|---|---|
A |
IPv4 address | Apex domains on Vercel use an A record. Copy the value from Settings → Domains; Vercel's KB still cites 76.76.21.21 |
AAAA |
IPv6 address | Not usable for Vercel origins (IPv4-only). Cloudflare adds one automatically for proxied names |
CNAME |
Another name | Cannot 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) |
MX |
Mail exchanger + priority | Lower number wins (RFC 5321). Vercel provides no mail service |
TXT |
Arbitrary text | Ownership proofs, SPF (RFC 7208), DKIM (RFC 6376), DMARC (RFC 9989, May 2026, which obsoletes RFC 7489) |
CAA |
Which CAs may issue for this name | RFC 8659: issue / issuewild / iodef. CAA lookups follow CNAMEs and climb to parent names |
NS |
Delegation to authoritative servers | Changing these at the registrar moves the whole zone (24–48 h) |
SOA |
Zone metadata | Serial, refresh, negative-cache TTL |
SRV |
Service host and port | For protocols that need port discovery |
HTTPS / SVCB |
Connection hints before the first request | RFC 9460: ALPN (h3), IP hints, and the ECH config browsers need to encrypt SNI |
PTR |
Reverse: address → name | Lives 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.
# 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
# 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
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 butdig @1.1.1.1is 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.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: TCP SYN → SYN/ACK → ACK
C->>S: ClientHello (SNI or ECH, ALPN=[h2,http/1.1], key_share X25519MLKEM768)
S->>C: ServerHello (key_share) + {Certificate, CertificateVerify, Finished}
Note over C,S: Client validates chain to a trusted root,<br/>checks hostname against SAN, checks validity dates
C->>S: {Finished}
C->>S: {HTTP request}, encrypted
S->>C: {HTTP response}, encrypted
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
HTTPSDNS record, and observers see only a shared public name. Vercel enables ECH automatically, and observers seevercel-ech.com. - ALPN (RFC 7301) agrees on
h2,http/1.1orh3inside 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.
- 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". - 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.
- Validity window:
notBefore≤ now ≤notAfter. Expiry is an outage, so renewal must be automated. - Transparency: modern browsers require Certificate Transparency SCTs.
Certificate lifetimes are collapsing — automate or break
| Date (issuance) | Max publicly-trusted TLS cert lifetime | Source |
|---|---|---|
| until 2026-03-14 | 398 days | CA/B Forum Baseline Requirements |
| from 2026-03-15 | 200 days | Ballot SC-081v3 |
| from 2027-03-15 | 100 days | SC-081v3 |
| from 2029-03-15 | 47 days (domain-validation reuse: 10 days) | SC-081v3 |
Let's Encrypt, which Vercel uses, has its own schedule:
- 2026-05-13: the opt-in
tlsserverprofile issues 45-day certificates. - 2027-02-10: the default
classicprofile drops to 64 days, with 10-day authorization reuse. - 2028-02-16:
classicdrops 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:
CAAmust 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.
# 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=63072000on custom domains (subdomain-scoped; noincludeSubDomains). AddincludeSubDomains; preloadthrough 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"(plusissuewildif 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, runningcurl -k, or passingrejectUnauthorized: falseturns a certificate bug into a permanent MITM hole. Fix the chain instead.
HTTP/1.1, HTTP/2, HTTP/3
| HTTP/1.1 | HTTP/2 (RFC 9113) | HTTP/3 (RFC 9114) | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC over UDP (RFC 9000) |
| Framing | Text | Binary frames | Binary frames on QUIC streams |
| Concurrency | One request in flight per connection; browsers open ~6 per origin | Multiplexed streams on one connection | Multiplexed, independent streams |
| Head-of-line blocking | At the request level | Gone at the HTTP level, still there at the TCP level: one lost segment stalls every stream | Gone: a lost packet stalls only its own stream |
| Header compression | None | HPACK | QPACK |
| Handshake | TCP + TLS separately | TCP + TLS separately | TLS 1.3 built into the QUIC handshake |
| Connection migration | No | No | Yes: the connection ID survives an IP change |
| Discovery | default | ALPN h2 |
Alt-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.comreturnsalt-svc: h3=":443"; ma=86400. - Vercel: not documented, and no
Alt-Svconvercel.comortech-stack.codeamanilabs.org(checked 2026-10-20).
If HTTP/3 matters, for example for Kenya-targeted traffic, put Cloudflare in front.
# 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 Events | WebSocket (RFC 6455) | |
|---|---|---|
| Direction | Server → client only | Bidirectional |
| Wire | Plain HTTP response, Content-Type: text/event-stream |
HTTP GET + Upgrade: websocket, then framed TCP |
| Reconnect | Built in. EventSource reconnects and resends the last id: as Last-Event-ID; retry: sets the delay |
You write it: backoff, resubscribe, reload state |
| Proxies / middleboxes | Pass through like any HTTP response (send Cache-Control: no-transform) |
Some corporate proxies break the upgrade |
| Browser limit | 6 per browser + domain over HTTP/1.1; negotiated (default 100) over HTTP/2 | No per-domain cap of note |
| CORS | Applies (EventSource with withCredentials) |
Does not apply. Check Origin yourself |
| Fit | Token streaming (AI), live feeds, order status | Chat, 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, withws(≥ 8) as a peer dependency. Seeexamples/ws-route.ts. Standalone Node servers (Express, Hono, h3), Nitro/Nuxt, Bun'sBun.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-Typelimited toapplication/x-www-form-urlencoded,multipart/form-dataortext/plain) go straight out. Anything else is preflighted with anOPTIONSrequest. A JSONPOSTis preflighted. - Credentials and
*don't mix. With cookies orAuthorization,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-Agedefaults 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
Originheader in the upgrade handler (cross-site WebSocket hijacking).
// 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.
curl -sI https://tech-stack.codeamanilabs.org | grep -Ei "cf-ray|cf-cache-status|x-vercel-cache|x-vercel-id|age|cache-control"
| Header | Meaning |
|---|---|
x-vercel-cache: HIT / MISS / STALE |
Vercel CDN cache outcome |
x-vercel-id: iad1::… |
Vercel region(s) that handled the request |
cf-cache-status: HIT / MISS / DYNAMIC / BYPASS |
Cloudflare cache outcome |
cf-ray: …-NBO |
Cloudflare ray ID; the suffix is the PoP's IATA code (NBO = Nairobi) |
age |
Seconds 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 Tunnel | Cloudflare named Tunnel | Tailscale Funnel | |
|---|---|---|---|---|
| Command | ngrok http 3000 |
cloudflared tunnel --url http://localhost:3000 |
cloudflared tunnel run <name> |
tailscale funnel --bg 3000 |
| URL | Free: one assigned dev domain (*.ngrok-free.app); custom domains are paid |
Random *.trycloudflare.com, new every run |
Your own hostname on a Cloudflare zone | <machine>.<tailnet>.ts.net |
| Account | Required (authtoken) | None | Cloudflare account + zone | Tailscale account; MagicDNS + HTTPS + funnel node attribute |
| Limits | Free: 3 endpoints, 1 GB/month out, 20,000 HTTP requests/month (4,000/min), 5,000 TCP conns/month | 200 in-flight requests (then 429), no SSE, no uptime guarantee | Production-grade | Ports 443/8443/10000 only, TLS only, non-configurable bandwidth limits |
| Browser interstitial | Yes on free. Skip with the ngrok-skip-browser-warning header (any value) or a non-browser User-Agent; API callers are unaffected |
No | No | No |
| Best for | Daraja/Stripe webhook dev, request inspector at http://127.0.0.1:4040 |
Throwaway demo of a page | Staging hooks, internal tools on your domain | Sharing from a box already on your tailnet |
# 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.
| Where | Tool | Rule of thumb |
|---|---|---|
| Cloud VM | Provider security group / firewall | Inbound 443 (+80 for redirect/ACME) from anywhere; 22 from nowhere (use Tailscale SSH or Cloudflare Access); DB ports from the app subnet only |
| Linux host | ufw / nftables |
ufw 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: |
| Vercel | Vercel Firewall (WAF, rate limits, IP blocks) | Rules also apply to WebSocket upgrade requests |
| Cloudflare | WAF / rate limiting / Access | Put admin surfaces behind Access instead of an "unguessable" path |
| Windows / WSL | Windows Defender Firewall + Hyper-V firewall | WSL 2.0.9+ on Windows 11 22H2+ filters WSL traffic through the Hyper-V firewall by default |
| Managed Postgres | Supabase / Neon network restrictions | Allowlist 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) | |
|---|---|---|
| Enable | default | .wslconfig → [wsl2] networkingMode=mirrored, then wsl --shutdown |
| Requires | — | Windows 11 22H2+ |
| Windows → Linux server | localhost works (localhostForwarding=true) |
localhost works |
| Linux → Windows server | Use the host IP: ip route show | grep -i default | awk '{ print $3}' |
127.0.0.1 works (::1 does not) |
| IPv6 inside Linux | No | Yes |
| VPN compatibility | Often broken | Improved |
| LAN → WSL (phone testing) | netsh interface portproxy to the VM IP, which changes on restart |
Direct, once a Hyper-V firewall rule allows it |
Related .wslconfig keys (all [wsl2], Windows 11 22H2+):
dnsTunneling(defaulttrue): answers DNS through Windows. Fixes most VPN DNS breakage.firewall(defaulttrue): Windows and Hyper-V firewall rules filter WSL traffic.autoProxy(defaulttrue): 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:
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.
# 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
| Symptom | Most likely layer | Next command |
|---|---|---|
Could not resolve host |
DNS | dig @1.1.1.1 <name> then dig @<authoritative-ns> <name> |
Connection refused |
Transport: nothing listening | ss -tlnp on the host |
Connection timed out |
Firewall / security group silently dropping | traceroute, then check the security group |
certificate verify failed / UNABLE_TO_VERIFY_LEAF_SIGNATURE |
TLS chain | openssl s_client -showcerts |
ERR_TLS_CERT_ALTNAME_INVALID |
Hostname not in SAN | Add the hostname to the platform's domain list |
Works in browser, fails in curl/app |
Missing intermediate certificate | Serve the full chain |
Right in dig @ns, wrong for users |
DNS TTL still counting down | Wait; do not re-edit the record |
| WebSocket closes after a few minutes on Vercel | Function max duration reached | Expected; reconnect with backoff |
| SSE works locally, never streams through a tunnel | Cloudflare Quick Tunnel (no SSE) or a buffering proxy | Use ngrok/named tunnel; send Cache-Control: no-transform |
| Fast locally, slow in production | RTT / cache miss | curl -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.
# 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.
| Risk | Why it happens | Mitigation |
|---|---|---|
| Open ports / exposed services | Service bound to 0.0.0.0; a 0.0.0.0/0 rule left over from debugging; Docker bypassing ufw |
Bind internal services to 127.0.0.1; default-deny inbound; audit with ss -tlnp; put admin surfaces behind Tailscale or Cloudflare Access |
| Weak / misconfigured TLS | Legacy versions enabled; missing intermediate; renewal blocked | TLS 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-claims |
2FA + registrar lock (porkbun); publish CAA; delete DNS records when you tear down what they point at |
| DNS spoofing / cache poisoning | Plaintext UDP:53 answers are forgeable on hostile networks | DNSSEC (RFC 4033) on your zone; DoH (RFC 8484) / DoT (RFC 7858) on clients you control |
| SSRF: server fetches an attacker-chosen URL | Any 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 hijacking | CORS does not protect WebSockets; cookies ride along on the upgrade | Check Origin and authenticate the upgrade request |
| MITM on hostile networks | Public Wi-Fi, transparent proxies, captive portals | HTTPS everywhere + HSTS; never disable certificate verification |
| Credentials on the wire | Postgres/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 tunnels | A dev tunnel left running exposes an unauthenticated local server | Stop tunnels after use; verify webhook signatures even in dev |
| Amplification / volumetric abuse | Unauthenticated endpoints that do real work | Rate 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:
// 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.
- Registrar. The name lives at Porkbun, and the
porkbun-dnsskill 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. - DNS. Use either Porkbun's nameservers or Cloudflare's.
- Apex →
Arecord with the value from Vercel Settings → Domains (the KB still cites76.76.21.21). - Subdomain →
CNAMEto the per-project Vercel target. Copy it exactly, including the trailing dot. - No
AAAAto Vercel. Vercel is IPv4-only.
- Apex →
- TLS. Vercel issues and renews certificates automatically through Let's Encrypt (HTTP-01; DNS-01 for wildcards). If you publish
CAA, include0 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. - Verify before declaring done.
dig @<authoritative-ns>for truth,dig @1.1.1.1for reach, andnode networking/examples/cert-check.mts <host>for the chain. A green dashboard and a wrongCAArecord 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 inNEXT_PUBLIC_*. The SSRF host allowlist andAPP_ORIGINare 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/0rule outlives the debugging session that created it. - Delete DNS records when you delete what they point to. A
CNAMEleft 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
preconnectonly the origins you cannot remove. - Prefer SSE plus
POSTover WebSockets for mobile realtime.EventSourceresumes on its own after a drop by sendingLast-Event-ID. A WebSocket needs hand-written reconnect logic, and half-open TCP connections on mobile radio need heartbeats (seews-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-raysuffixNBO) plus longCache-Controlon 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 -wtiming probe through a throttled profile; seePATTERNS.md.
Troubleshooting
| Issue | Fix |
|---|---|
| Record changed but users still see the old value | TTL has not expired. Confirm with dig @<authoritative-ns>, then wait; re-editing changes nothing |
CNAME rejected at the apex |
Not allowed in DNS. Use an A record, or the provider's ALIAS/ANAME/flattening |
Want AAAA for a Vercel domain |
Not supported by Vercel. Proxy through Cloudflare for IPv6 |
| Certificate issuance/renewal fails | Check 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 fine |
Server omits the intermediate. Serve the full chain |
ERR_SSL_PROTOCOL_ERROR on a proxied domain |
Cloudflare 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 locally | Dev box is behind NAT. Tunnel it (ngrok http 3000) and register the HTTPS URL |
| ngrok URL returns an HTML warning page to a webhook test | Free-plan interstitial. Send ngrok-skip-browser-warning: 1 (real API callers aren't affected) |
SSE stream never arrives through trycloudflare.com |
Quick 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/deploy | Connections pin to one instance; reconnects may land elsewhere. Move state to Redis |
runtime = 'edge' route suddenly runs on Node |
Expected on Next.js ≥ 16.3. Remove the export |
| CORS error only when logged in | Access-Control-Allow-Origin: * with credentials. Reflect the allowlisted origin and add Vary: Origin |
WSL can't reach a Windows service on localhost |
NAT mode. Switch to networkingMode=mirrored, or use the host IP from ip route |
Phone on Wi-Fi can't reach next dev in WSL |
Bind -H 0.0.0.0, use mirrored mode, and add a port-scoped New-NetFirewallHyperVRule |
.wslconfig edit has no effect |
wsl --shutdown, or wait ~8 s after closing every distro shell |
traceroute shows * * * for the last hops |
ICMP filtered; normal for cloud hosts. Test the port with nc -vz instead |
Two v=spf1 TXT records on one domain |
Permanent 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 |
Official docs:
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview
- https://www.rfc-editor.org/rfc/rfc1035
- https://www.rfc-editor.org/rfc/rfc8446
- https://www.rfc-editor.org/rfc/rfc9114
- https://vercel.com/docs/functions/websockets
- https://learn.microsoft.com/en-us/windows/wsl/networking
- https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
- https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html