How this page was checked: The Worker's fetch(request, env, ctx) was executed unchanged on Node 24 against the in-memory API, with a Map-backed stand-in for caches.default and a collector for ctx.waitUntil: the responses, the single upstream call for three spellings of the sign, the 400/404 paths and the missing-secret 401 are from that run. Not run: wrangler, the Workers runtime itself and Cloudflare's real cache.
The key is a secret binding, not a variable
Workers have no process.env by default. Configuration reaches your code as bindings on the env argument of fetch, and there are two kinds: [vars] in wrangler.toml, which are plain text, committed with the file and visible in the dashboard, and secrets, which are encrypted and never printed back. The API key is a secret:
npx wrangler secret put ASTRONODE_API_KEY # prompts for the value; it is stored on the deployed Worker, not in any file
wrangler.toml - only non-secret settings live here:
name = "horoscope"
main = "src/index.ts"
compatibility_date = "2026-12-01"
routes = [{ pattern = "horoscope.example.com", custom_domain = true }]For wrangler dev, put ASTRONODE_API_KEY=aie_test_... in a .dev.vars file next to wrangler.toml and add .dev.vars to .gitignore - it is the local stand-in for secrets and holds the same value in plain text. npx wrangler types generates the Env and ExecutionContext types the Worker below uses.
The Worker
src/index.ts:
interface Env {
ASTRONODE_API_KEY: string;
ASTRONODE_BASE_URL?: string;
}
const SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"];
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
const slug = url.pathname.match(/^\/horoscope\/([a-z]+)$/i)?.[1].toLowerCase();
const sign = SIGNS.find((s) => s.toLowerCase() === slug);
if (!sign) return Response.json({ error: "unknown sign" }, { status: 404 });
const date = url.searchParams.get("date") ?? new Date().toISOString().slice(0, 10);
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return Response.json({ error: "date must be YYYY-MM-DD" }, { status: 400 });
// One cache entry per sign per day - the key is ours, not the client's URL.
const cacheKey = new Request(`https://horoscope.internal/${sign}/${date}`);
const cache = caches.default;
const hit = await cache.match(cacheKey);
if (hit) return hit;
const base = env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";
const upstream = await fetch(`${base}/v1/horoscope/daily/${sign}?date=${date}`, {
headers: { Authorization: `Bearer ${env.ASTRONODE_API_KEY}` },
});
const json = (await upstream.json()) as any;
if (!upstream.ok) {
console.log("astronode", upstream.status, json.error.code);
return Response.json({ error: "upstream" }, { status: 502 });
}
const { summary, focus_areas, cautions } = json.data;
const response = Response.json(
{ sign, date, summary, focus_areas, cautions },
{ headers: { "Cache-Control": "public, max-age=86400" } },
);
ctx.waitUntil(cache.put(cacheKey, response.clone()));
return response;
},
};- Normalise the sign before anything else. The API's path parameter is an enum of the twelve capitalised names; sent
leo, it answers400 VALIDATION_ERRORlisting them. Normalising first also means/horoscope/leo,/horoscope/Leoand/horoscope/LEOshare one cache entry - in the run, those three requests made one AstroNode call. - Build the cache key yourself. Caching on
request.urlwould store a separate copy for every query-string variation a client invents. The synthetichoroscope.internalURL is never fetched; it only names the entry. - `ctx.waitUntil(cache.put(...))` lets the response go to the reader while the cache write finishes.
response.clone()is required because a body can be read only once. - Only successes are cached. Errors return before
cache.put, so a bad key or a brief upstream failure is not served for a day.
What it returned
GET /horoscope/leo?date=2026-12-05 (first request a cache miss, the next two hits):
{
"sign": "Leo",
"date": "2026-12-05",
"summary": "The Moon is in your house of home, roots and inner peace - it rules this house, so the pull inward is strong and worth honouring. Saturday is Saturn's day: slow, patient work pays, and shortcuts rarely do.",
"focus_areas": ["Home, mother, and the people you don't perform for", "Rest without guilt", "Fixing something domestic"],
"cautions": ["Withdrawing from something you actually need to face", "Nostalgia standing in for a decision"]
}The date is explicit for a reason. Without ?date= the Worker uses the UTC date, which flips at 05:30 in India and at 19:00 in New York (EST). If your readers are in one zone, compute the date in that zone and pass it; the API returns the reading for exactly the date you ask for, so the cache entry can never outlive its day. GET /v1/horoscope/daily/:sign is on the Free plan.
Workers limits that matter here
- CPU time, not wall time. The Free plan allows 10 ms of CPU per request. Waiting for AstroNode's response is I/O and does not count, so this Worker sits far inside the limit; parsing a very large JSON body would not.
- Subrequests per invocation are capped (50 on the Free plan). One horoscope is one subrequest; a page that fans out to all twelve signs in a single request is twelve - fine, but loops over dates add up quickly.
- The cache is per data centre.
caches.defaultis not replicated: a reader in Mumbai and one in Frankfurt each cause one AstroNode call per sign per day. That is still a tiny number, but do not size your quota on "one call per day". - Test caching on your own domain. Cache API calls have no effect in the dashboard's preview editor, and Cloudflare documents the Cache API for Workers on a zone you own - hence the
custom_domainroute inwrangler.toml. A Worker that seems never to cache is often being tested onworkers.dev.
The mistake that bites first: a secret on the wrong environment
Wrangler environments are separate Workers. wrangler deploy --env production deploys horoscope-production, which does not inherit the secret you set with a bare wrangler secret put. The binding is then undefined, the template string sends Authorization: Bearer undefined, and AstroNode answers - from the run with no secret bound:
HTTP 401
{ "error": { "code": "UNAUTHORIZED", "message": "Invalid API key" } }Set the secret per environment (npx wrangler secret put ASTRONODE_API_KEY --env production), and keep the upstream status in your logs, as the Worker above does with console.log, so a 502 at the edge can be traced to a 401 behind it. Never move the key into [vars] to "make it work" - that commits it to the repository.
Questions
- Which AstroNode endpoints does the Cloudflare Workers example call?
- 1 endpoint: Daily Sun Sign Horoscope (
GET /v1/horoscope/daily/:sign). - Was the Cloudflare Workers code on this page actually run?
- The Worker's
fetch(request, env, ctx)was executed unchanged on Node 24 against the in-memory API, with a Map-backed stand-in forcaches.defaultand a collector forctx.waitUntil: the responses, the single upstream call for three spellings of the sign, the 400/404 paths and the missing-secret 401 are from that run. Not run:wrangler, the Workers runtime itself and Cloudflare's real cache.