Complete operational guide and customization reference for the Cloudflare Worker (adsvise-speed-test) located at archAive/.www/WP/cf-speedTest-wkr.
It securely interfaces with the Google PageSpeed Insights API using keys managed in Cloudflare Secrets Store, minimizes payload sizes from ~400KB down to ~200 bytes, and caches audit results in Cloudflare KV to deliver sub-200ms cached responses.
Current Worker State
- Worker Name:
adsvise-speed-test - Live Endpoint:
https://adsvise-speed-test.adsviser.workers.dev - KV Namespace ID (
pagespeed-cache):a631f67ed3954600916ddcdb7c7029bf - Secrets Store ID (
default_secrets_store):c61bd4eecad74b8e978d31ca9e0c5317 - Frontend Consumer:
archAive/.www/adsvise.me/pagespeed-results/index.html
1. How to Rename the Worker
Renaming the worker requires modifying the configuration and redeploying.
Step-by-Step
-
Update
wrangler.jsonc:
Change the"name"property to your preferred identifier:{ "$schema": "node_modules/wrangler/config-schema.json", "name": "your-new-worker-name", "main": "src/index.ts", ... } -
Deploy the Renamed Worker:
From thecf-speedTest-wkrdirectory:npm run deployWrangler will register and deploy the new worker at:
https://your-new-worker-name.adsviser.workers.dev -
Update Frontend API Endpoint:
OpenarchAive/.www/adsvise.me/pagespeed-results/index.html(around line 2130) and update the fetch destination:const cfWorkerUrl = "https://your-new-worker-name.adsviser.workers.dev/?url=" + encodeURIComponent(leadData.url);
Cloudflare treats a name change as a new deployment. The previous worker (adsvise-speed-test) will remain active on your Cloudflare account until deleted.
To cleanly remove the legacy worker:
npx wrangler delete --name adsvise-speed-test
Or delete it directly from Cloudflare Dashboard → Workers & Pages → adsvise-speed-test → Manage → Delete.
2. Setting Up a Custom Domain (e.g. speed.adsvise.me)
Instead of routing traffic through *.workers.dev, you can attach the worker directly to your custom domain. This eliminates third-party worker subdomains, provides cleaner branding, and optimizes edge SSL routing.
- Add Custom Domain in
wrangler.jsonc:
Add a"routes"configuration block:{ "name": "adsvise-speed-test", "main": "src/index.ts", "compatibility_date": "2026-02-19", "routes": [ { "pattern": "speed.adsvise.me/*", "custom_domain": true } ], ... } - Deploy:
Cloudflare automatically configures the DNS record in your zone and provisions edge TLS certificates.npm run deploy - Update Frontend:
const cfWorkerUrl = "https://speed.adsvise.me/?url=" + encodeURIComponent(leadData.url);
3. Managing API Keys & Secrets
The worker supports a hybrid secret resolution system in src/index.ts. It dynamically resolves credentials whether they come from Cloudflare Secrets Store, standard Worker Secrets, or local .dev.vars.
const apiKey =
typeof env.PAGESPEED_API_KEY === 'string'
? env.PAGESPEED_API_KEY
: typeof (env.PAGESPEED_API_KEY as any)?.get === 'function'
? await env.PAGESPEED_API_KEY.get()
: null;
Option A: Cloudflare Secrets Store (Current)
- Bound in
wrangler.jsoncviasecrets_store_secrets:"secrets_store_secrets": [ { "binding": "PAGESPEED_API_KEY", "store_id": "c61bd4eecad74b8e978d31ca9e0c5317", "secret_name": "PAGESPEED_API_KEY" } ] - To update/rotate the key: Navigate to Cloudflare Dashboard → Storage & Databases → Secrets Store → default_secrets_store and edit the value for
PAGESPEED_API_KEY. No redeploy is needed.
Option B: Standard Worker Secret (Alternative)
If you prefer managing the secret directly per-worker via CLI without using Secrets Store:
- Run:
(Paste your Google PageSpeed API key when prompted).npx wrangler secret put PAGESPEED_API_KEY - Remove the
secrets_store_secretsblock fromwrangler.jsoncand runnpm run deploy.
Option C: Local Development Testing
For local testing via npm run dev, credentials are read from .dev.vars (excluded from git):
PAGESPEED_API_KEY=AIzaSy...your_key_here
4. Customizing the KV Cache
Google PageSpeed Lighthouse mobile audits take 15–35 seconds. The KV cache allows any subsequent request within the TTL window to return in under 200ms (X-Cache: HIT).
Changing Cache Expiration (TTL)
In src/index.ts, locate the cache storage line (around line 132):
// Default: 24 hours (86,400 seconds)
ctx.waitUntil(env.PAGESPEED_CACHE.put(cacheKey, jsonResponse, { expirationTtl: 86400 }));
- 3 Days:
expirationTtl: 259200 - 7 Days:
expirationTtl: 604800 - 30 Days:
expirationTtl: 2592000
Clearing or Invalidating Cached Results
- Purge a specific site:
npx wrangler kv key delete --binding PAGESPEED_CACHE "pagespeed:https://www.example.com/" - Nuclear cache reset:
Create a fresh namespace and updateidinwrangler.jsonc:
Replacenpx wrangler kv namespace create pagespeed-cache-v2"id": "..."under"kv_namespaces"with the new namespace ID and redeploy.
5. Security & Rate Limiting Customizations
1. Restricting CORS Origins
Currently, the worker permits all origins (*) for public testing. In production, lock this down to your own domain in src/index.ts:
const ALLOWED_ORIGINS = ['https://adsvise.me', 'https://www.adsvise.me', 'http://localhost:8080'];
function getCorsHeaders(request: Request) {
const origin = request.headers.get('Origin') || '';
const allowOrigin = ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0];
return {
'Access-Control-Allow-Origin': allowOrigin,
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};
}
2. Rate Limiting Protection
To prevent bots from exhausting your Google PageSpeed API quota on cache misses, bind Cloudflare Rate Limiting in wrangler.jsonc:
"unsafe": {
"bindings": [
{
"name": "RATE_LIMITER",
"type": "ratelimit",
"namespace_id": "1001",
"simple": { "limit": 10, "period": 60 }
}
]
}
6. Code Customizations: Metrics & Strategies
Adding Desktop Audits Support
By default, the worker requests &strategy=mobile. To allow callers to choose between mobile and desktop:
const requestedStrategy = url.searchParams.get('strategy') === 'desktop' ? 'desktop' : 'mobile';
const cacheKey = `pagespeed:${requestedStrategy}:${siteUrl}`;
const apiEndpoint = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(siteUrl)}&key=${apiKey}&strategy=${requestedStrategy}`;
Extracting Additional Web Vitals
In src/index.ts, you can extract more metrics from audits:
// Cumulative Layout Shift (CLS)
const clsScore = audits?.['cumulative-layout-shift']?.numericValue ?? 0;
// Total Blocking Time (TBT in ms)
const tbtMs = audits?.['total-blocking-time']?.numericValue ?? 0;
// First Contentful Paint (FCP in seconds)
const fcpSeconds = ((audits?.['first-contentful-paint']?.numericValue ?? 0) / 1000).toFixed(1);
7. Developer Cheatsheet
| Command | Action |
|---|---|
npm run dev | Run local development server at http://localhost:8787 |
npm test | Run Vitest unit & integration test suites |
npm run deploy | Build and deploy changes to Cloudflare edge |
npx wrangler tail | Stream live real-time HTTP traffic and console logs |
npx wrangler kv key list --binding PAGESPEED_CACHE | List all cached URLs currently stored in KV |