Summary

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


1. How to Rename the Worker

Renaming the worker requires modifying the configuration and redeploying.

Step-by-Step

  1. 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",
      ...
    }
    
  2. Deploy the Renamed Worker:
    From the cf-speedTest-wkr directory:

    npm run deploy
    

    Wrangler will register and deploy the new worker at:
    https://your-new-worker-name.adsviser.workers.dev

  3. Update Frontend API Endpoint:
    Open archAive/.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);
    
Deleting the Old Worker

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.

  1. 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
        }
      ],
      ...
    }
    
  2. Deploy:
    npm run deploy
    
    Cloudflare automatically configures the DNS record in your zone and provisions edge TLS certificates.
  3. 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)

Option B: Standard Worker Secret (Alternative)

If you prefer managing the secret directly per-worker via CLI without using Secrets Store:

  1. Run:
    npx wrangler secret put PAGESPEED_API_KEY
    
    (Paste your Google PageSpeed API key when prompted).
  2. Remove the secrets_store_secrets block from wrangler.jsonc and run npm 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 }));

Clearing or Invalidating Cached Results


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