The test runs in the browser against this website only. There is no account and no analytics.
The files below are copied from the project when the site is built. They match the files in the zip. The build uses Node.js only. It does not install packages.
Ratings
The result is the highest rating where download, upload, and ping all meet the bar.
The numbers come from public/js/thresholds.js, which is listed below.
| Rating | Band | Download | Upload | Ping |
|---|
What the test does
Download reads /assets/test-blob.bin, a 16 MB file of random bytes.
Upload sends random chunks to POST /api/upload. That endpoint reads the body and discards it.
Ping is the median of six requests to /assets/ping.txt.
On Cloudflare Pages the upload endpoint is functions/api/upload.js.
Locally, node server.mjs does the same thing.
README.md
# How's My Wi-Fi
A free, private speed check. It times a download, an upload, and a round trip from the browser to this website, then shows a rating: Excellent, Good, Fair, Slow, or Poor.
This is a static site. It can sit on Cloudflare Pages’ free tier. There is no database and no analytics. The only server behavior is an upload endpoint that reads a request body and throws it away, so the browser can time a real upload.
## Run it locally
You need Node.js 18 or newer. No install step.
```bash
node server.mjs
```
Open [http://127.0.0.1:8741](http://127.0.0.1:8741). The test starts on its own.
`server.mjs` serves the `public/` folder and accepts `POST /api/upload`, which discards the body. That is the same job as `functions/api/upload.js` on Cloudflare. A purely static file server cannot time an upload, because nothing is there to receive the bytes. If the 16 MB test file is missing, the server writes it before it starts listening.
Set `PORT` to listen somewhere else:
```bash
PORT=8741 node server.mjs
```
Check the report-card math without a browser:
```bash
node scripts/self-check.mjs
```
Generate the test file on its own:
```bash
node scripts/build-site.mjs
```
That writes `public/assets/test-blob.bin` (16 MB of random bytes). The file is gitignored. Do not commit it. Random bytes are required because a file of zeros compresses and would overstate the speed.
On this machine the preview measures loopback, not a home router. Expect Excellent and a very large number. That result is the speed of this machine. It is not a measurement of a room’s Wi-Fi.
## What the test measures
All of it stays on this origin.
- **Download.** `GET /assets/test-blob.bin` with `cache: "no-store"`. One short warmup, then about 4.5 seconds or 32 MB, whichever comes first, across three connections.
- **Upload.** `POST /api/upload` with random 1 MB chunks for about 4 seconds or 16 MB. The endpoint reads the body, then discards it and returns `204`. A failed request retries once with a smaller chunk. A missing endpoint does not retry; the page says how to start the right server.
- **Latency.** One warmup, then six trips to `/assets/ping.txt`. The grade uses the median. Jitter is the average distance from that median. Jitter is shown and not graded.
- **Megabits.** Payload bytes times 8, divided by seconds, divided by 1,000,000. Protocol overhead is not included, so this is the traffic you actually moved.
The browser is told `Cache-Control: no-store`. On Cloudflare, `_headers` also sets `CDN-Cache-Control` on the test file so an edge may keep a copy. A nearby edge is the point: the grade should be about the connection in front of the visitor. Unique URLs are not used, because they would skip that edge and measure a longer trip.
## Ratings
The highest rating where **download, upload, and ping all meet the bar**. A fast download with a slow upload or a high ping is rated lower. Thresholds live in `public/js/thresholds.js`. The `/code` page renders the same file.
| Rating | Band | Download | Upload | Ping |
| --- | --- | --- | --- | --- |
| Excellent | Green | ≥ 150 Mbps | ≥ 10 Mbps | ≤ 80 ms |
| Good | Green | ≥ 50 Mbps | ≥ 5 Mbps | ≤ 120 ms |
| Fair | Yellow | ≥ 20 Mbps | ≥ 2 Mbps | ≤ 180 ms |
| Slow | Yellow | ≥ 5 Mbps | ≥ 1 Mbps | ≤ 300 ms |
| Poor | Red | Below Slow | Below Slow | Below Slow |
Why these bars:
- **150 / 10 / 80 ms (Excellent)** supports several 4K streams, video calls, and large downloads. 10 Mbps up covers a call plus a backup. 80 ms still leaves room for distance to a nearby edge.
- **50 / 5 / 120 ms (Good)** supports HD streaming and video calls on a few devices.
- **20 / 2 / 180 ms (Fair)** supports browsing, email, and one video stream.
- **5 / 1 / 300 ms (Slow)** supports light browsing. Video is likely to buffer.
- **Below that (Poor)** is below the level needed for steady browsing. The same rating is used when the test does not finish.
Ping limits are wide because the number is an HTTP round trip to this site, not ICMP. Distance to the nearest edge is included. Download and upload decide most of the rating.
Color repeats the rating. The words Excellent, Good, Fair, Slow, and Poor are always shown.
Examples:
- 300 Mbps down, 12 Mbps up, 22 ms → Excellent
- 300 Mbps down, 12 Mbps up, 150 ms → Fair (ping missed Good and Excellent)
- 300 Mbps down, 4 Mbps up, 20 ms → Fair (upload missed Good and Excellent)
- 40 Mbps down, 6 Mbps up, 50 ms → Good
- 4 Mbps down → Poor
## Privacy
- Visible “No data collected” statement on the page.
- Results render in the browser. The last five results are kept in `localStorage` under `howsmywifi.history.v1` (rating, three numbers, jitter, timestamp). Clearing site data removes them.
- No cookies, no accounts, no third-party scripts, fonts, or pixels. Fonts are self-hosted (Fraunces and Outfit, SIL Open Font License; see `public/fonts/*-OFL.txt`).
- The share line is the rating plus `howsmywifi.com`. It never includes an IP address, a location, or the measurements.
- Content-Security-Policy is `default-src 'self'`. The upload endpoint returns 403 when the `Origin` host does not match `Host`.
- Brave with Shields up should work, because the page never leaves its own origin. Strict timer rounding in privacy browsers can nudge a number slightly.
The dashed “Affiliate placeholder” boxes and the ad slot are not live. They do not load a network. “View the code” goes to `/code` on this same site. That page lists the source files and links to `/source.zip`, which is built with the site.
## Deploy to Cloudflare Pages
1. In the Cloudflare dashboard, create a Pages project from these files.
2. Framework preset: **None**.
3. Build command: `node scripts/build-site.mjs`
4. Build output directory: `public`
5. Deploy. Pages picks up `functions/` from the project root on its own. No environment variables and no package install.
6. Attach the domain `howsmywifi.com` when you are ready.
The build command uses Node.js only. It creates the 16 MB test file (under the Pages 25 MiB per-file limit), writes `/code` from the source files, and writes `/source.zip`. There is no bundler and no npm install.
`public/_headers` sends the security headers, tells browsers not to cache the test file, and lets Cloudflare’s edge cache that file for a week via `CDN-Cache-Control`.
Optional local check of the real function, if you have Wrangler:
```bash
node scripts/build-site.mjs
npx wrangler pages dev public
```
`node server.mjs` is enough for day-to-day preview.
## Layout
```
public/ static site (Pages output)
index.html the check
code/index.html how it works
404.html
css/styles.css
js/ thresholds, speed test, page behavior
assets/ favicon, ping file, generated blob
fonts/ self-hosted Fraunces and Outfit
_headers Cloudflare headers
functions/api/upload.js
scripts/build-site.mjs blob, /code page, and source zip
scripts/generate-test-blob.mjs
scripts/code-page.template.html
scripts/self-check.mjs
server.mjs local static server plus the discard endpoint
```
## Limitations
- The grade includes Wi-Fi, the router, the plan, and the path to this site. It cannot see which of those is the bottleneck. The quick fixes are the honest first pass.
- Figures are browser payload estimates. They are not a lab meter, and they do not count packet loss.
- Very fast links hit the byte cap in under a second, so a result above Excellent is a short sample.
- Upload time includes however long the endpoint takes to read the body.
- Latency is HTTP, not ICMP. Jitter is displayed and does not move the rung.
- Loopback (this preview) is not a living-room measurement.
- Cloudflare’s free tier has bandwidth limits. The test file is 16 MB and repeated checks use that bandwidth. A very slow upload that cannot finish inside the platform’s request limits stops the test. The page reports that and offers another try.
- Affiliate links and the ad slot are placeholders. No ad-network code is included.
- Wording on the site is factual. Ratings are Excellent, Good, Fair, Slow, and Poor.
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>How's My Wi-Fi?</title>
<meta name="description" content="A free Wi-Fi speed check. Download, upload, and ping, measured in this browser." />
<meta name="referrer" content="no-referrer" />
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#fffaf3" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#241f1a" />
<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml" />
<link rel="preload" href="/fonts/outfit-400.woff2" as="font" type="font/woff2" crossorigin />
<link rel="preload" href="/fonts/outfit-500.woff2" as="font" type="font/woff2" crossorigin />
<link rel="stylesheet" href="/css/styles.css" />
</head>
<body class="home">
<a class="skip" href="#speed">Skip to the speed</a>
<main id="main">
<section class="stage" id="speed">
<h1 class="home-mark">
<a class="wordmark" href="/">How’s My Wi-Fi?</a>
</h1>
<div class="stage-center">
<p class="speed">
<span class="speed-value" id="down-value">—</span>
<span class="speed-unit" id="down-unit">Mbps</span>
</p>
<p class="verdict-line" id="verdict" hidden><span id="verdict-name"></span></p>
<button class="more-info" type="button" id="more" hidden aria-expanded="false" aria-controls="details">
Show more info
</button>
</div>
<p class="sr-only" id="status" role="status">Starting the test…</p>
<footer class="home-foot">
<span>No data collected</span>
<a href="/code/">View the code</a>
</footer>
</section>
<section class="details" id="details" hidden>
<p class="details-lead">Measured from this browser to this website.</p>
<div class="detail-stats" aria-label="More measurements">
<p>
<span class="kicker">Upload</span>
<strong id="up-value">—</strong> <span id="up-unit">Mbps</span>
</p>
<p>
<span class="kicker">Ping</span>
<strong id="ping-value">—</strong> ms
</p>
</div>
<p class="verdict-blurb" id="verdict-blurb"></p>
<p class="again-note">A repeat test takes about 15 seconds.</p>
<p class="actions">
<button class="button-primary" type="button" id="again">Test again</button>
</p>
<h2>Quick fixes</h2>
<ol class="fix-list">
<li>Unplug the router for 30 seconds, then plug it back in.</li>
<li>Move closer to the router.</li>
<li>Use the 5 GHz network if the router has one.</li>
<li>Pause large downloads and streams on other devices.</li>
<li>
For a larger home, add a mesh system or replace the router.
<p class="affiliate-slot" id="affiliate-mesh" data-affiliate-slot="mesh">
<span class="slot-label">Affiliate placeholder</span>
Mesh Wi-Fi system. Not a live link.
</p>
</li>
</ol>
<h2 id="share-heading">Share</h2>
<label class="kicker" for="share-text">Share text</label>
<textarea
id="share-text"
class="share-text"
rows="2"
readonly
placeholder="Your verdict line shows up here."
></textarea>
<div class="actions">
<button class="button-primary" type="button" id="copy" disabled>Copy Link</button>
<button class="button-secondary" type="button" id="native-share" hidden disabled>Share</button>
</div>
<h2 id="numbers-heading">What the numbers mean</h2>
<h3>Download</h3>
<p>How fast data arrives, in megabits per second. Used by video and web pages.</p>
<h3>Upload</h3>
<p>How fast data leaves, in megabits per second. Used by video calls and file uploads.</p>
<h3>Ping</h3>
<p>Round-trip time in milliseconds. Lower is more responsive. Under 50 ms is suitable for calls.</p>
<aside class="ad-slot" id="ad-slot" aria-label="Advertisement placeholder" data-ad-slot="details">
<p class="ad-kicker">Ad</p>
<p>Placeholder. No ad script is loaded, and nothing is requested from an ad network.</p>
</aside>
</section>
</main>
<noscript>
<p class="noscript">The speed check needs JavaScript. The script is served from this same site.</p>
</noscript>
<script type="module" src="/js/app.js"></script>
</body>
</html>
public/css/styles.css
@font-face {
font-family: "Fraunces";
src: url("/fonts/fraunces-600.woff2") format("woff2");
font-weight: 600;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Fraunces";
src: url("/fonts/fraunces-600-italic.woff2") format("woff2");
font-weight: 600;
font-style: italic;
font-display: swap;
}
@font-face {
font-family: "Outfit";
src: url("/fonts/outfit-400.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Outfit";
src: url("/fonts/outfit-500.woff2") format("woff2");
font-weight: 500;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Outfit";
src: url("/fonts/outfit-700.woff2") format("woff2");
font-weight: 700;
font-style: normal;
font-display: swap;
}
:root {
color-scheme: light;
--bg: #e7dcc8;
--sheet: #fffaf3;
--ink: #231e18;
--muted: #4e463c;
--line: #eadfce;
--rule: #cbbba4;
--green: #0e5c34;
--green-bg: #e5f6ec;
--yellow: #7a4b00;
--yellow-bg: #fff4dc;
--red: #8f1d2c;
--red-bg: #fdecef;
--gold: #a97800;
--link: #184a86;
--shadow: 0 24px 60px rgba(70, 48, 12, 0.12);
--serif: "Fraunces", "Iowan Old Style", Palatino, Georgia, serif;
--sans: "Outfit", "Avenir Next", "Segoe UI", sans-serif;
}
@media (prefers-color-scheme: dark) {
:root {
color-scheme: dark;
--bg: #14110e;
--sheet: #241f1a;
--ink: #f6f1e8;
--muted: #d2c4b2;
--line: #3c342c;
--rule: #5a4e42;
--green: #9ee0b6;
--green-bg: #173226;
--yellow: #f3cc7a;
--yellow-bg: #332912;
--red: #ffb7c1;
--red-bg: #3c1d24;
--gold: #f0c14b;
--link: #9dc2f5;
--shadow: 0 24px 60px rgba(0, 0, 0, 0.35);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
min-height: 100vh;
font-family: var(--sans);
font-size: 1.0625rem;
line-height: 1.55;
color: var(--ink);
background-color: var(--bg);
background-image:
radial-gradient(ellipse at 0% 0%, rgba(255, 250, 243, 0.7), transparent 46%),
radial-gradient(ellipse at 100% 100%, rgba(169, 120, 0, 0.16), transparent 42%);
}
@media (prefers-color-scheme: dark) {
body {
background-image:
radial-gradient(ellipse at 0% 0%, rgba(240, 193, 75, 0.08), transparent 42%),
radial-gradient(ellipse at 100% 100%, rgba(255, 250, 243, 0.04), transparent 40%);
}
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
*,
*::before,
*::after {
animation: none !important;
transition: none !important;
}
}
img,
svg {
max-width: 100%;
}
p,
h1,
h2,
h3 {
overflow-wrap: break-word;
}
a {
color: var(--link);
text-underline-offset: 0.16em;
}
a:visited {
color: var(--link);
}
a.wordmark,
a.wordmark:visited {
color: inherit;
text-decoration: none;
}
a.button-secondary,
a.button-secondary:visited {
color: var(--ink);
}
:focus-visible {
outline: 3px solid var(--link);
outline-offset: 3px;
}
.skip {
position: absolute;
left: 12px;
top: -48px;
z-index: 5;
background: var(--sheet);
color: var(--ink);
padding: 8px 12px;
border-radius: 8px;
}
.skip:focus {
top: 12px;
}
.sheet {
width: min(1080px, calc(100% - 24px));
margin: 28px auto 40px;
padding: clamp(20px, 4vw, 48px);
background: var(--sheet);
border: 1px solid var(--rule);
border-radius: 28px;
box-shadow: var(--shadow);
}
.mast {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 18px 28px;
flex-wrap: wrap;
position: relative;
padding-bottom: 22px;
margin-bottom: 22px;
}
.mast::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 3px;
background: linear-gradient(90deg, var(--gold), transparent 72%);
}
.kicker,
.stat-label,
.slot-label,
.ad-kicker {
margin: 0 0 6px;
font-size: 0.75rem;
letter-spacing: 0.14em;
text-transform: uppercase;
font-weight: 700;
color: var(--muted);
}
.stat-label {
white-space: nowrap;
}
.nowrap {
white-space: nowrap;
}
.brand-title {
margin: 0;
font-family: var(--serif);
font-size: clamp(2.1rem, 6vw, 3.4rem);
font-weight: 600;
letter-spacing: -0.04em;
line-height: 0.95;
}
.wordmark {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 10px 12px;
}
.mark {
width: 42px;
height: 42px;
flex: none;
}
.mast-actions {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.privacy-badge {
display: inline-flex;
align-items: center;
gap: 8px;
margin: 0;
padding: 7px 12px;
border: 1px solid var(--green);
border-radius: 999px;
background: var(--green-bg);
color: var(--green);
font-weight: 700;
line-height: 1.2;
}
.privacy-dot {
width: 0.55rem;
height: 0.55rem;
border-radius: 50%;
background: currentColor;
}
.lede {
max-width: 42rem;
margin: 0;
font-size: 1.15rem;
}
.fine {
max-width: 42rem;
margin: 12px 0 0;
color: var(--muted);
}
.report {
display: grid;
gap: 22px;
margin-top: 28px;
}
.seal {
position: relative;
width: min(240px, 70vw);
margin: 0 auto;
aspect-ratio: 1;
color: var(--rule);
}
.seal[data-band="green"] {
color: var(--green);
}
.seal[data-band="yellow"] {
color: var(--yellow);
}
.seal[data-band="red"] {
color: var(--red);
}
.seal svg {
width: 100%;
height: 100%;
}
.seal-track {
fill: none;
stroke: var(--line);
stroke-width: 8;
}
#seal-ring {
fill: none;
stroke: currentColor;
stroke-width: 8;
stroke-linecap: round;
transform: rotate(-90deg);
transform-origin: 60px 60px;
transition: stroke-dashoffset 180ms linear;
}
.seal-readout {
position: absolute;
inset: 18%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
color: var(--ink);
}
.seal-kicker,
.seal-unit {
margin: 0;
font-size: 0.75rem;
letter-spacing: 0.14em;
text-transform: uppercase;
font-weight: 700;
color: var(--muted);
}
.seal-value {
margin: 2px 0;
font-family: var(--serif);
font-weight: 600;
font-size: clamp(1.8rem, 5vw, 2.6rem);
letter-spacing: -0.04em;
line-height: 0.95;
}
.seal[data-tier="gold"] .seal-unit::before {
content: "★ ";
color: var(--gold);
}
.report-main {
min-width: 0;
}
.stats {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
align-items: stretch;
}
.stat {
margin: 0;
padding: 14px;
border-radius: 16px;
background: var(--bg);
border: 1px solid transparent;
min-width: 0;
}
@supports (background: color-mix(in srgb, black 50%, white)) {
.stat {
background: color-mix(in srgb, var(--bg) 65%, var(--sheet));
}
}
.stat[data-active="true"] {
border-color: var(--ink);
}
.stat-value {
margin: 4px 0 0;
font-family: var(--serif);
font-size: clamp(1.7rem, 4vw, 2.5rem);
letter-spacing: -0.04em;
line-height: 1;
}
.stat-unit {
font-family: var(--sans);
font-size: 0.85rem;
letter-spacing: 0;
color: var(--muted);
}
.stat-note {
margin: 8px 0 0;
color: var(--muted);
font-size: 0.95rem;
}
.verdict {
margin-top: 14px;
padding: 16px 16px 14px;
border-radius: 18px;
border-left: 8px solid var(--rule);
background: var(--line);
}
.verdict[data-band="green"] {
background: var(--green-bg);
border-left-color: var(--green);
}
.verdict[data-band="yellow"] {
background: var(--yellow-bg);
border-left-color: var(--yellow);
}
.verdict[data-band="red"] {
background: var(--red-bg);
border-left-color: var(--red);
}
.verdict-kicker {
margin: 0 0 4px;
font-size: 0.75rem;
letter-spacing: 0.16em;
text-transform: uppercase;
font-weight: 700;
}
.verdict[data-band="green"] .verdict-kicker,
.verdict[data-band="green"] .verdict-title {
color: var(--green);
}
.verdict[data-band="yellow"] .verdict-kicker,
.verdict[data-band="yellow"] .verdict-title {
color: var(--yellow);
}
.verdict[data-band="red"] .verdict-kicker,
.verdict[data-band="red"] .verdict-title {
color: var(--red);
}
.verdict-title {
display: flex;
align-items: baseline;
gap: 0.35rem;
margin: 0;
font-family: var(--serif);
font-style: italic;
font-weight: 600;
font-size: clamp(2rem, 5vw, 3.15rem);
letter-spacing: -0.035em;
line-height: 1.02;
text-wrap: balance;
}
#verdict-name {
min-width: 0;
}
.verdict[data-state="done"] .verdict-title {
transform: rotate(-1.1deg);
transform-origin: left center;
}
.verdict[data-state="running"] .verdict-title {
font-family: var(--sans);
font-style: normal;
font-weight: 500;
font-size: clamp(1.25rem, 2.6vw, 1.65rem);
letter-spacing: 0;
}
.verdict-emoji:empty {
display: none;
}
.verdict-emoji {
font-style: normal;
}
.verdict-blurb,
.verdict-note,
.transfer-note {
margin: 10px 0 0;
max-width: 40rem;
color: var(--ink);
}
.verdict-note,
.transfer-note {
color: var(--muted);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 16px;
}
button,
.button {
font: inherit;
cursor: pointer;
min-height: 44px;
padding: 0.65rem 1.15rem;
border-radius: 999px;
border: 1px solid transparent;
text-decoration: none;
}
.button-primary {
background: var(--ink);
color: var(--sheet);
}
.button-primary:hover:not(:disabled) {
transform: translateY(-1px);
}
.button-secondary {
display: inline-flex;
align-items: center;
justify-content: center;
background: transparent;
color: var(--ink);
border-color: var(--rule);
}
.button-primary:disabled,
.button-secondary[aria-disabled="true"] {
opacity: 0.45;
cursor: not-allowed;
}
.progress {
height: 6px;
margin-top: 16px;
border-radius: 999px;
background: var(--line);
overflow: hidden;
}
body[data-state="done"][data-band="green"] .progress-fill {
background: var(--green);
}
body[data-state="done"][data-band="yellow"] .progress-fill {
background: var(--yellow);
}
body[data-state="done"][data-band="red"] .progress-fill {
background: var(--red);
}
.progress-fill {
display: block;
height: 100%;
width: 0;
background: var(--ink);
border-radius: inherit;
}
.status {
min-height: 1.5em;
margin: 10px 0 0;
font-weight: 500;
}
.panel {
margin-top: 28px;
padding-top: 22px;
border-top: 1px solid var(--line);
}
.panel h2,
.prose h2,
.fix h3 {
margin: 0 0 8px;
font-family: var(--serif);
font-weight: 600;
letter-spacing: -0.03em;
line-height: 1.15;
}
.panel h2,
.prose h2 {
font-size: clamp(1.7rem, 3vw, 2.15rem);
}
.share-text {
width: 100%;
margin: 0;
padding: 12px 14px;
border: 1px solid var(--rule);
border-radius: 14px;
background: var(--sheet);
color: var(--ink);
font: inherit;
resize: vertical;
min-height: 4.75rem;
}
.columns {
display: grid;
gap: 8px 40px;
}
.explain h3 {
margin: 18px 0 4px;
font-size: 1.05rem;
}
.fix {
padding: 0;
border-top: 1px solid var(--line);
}
.fix summary {
padding: 16px 0;
font-family: var(--serif);
font-size: 1.35rem;
font-weight: 600;
letter-spacing: -0.03em;
cursor: pointer;
}
.fix summary:focus-visible {
outline-offset: 4px;
}
.fix p {
margin: 0 0 16px;
}
p.affiliate-slot {
display: block;
margin-top: 12px;
padding: 10px 12px;
border: 1.5px dashed var(--rule);
border-radius: 12px;
color: var(--muted);
text-decoration: none;
font-size: 0.95rem;
}
.slot-label,
.ad-kicker {
display: inline-block;
margin: 0 8px 0 0;
color: var(--ink);
}
.history-list {
margin: 12px 0 0;
padding-left: 1.2rem;
}
.history-list li + li {
margin-top: 6px;
}
.ad-slot {
margin-top: 28px;
padding: 16px;
border: 1.5px dashed var(--rule);
border-radius: 16px;
text-align: center;
color: var(--muted);
}
.ad-slot p {
margin: 0;
}
.footer {
margin-top: 28px;
padding-top: 18px;
border-top: 1px solid var(--line);
color: var(--muted);
}
.footer p {
margin: 0 0 8px;
}
.footer-links {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.55rem;
align-items: baseline;
}
.prose h2 {
margin-top: 1.6rem;
}
.prose p,
.prose li {
max-width: 42rem;
}
.table-wrap {
width: 100%;
overflow-x: auto;
margin: 12px 0 4px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.98rem;
}
th,
td {
text-align: left;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
vertical-align: top;
}
th {
font-size: 0.75rem;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--muted);
}
tr[data-band="green"] td:first-child {
color: var(--green);
}
tr[data-band="yellow"] td:first-child {
color: var(--yellow);
}
tr[data-band="red"] td:first-child {
color: var(--red);
}
code {
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
font-size: 0.92em;
}
.source {
overflow: auto;
max-height: 28rem;
margin: 0 0 1.5rem;
padding: 1rem 1.1rem;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--bg);
color: var(--ink);
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
font-size: 0.82rem;
line-height: 1.5;
white-space: pre;
tab-size: 2;
}
.source code {
font: inherit;
font-size: inherit;
}
@media (max-width: 639px) {
.stat {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: baseline;
column-gap: 16px;
}
.stat-label,
.stat-value {
margin: 0;
}
.stat-value {
text-align: right;
}
}
@media (min-width: 640px) {
.stats {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (min-width: 720px) {
.mast-actions {
align-items: flex-end;
}
.columns {
grid-template-columns: 1fr 1fr;
align-items: start;
}
}
@media (min-width: 900px) {
.report {
grid-template-columns: 260px minmax(0, 1fr);
align-items: center;
gap: 36px;
}
.seal {
width: 260px;
}
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
body.home {
min-height: 100vh;
background: var(--sheet);
background-image: none;
}
body.home .stage {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
min-height: 100dvh;
padding: 1.25rem 1.25rem 0;
}
body.home .home-mark {
margin: 1.25rem 0 0;
font-family: var(--sans);
font-size: 1rem;
font-weight: 500;
letter-spacing: 0;
line-height: 1.2;
}
body.home .home-mark .wordmark {
font-family: inherit;
font-size: inherit;
font-weight: inherit;
letter-spacing: inherit;
}
body.home .stage-center {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: min(100%, 960px);
text-align: center;
padding: 2rem 0 3rem;
}
body.home .speed {
display: flex;
align-items: baseline;
justify-content: center;
gap: 0.35rem;
margin: 0;
color: var(--ink);
line-height: 0.85;
}
body.home .speed-value {
font-family: var(--sans);
font-weight: 500;
font-size: clamp(4.6rem, 16vw, 10.5rem);
letter-spacing: -0.055em;
font-variant-numeric: tabular-nums;
}
body.home .speed-unit {
font-family: var(--sans);
font-size: clamp(1.35rem, 3vw, 2rem);
font-weight: 500;
letter-spacing: 0;
color: var(--muted);
}
body.home .verdict-line {
margin: 1.5rem 0 0;
font-family: var(--serif);
font-size: clamp(1.45rem, 3vw, 2rem);
font-weight: 600;
font-style: italic;
letter-spacing: -0.03em;
line-height: 1.15;
}
body.home .verdict-line[data-band="green"] {
color: var(--green);
}
body.home .verdict-line[data-band="yellow"] {
color: var(--yellow);
}
body.home .verdict-line[data-band="red"] {
color: var(--red);
}
body.home .more-info {
margin-top: 1.75rem;
padding: 0.4rem 0.2rem;
border: 0;
background: transparent;
color: var(--link);
font: inherit;
font-size: 0.98rem;
text-decoration: underline;
text-underline-offset: 0.18em;
cursor: pointer;
min-height: 44px;
}
body.home .home-foot {
display: flex;
justify-content: center;
gap: 1.25rem;
width: 100%;
margin: 0;
padding: 0 1rem 1.25rem;
border: 0;
color: var(--muted);
font-size: 0.82rem;
}
body.home .home-foot a {
color: var(--muted);
}
body.home .details {
width: min(640px, calc(100% - 2rem));
margin: 0 auto;
padding: 3rem 0 5rem;
}
body.home .details h2 {
margin: 2.25rem 0 0.6rem;
font-family: var(--serif);
font-size: 1.7rem;
font-weight: 600;
letter-spacing: -0.03em;
}
body.home .details h3 {
margin: 1.1rem 0 0.2rem;
font-family: var(--sans);
font-size: 1rem;
font-weight: 700;
}
body.home .details-lead {
margin: 0 0 1.75rem;
color: var(--muted);
}
body.home .detail-stats {
display: flex;
flex-wrap: wrap;
gap: 1.5rem 2.5rem;
margin-bottom: 1.25rem;
}
body.home .detail-stats p {
margin: 0;
}
body.home .detail-stats strong {
font-family: var(--sans);
font-size: 1.8rem;
font-weight: 500;
letter-spacing: -0.03em;
}
body.home .again-note {
color: var(--muted);
}
body.home .fix-list {
margin: 0.5rem 0 0;
padding-left: 1.2rem;
}
body.home .fix-list li + li {
margin-top: 0.85rem;
}
body.home .noscript {
width: min(640px, calc(100% - 2rem));
margin: 1rem auto 2rem;
}
@media (forced-colors: active) {
.privacy-badge,
.verdict,
.stat,
.affiliate-slot,
.ad-slot,
.button-primary {
border: 1px solid CanvasText;
}
}
public/js/thresholds.js
/**
* Report-card bars for How's My Wi-Fi.
*
* A result lands on the highest rung where download, upload, and latency
* all clear the bar. Latency is a median HTTP round trip to this site,
* so the ceilings are loose on purpose: a far-away visitor with fine
* Wi-Fi should not be graded as if the router were the whole planet.
*
* Source of truth for the homepage, the /code page, and scripts/self-check.mjs.
*/
export const TIERS = [
{
id: "excellent",
name: "Excellent",
band: "green",
bandLabel: "Green",
minDown: 150,
minUp: 10,
maxLatency: 80,
share: "My Wi-Fi rated Excellent. How's yours? howsmywifi.com",
blurb: "Excellent: handles several 4K streams, video calls, and large downloads.",
},
{
id: "good",
name: "Good",
band: "green",
bandLabel: "Green",
minDown: 50,
minUp: 5,
maxLatency: 120,
share: "My Wi-Fi rated Good. How's yours? howsmywifi.com",
blurb: "Good: handles HD streaming and video calls on a few devices.",
},
{
id: "fair",
name: "Fair",
band: "yellow",
bandLabel: "Yellow",
minDown: 20,
minUp: 2,
maxLatency: 180,
share: "My Wi-Fi rated Fair. How's yours? howsmywifi.com",
blurb: "Fair: handles browsing, email, and one video stream.",
},
{
id: "slow",
name: "Slow",
band: "yellow",
bandLabel: "Yellow",
minDown: 5,
minUp: 1,
maxLatency: 300,
share: "My Wi-Fi rated Slow. How's yours? howsmywifi.com",
blurb: "Slow: handles light browsing. Video is likely to buffer.",
},
{
id: "poor",
name: "Poor",
band: "red",
bandLabel: "Red",
floor: true,
share: "My Wi-Fi rated Poor. How's yours? howsmywifi.com",
blurb: "Poor: below the level needed for steady browsing, or the test did not finish.",
},
];
export function classify(result) {
const down = Number(result.down);
const up = Number(result.up);
const latency = Number(result.latency);
if (![down, up, latency].every(Number.isFinite)) {
return TIERS[TIERS.length - 1];
}
for (const tier of TIERS) {
if (tier.floor) return tier;
if (down >= tier.minDown && up >= tier.minUp && latency <= tier.maxLatency) {
return tier;
}
}
return TIERS[TIERS.length - 1];
}
export function limitingNote(result, tier) {
if (tier.id === "excellent") {
return "Download, upload, and ping all meet the Excellent bar.";
}
if (tier.floor) {
return "At least one number is below the Slow bar.";
}
const index = TIERS.findIndex((item) => item.id === tier.id);
const higher = TIERS[index - 1];
if (!higher || higher.floor) return "";
const misses = [];
if (Number(result.down) < higher.minDown) misses.push("download");
if (Number(result.up) < higher.minUp) misses.push("upload");
if (Number(result.latency) > higher.maxLatency) misses.push("the round trip");
if (!misses.length) return "";
return `One rung up wanted a little more from ${joinAnd(misses)}.`;
}
export function formatRate(mbps) {
if (!Number.isFinite(mbps)) return { text: "—", unit: "Mbps" };
if (mbps >= 1000) {
const gbps = mbps / 1000;
return { text: gbps >= 10 ? gbps.toFixed(0) : gbps.toFixed(1), unit: "Gbps" };
}
if (mbps >= 100) {
return { text: Math.round(mbps).toLocaleString("en-US"), unit: "Mbps" };
}
return { text: mbps.toFixed(1), unit: "Mbps" };
}
export function formatMs(ms) {
if (!Number.isFinite(ms)) return "—";
if (ms < 10) return ms.toFixed(1);
return Math.round(ms).toLocaleString("en-US");
}
export function formatMoved(bytes) {
if (!Number.isFinite(bytes) || bytes < 0) return "0 MB";
const mb = bytes / 1e6;
if (mb >= 10) return `${Math.round(mb)} MB`;
if (mb >= 0.1) return `${mb.toFixed(1)} MB`;
return `${Math.max(1, Math.round(bytes / 1e3))} KB`;
}
function joinAnd(items) {
if (items.length === 1) return items[0];
if (items.length === 2) return `${items[0]} and ${items[1]}`;
return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`;
}
public/js/speedtest.js
/**
* Browser speed check against this site's own origin.
*
* Download reads /assets/test-blob.bin (incompressible, generated, not committed).
* Upload POSTs random bytes to /api/upload, which reads and discards them.
* Latency is the median of small HTTP round trips to /assets/ping.txt.
*
* Nothing here looks up an address, a place, or a third-party host.
*/
const DOWNLOAD_URL = "/assets/test-blob.bin";
const UPLOAD_URL = "/api/upload";
const PING_URL = "/assets/ping.txt";
const PING_SAMPLES = 6;
const DOWNLOAD_MS = 4500;
const DOWNLOAD_MAX_BYTES = 32 * 1024 * 1024;
const UPLOAD_MS = 4000;
const UPLOAD_MAX_BYTES = 16 * 1024 * 1024;
const DOWNLOAD_PARALLEL = 3;
const UPLOAD_PARALLEL = 2;
const UPLOAD_CHUNK = 1024 * 1024;
const MIN_BYTES = 8 * 1024;
export function mbps(bytes, elapsedMs) {
if (!Number.isFinite(bytes) || !Number.isFinite(elapsedMs) || elapsedMs <= 0) return 0;
return (bytes * 8) / (elapsedMs / 1000) / 1e6;
}
export function median(values) {
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
if (sorted.length === 0) return 0;
if (sorted.length % 2) return sorted[mid];
return (sorted[mid - 1] + sorted[mid]) / 2;
}
function throwIfAborted(signal) {
if (signal?.aborted) {
throw new DOMException("Aborted", "AbortError");
}
}
function delay(ms, signal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
};
if (signal?.aborted) {
onAbort();
return;
}
signal?.addEventListener("abort", onAbort, { once: true });
});
}
async function discard(response, maxMs, maxBytes) {
if (!response.body) {
await response.arrayBuffer();
return;
}
const reader = response.body.getReader();
const started = performance.now();
let bytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.byteLength;
if (performance.now() - started >= maxMs || bytes >= maxBytes) break;
}
} finally {
try {
await reader.cancel();
} catch {
/* The stream may already be closed. */
}
}
}
export async function measurePing({ signal, onSample }) {
throwIfAborted(signal);
const warmup = await fetch(PING_URL, { cache: "no-store", signal });
await warmup.arrayBuffer();
const samples = [];
for (let i = 0; i < PING_SAMPLES; i += 1) {
throwIfAborted(signal);
const started = performance.now();
const response = await fetch(PING_URL, { cache: "no-store", signal });
if (!response.ok) {
throw new Error(`Latency check failed (${response.status})`);
}
await response.arrayBuffer();
const sample = performance.now() - started;
samples.push(sample);
onSample?.({ sample, index: i, total: PING_SAMPLES });
if (i < PING_SAMPLES - 1) await delay(40, signal);
}
const latencyMs = median(samples);
const jitterMs = samples.reduce((sum, value) => sum + Math.abs(value - latencyMs), 0) / samples.length;
return { latencyMs, jitterMs, samples };
}
async function pumpDownload({ signal, durationMs, maxBytes, parallel, onProgress, countBytes }) {
let bytes = 0;
let stop = false;
const started = performance.now();
async function worker() {
while (!stop) {
throwIfAborted(signal);
const response = await fetch(DOWNLOAD_URL, { cache: "no-store", signal });
if (!response.ok || !response.body) {
throw new Error(`Download failed (${response.status})`);
}
const reader = response.body.getReader();
let got = 0;
try {
while (!stop) {
const { done, value } = await reader.read();
if (done) break;
got += value.byteLength;
bytes += value.byteLength;
const elapsed = performance.now() - started;
if (countBytes) onProgress?.({ bytes, elapsed });
if (elapsed >= durationMs || bytes >= maxBytes) {
stop = true;
break;
}
}
} finally {
try {
await reader.cancel();
} catch {
/* Already closed. */
}
}
if (got === 0 && !stop) throw new Error("Download failed (empty)");
}
}
await Promise.all(Array.from({ length: parallel }, () => worker()));
const elapsed = Math.max(1, performance.now() - started);
return { bytes, elapsedMs: elapsed, mbps: mbps(bytes, elapsed) };
}
export async function measureDownload({ signal, onProgress }) {
await pumpDownload({
signal,
durationMs: 400,
maxBytes: 256 * 1024,
parallel: 1,
countBytes: false,
});
return pumpDownload({
signal,
durationMs: DOWNLOAD_MS,
maxBytes: DOWNLOAD_MAX_BYTES,
parallel: DOWNLOAD_PARALLEL,
onProgress,
countBytes: true,
});
}
function randomPayload(size) {
const buffer = new Uint8Array(size);
const stride = 65536;
for (let offset = 0; offset < size; offset += stride) {
crypto.getRandomValues(buffer.subarray(offset, Math.min(size, offset + stride)));
}
return buffer;
}
async function pumpUpload({ signal, durationMs, maxBytes, parallel, chunkBytes, onProgress }) {
const payloads = Array.from({ length: parallel }, () => randomPayload(chunkBytes));
let bytes = 0;
let stop = false;
const started = performance.now();
async function worker(payload) {
while (!stop) {
throwIfAborted(signal);
const response = await fetch(UPLOAD_URL, {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/octet-stream" },
body: payload,
signal,
});
if (response.status !== 204 && !response.ok) {
const error = new Error(`Upload failed (${response.status})`);
error.status = response.status;
throw error;
}
try {
await response.arrayBuffer();
} catch {
/* A 204 has nothing to read. */
}
bytes += payload.byteLength;
const elapsed = performance.now() - started;
onProgress?.({ bytes, elapsed });
if (elapsed >= durationMs || bytes >= maxBytes) stop = true;
}
}
await Promise.all(payloads.map((payload) => worker(payload)));
const elapsed = Math.max(1, performance.now() - started);
return { bytes, elapsedMs: elapsed, mbps: mbps(bytes, elapsed) };
}
export async function measureUpload({ signal, onProgress }) {
try {
return await pumpUpload({
signal,
durationMs: UPLOAD_MS,
maxBytes: UPLOAD_MAX_BYTES,
parallel: UPLOAD_PARALLEL,
chunkBytes: UPLOAD_CHUNK,
onProgress,
});
} catch (error) {
if (error.name === "AbortError" || error.status === 404 || error.status === 405) throw error;
return pumpUpload({
signal,
durationMs: UPLOAD_MS,
maxBytes: UPLOAD_MAX_BYTES,
parallel: 1,
chunkBytes: 256 * 1024,
onProgress,
});
}
}
export async function runSpeedTest({ signal, onProgress }) {
onProgress?.({ phase: "ping" });
const ping = await measurePing({
signal,
onSample: (sample) => onProgress?.({ phase: "ping", ...sample }),
});
onProgress?.({ phase: "download", mbps: 0, fraction: 0 });
const down = await measureDownload({
signal,
onProgress: ({ bytes, elapsed }) => {
onProgress?.({
phase: "download",
mbps: mbps(bytes, elapsed),
fraction: Math.min(1, elapsed / DOWNLOAD_MS, bytes / DOWNLOAD_MAX_BYTES),
});
},
});
if (down.bytes < MIN_BYTES) {
throw new Error("Not enough data arrived to grade the download.");
}
onProgress?.({ phase: "upload", mbps: 0, fraction: 0 });
const up = await measureUpload({
signal,
onProgress: ({ bytes, elapsed }) => {
onProgress?.({
phase: "upload",
mbps: mbps(bytes, elapsed),
fraction: Math.min(1, elapsed / UPLOAD_MS, bytes / UPLOAD_MAX_BYTES),
});
},
});
if (up.bytes < MIN_BYTES) {
throw new Error("Not enough data was accepted to grade the upload.");
}
return {
down: down.mbps,
up: up.mbps,
latency: ping.latencyMs,
jitter: ping.jitterMs,
downBytes: down.bytes,
upBytes: up.bytes,
};
}
public/js/app.js
import { classify, formatMs } from "./thresholds.js";
import { runSpeedTest } from "./speedtest.js";
const HISTORY_KEY = "howsmywifi.history.v1";
const HISTORY_LIMIT = 5;
const statusEl = document.querySelector("#status");
const downValue = document.querySelector("#down-value");
const upValue = document.querySelector("#up-value");
const upUnit = document.querySelector("#up-unit");
const pingValue = document.querySelector("#ping-value");
const verdict = document.querySelector("#verdict");
const verdictName = document.querySelector("#verdict-name");
const verdictBlurb = document.querySelector("#verdict-blurb");
const again = document.querySelector("#again");
const more = document.querySelector("#more");
const details = document.querySelector("#details");
const shareText = document.querySelector("#share-text");
const copyButton = document.querySelector("#copy");
const nativeShare = document.querySelector("#native-share");
const PHASE_STATUS = {
ping: "Measuring ping…",
download: "Testing download speed…",
upload: "Testing upload speed…",
};
let activeController = null;
let copyTimer = 0;
let lastPhase = "";
if (navigator.share) nativeShare.hidden = false;
wireShare();
wireMore();
again.addEventListener("click", () => {
window.scrollTo({ top: 0, behavior: "smooth" });
start();
});
start();
function start() {
activeController?.abort();
const controller = new AbortController();
activeController = controller;
const timer = setTimeout(() => controller.abort("timeout"), 45000);
setRunning();
runSpeedTest({
signal: controller.signal,
onProgress: (update) => {
if (controller.signal.aborted) return;
paintProgress(update);
},
})
.then((result) => {
if (controller !== activeController) return;
showResult(result);
})
.catch((error) => {
if (controller !== activeController) return;
if (error?.name === "AbortError") {
showError(
controller.signal.reason === "timeout"
? "The test took too long and stopped. Try again."
: "The test stopped.",
);
return;
}
showError(messageFor(error));
})
.finally(() => {
clearTimeout(timer);
});
}
function setRunning() {
document.body.dataset.state = "running";
delete document.body.dataset.band;
document.body.setAttribute("aria-busy", "true");
collapseDetails();
verdict.hidden = true;
verdict.dataset.band = "pending";
delete verdict.dataset.tier;
verdictName.textContent = "";
verdictBlurb.textContent = "";
downValue.textContent = "—";
upValue.textContent = "—";
upUnit.textContent = "Mbps";
pingValue.textContent = "—";
setShareReady("");
lastPhase = "";
statusEl.textContent = "Starting the test…";
document.title = "How's My Wi-Fi?";
}
function collapseDetails() {
details.hidden = true;
more.hidden = true;
more.setAttribute("aria-expanded", "false");
more.textContent = "Show more info";
}
function notePhase(phase) {
if (phase === lastPhase) return;
lastPhase = phase;
const line = PHASE_STATUS[phase];
if (line && document.body.dataset.state === "running") statusEl.textContent = line;
}
function paintProgress(update) {
if (update.phase === "ping") {
notePhase("ping");
return;
}
if (update.phase === "download") {
notePhase("download");
downValue.textContent = formatMbps(update.mbps || 0);
return;
}
if (update.phase === "upload") {
notePhase("upload");
upValue.textContent = formatMbps(update.mbps || 0);
}
}
function showResult(result) {
const tier = classify(result);
document.body.dataset.state = "done";
document.body.dataset.band = tier.band;
document.body.setAttribute("aria-busy", "false");
verdict.hidden = false;
verdict.dataset.band = tier.band;
verdict.dataset.tier = tier.id;
verdictName.textContent = tier.name;
verdictBlurb.textContent = tier.blurb;
downValue.textContent = formatMbps(result.down);
upValue.textContent = formatMbps(result.up);
pingValue.textContent = formatMs(result.latency);
more.hidden = false;
statusEl.textContent = tier.name;
setShareReady(tier.share);
document.title = `${tier.name} · How's My Wi-Fi?`;
remember(result, tier);
}
function showError(message) {
document.body.dataset.state = "error";
document.body.dataset.band = "red";
document.body.setAttribute("aria-busy", "false");
verdict.hidden = false;
verdict.dataset.band = "red";
verdict.dataset.tier = "poor";
verdictName.textContent = "Poor";
verdictBlurb.textContent = message;
more.hidden = false;
statusEl.textContent = message;
setShareReady("");
}
function messageFor(error) {
const text = String(error?.message || error || "");
if (text.includes("Upload failed (404)") || text.includes("Upload failed (405)")) {
return "The upload check needs the discard endpoint. Locally, start the site with node server.mjs. On Cloudflare Pages, deploy the functions folder with the site.";
}
if (text.includes("Download failed (404)")) {
return "The test file is missing. Run node scripts/generate-test-blob.mjs, then reload.";
}
if (text.includes("Not enough data")) return text;
return "The test did not finish. Check the connection and try again.";
}
function formatMbps(mbps) {
if (!Number.isFinite(mbps)) return "—";
if (mbps >= 100) return Math.round(mbps).toLocaleString("en-US");
if (mbps >= 10) return mbps.toFixed(0);
return mbps.toFixed(1);
}
function wireMore() {
more.addEventListener("click", () => {
const open = details.hidden;
details.hidden = !open;
more.setAttribute("aria-expanded", String(open));
more.textContent = open ? "Show less info" : "Show more info";
if (open) details.scrollIntoView({ behavior: "smooth", block: "start" });
});
}
function setShareReady(text) {
shareText.value = text;
const ready = Boolean(text);
copyButton.disabled = !ready;
nativeShare.disabled = !ready;
}
function wireShare() {
copyButton.addEventListener("click", async () => {
const text = shareText.value;
if (!text) return;
let copied = false;
try {
await navigator.clipboard.writeText(text);
copied = true;
} catch {
shareText.focus();
shareText.select();
try {
copied = document.execCommand("copy");
} catch {
copied = false;
}
}
copyButton.textContent = copied ? "Copied" : "Select the line and copy";
window.clearTimeout(copyTimer);
copyTimer = window.setTimeout(() => {
copyButton.textContent = "Copy Link";
}, 2000);
});
nativeShare.addEventListener("click", async () => {
if (!shareText.value || !navigator.share) return;
try {
await navigator.share({ text: shareText.value });
} catch (error) {
if (error?.name !== "AbortError") copyButton.click();
}
});
}
function remember(result, tier) {
try {
const history = loadHistory();
history.unshift({
at: new Date().toISOString(),
tier: tier.id,
down: Math.round(result.down * 10) / 10,
up: Math.round(result.up * 10) / 10,
latency: Math.round(result.latency * 10) / 10,
jitter: Math.round(result.jitter * 10) / 10,
});
localStorage.setItem(HISTORY_KEY, JSON.stringify(history.slice(0, HISTORY_LIMIT)));
} catch {
/* Private mode can refuse storage. The result still shows. */
}
}
function loadHistory() {
try {
const parsed = JSON.parse(localStorage.getItem(HISTORY_KEY) || "[]");
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
public/js/codepage.js
import { TIERS } from "./thresholds.js";
const tbody = document.querySelector("#tier-rows");
for (const tier of TIERS) {
const row = document.createElement("tr");
const cells = tier.floor
? [tier.name, tier.bandLabel, "Below Slow", "Below Slow", "Below Slow"]
: [
tier.name,
tier.bandLabel,
`≥ ${tier.minDown} Mbps`,
`≥ ${tier.minUp} Mbps`,
`≤ ${tier.maxLatency} ms`,
];
for (const text of cells) {
const cell = document.createElement("td");
cell.textContent = text;
row.append(cell);
}
row.dataset.band = tier.band;
tbody.append(row);
}
functions/api/upload.js
/**
* Cloudflare Pages Function for the upload half of the speed check.
*
* The browser POSTs a random body. We read it so the upload actually
* finishes, then we drop it. Nothing is logged, stored, or forwarded.
* Same-origin only, so another website cannot use this as a sink.
*/
export async function onRequestPost({ request }) {
if (!sameOrigin(request)) {
return new Response("Same-origin only.", {
status: 403,
headers: { "Cache-Control": "no-store" },
});
}
try {
await request.arrayBuffer();
} catch {
return new Response("The upload could not be read.", {
status: 400,
headers: { "Cache-Control": "no-store" },
});
}
return new Response(null, {
status: 204,
headers: { "Cache-Control": "no-store" },
});
}
function sameOrigin(request) {
const origin = request.headers.get("Origin");
if (!origin) return true;
const host = request.headers.get("Host");
if (!host) return false;
try {
return new URL(origin).host === host;
} catch {
return false;
}
}
scripts/generate-test-blob.mjs
/**
* Writes an incompressible test file. Random bytes barely compress, so a
* gzip-happy host cannot pretend the line is faster than it is.
*
* The file is gitignored. Local `node server.mjs` creates it on startup.
* Cloudflare Pages should use this script as the build command.
*
* node scripts/generate-test-blob.mjs
* node scripts/generate-test-blob.mjs public/assets/test-blob.bin
*/
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
export const BLOB_BYTES = 16 * 1024 * 1024;
export function generateTestBlob(dest, bytes = BLOB_BYTES) {
fs.mkdirSync(path.dirname(dest), { recursive: true });
const fd = fs.openSync(dest, "w");
try {
let left = bytes;
while (left > 0) {
const size = Math.min(left, 1024 * 1024);
fs.writeSync(fd, crypto.randomBytes(size));
left -= size;
}
} finally {
fs.closeSync(fd);
}
return dest;
}
function defaultDest() {
return path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "public", "assets", "test-blob.bin");
}
const invokedDirectly =
process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (invokedDirectly) {
const dest = path.resolve(process.argv[2] || defaultDest());
generateTestBlob(dest);
const size = fs.statSync(dest).size;
console.log(`Wrote ${dest} (${size} bytes)`);
}