A Cloudflare Worker that serves random background images from Unsplash with KV-based caching. Built with Hono.
GET /api/background?tags=mountain,fog fetches 30 photos from Unsplash for the given tags, caches the pool in Cloudflare KV for 3 days, then returns one random photo on each request.
Response:
{
"url": "https://images.unsplash.com/photo-...?w=3840&q=90&fm=jpg&fit=crop",
"location": "Dolomites, Italy",
"photographer": "John Doe",
"photographerUrl": "https://unsplash.com/@johndoe"
}
tags defaults to landscape,forest,mountain,fog,nature view when omitted.
From the monorepo root:
pnpm install
Create apps/api/.dev.vars:
UNSPLASH_ACCESS_KEY=your_unsplash_access_key
Get a free key at unsplash.com/developers → create an app → copy the Access Key.
cd apps/api
pnpm dev
# Worker runs at http://localhost:8787
Test it:
curl "http://localhost:8787/api/background?tags=mountain"
pnpm typecheck
The API deploys to Cloudflare Workers via GitHub Actions on every api@* tag push.
Requires Cloudflare credentials in your environment:
export CLOUDFLARE_API_TOKEN=your_token
export CLOUDFLARE_ACCOUNT_ID=your_account_id
cd apps/api
pnpm deploy
CLOUDFLARE_API_TOKENCLOUDFLARE_ACCOUNT_IDgit tag api@1.0.6
git push origin api@1.0.6
GitHub Actions runs .github/workflows/deploy-api.yml, which runs pnpm nx deploy api.
wrangler.toml — Cloudflare Worker config:
name = "hub-api"
compatibility_date = "2024-03-20"
[[kv_namespaces]]
binding = "UNSPLASH_CACHE"
id = "<production-kv-id>"
preview_id = "<dev-kv-id>"
The KV namespace IDs point to Cloudflare KV stores used to cache image pools. Update these if you fork the project.
| Tool | Purpose |
|---|---|
| Hono | Web framework |
| Cloudflare Workers | Serverless runtime |
| Cloudflare KV | Image pool cache |
| Wrangler | CLI and dev server |
| TypeScript | Language |