Fi Worker – Cloudflare Workers Proxy & Dashboard for the TryFi Pet Tracker
Project Overview
Fi Worker is a Cloudflare‑based backend + frontend that turns the TryFi pet‑tracker GraphQL API into a clean, REST‑style service and a ready‑made dashboard.
The worker runs on Cloudflare Workers using the Hono framework, stores authentication cookies in KV, and archives location points in a D1 SQLite database.
An Astro application hosted on Cloudflare Pages consumes the REST endpoints to display real‑time maps, activity charts, and device health information.
Why does this matter?
TryFi’s native GraphQL API is powerful but requires custom query construction, OAuth handling, and manual pagination. Fi Worker abstracts those details away, giving developers a familiar REST surface and a UI that can be deployed in minutes. It also adds historical location storage—something the upstream API does not provide out of the box.
Key Features
| Feature | What it provides |
|---|---|
| REST API proxy | Simple endpoints (/api/pets, /api/pets/:id/location, etc.) that internally translate to GraphQL calls. |
| Real‑time pet location | /api/pets/:id/location returns latitude, longitude and a reverse‑geocoded place name. |
| Activity & rest stats | Daily, weekly and monthly step counts, distance, and sleep periods via /api/pets/:id/activity and /api/pets/:id/rest. |
| Walk history | Paginated walk routes with polyline data at /api/pets/:id/walks. |
| Device information | Battery level, temperature, signal strength, firmware version and LED colour control via /api/pets/:id/device. |
| Lost‑dog mode | Toggle high‑frequency tracking with /api/pets/:id/lost-mode. |
| Historical location storage | A cron job stores a snapshot every 5 minutes in D1, enabling custom history visualisations. |
| Cookie‑based session management | TryFi session cookies are kept securely in Cloudflare KV, eliminating server‑side state. |
Architecture Overview
+-------------------+ +-------------------+ +-------------------+
| Browser / UI | HTTPS | Cloudflare Pages | HTTPS | Cloudflare Worker |
| (Astro Dashboard)| <------> | (fi-web) | <------> | (fi-worker) |
+-------------------+ +-------------------+ +-------------------+
| |
| KV (session cookies)
| D1 (location history)
v v
+-------------------+ +-------------------+
| TryFi GraphQL | | External APIs |
| (api.tryfi.com) | | (maps, etc.) |
+-------------------+ +-------------------+The diagram shows the flow from the user’s browser to the Astro frontend, then to the Hono‑based Worker, which talks to TryFi’s GraphQL endpoint while persisting session data in KV and location snapshots in D1.
How It Works
1. Hono REST API
The worker is a small Hono app that defines the public REST surface.
Each route calls a helper in src/tryfi-client.ts, which hides the GraphQL details.
// src/index.ts
import { Hono } from 'hono';
import { getPetLocation } from './tryfi-client';
const app = new Hono();
// Health check
app.get('/health', (c) => c.text('OK'));
// GET /api/pets/:id/location → returns the latest coordinates
app.get('/api/pets/:id/location', async (c) => {
const petId = c.req.param('id');
const location = await getPetLocation(petId);
return c.json(location);
});
export default app;Note: All other endpoints (
/activity,/walks,/device, …) follow the same pattern – a thin handler that forwards the request to the GraphQL client and returns JSON.
2. TryFi GraphQL Client
src/tryfi-client.ts holds a single GraphQLClient instance.
Authentication with TryFi is cookie‑based, so the client injects the stored session cookie on every request.
// src/tryfi-client.ts
import { GraphQLClient, gql } from 'graphql-request';
import { getSessionCookie } from './kv';
const endpoint = 'https://api.tryfi.com/graphql';
/**
* Returns a GraphQLClient that includes the TryFi session cookie.
*/
async function createClient(): Promise<GraphQLClient> {
const cookie = await getSessionCookie(); // reads from KV
return new GraphQLClient(endpoint, {
headers: {
cookie, // e.g. "session=abc123"
},
});
}
/** Query for a pet's current location */
const LOCATION_QUERY = gql`
query GetPetLocation($petId: ID!) {
pet(id: $petId) {
id
currentLocation {
latitude
longitude
placeName
}
}
}
`;
export async function getPetLocation(petId: string) {
const client = await createClient();
const data = await client.request(LOCATION_QUERY, { petId });
return data.pet.currentLocation;
}The same pattern is used for activity, walks, device info, etc., with each query stored as a separate gql string.
3. KV Namespace for Session Management
A tiny wrapper isolates KV access. The namespace is declared in wrangler.toml as TRYFI_TOKENS.
// src/kv.ts
export async function getSessionCookie(): Promise<string> {
const token = await TRYFI_TOKENS.get('session');
if (!token) throw new Error('No TryFi session found. Authenticate first.');
// TryFi expects the cookie name "session"
return `session=${token}`;
}
export async function setSessionCookie(token: string): Promise<void> {
await TRYFI_TOKENS.put('session', token, { expirationTtl: 60 * 60 * 24 * 7 }); // 1 week
}When a user logs in through the Cloudflare Access flow, the worker receives the TryFi session cookie and stores it via setSessionCookie.
4. D1 Database for Location History
A scheduled handler runs every 5 minutes, fetches the latest location for every registered pet, and writes it to a D1 table called location_history.
// src/schedule.ts
import { getAllPetIds } from './tryfi-client';
import { DB } from './d1';
export async function scheduled(event: ScheduledEvent) {
const petIds = await getAllPetIds();
for (const id of petIds) {
const loc = await getPetLocation(id);
await DB.prepare(
`INSERT INTO location_history (pet_id, latitude, longitude, timestamp)
VALUES (?, ?, ?, datetime('now'))`
)
.bind(id, loc.latitude, loc.longitude)
.run();
}
}The location_history table is defined in schema.sql (created with wrangler d1 execute).
5. Putting It All Together
- User visits the Astro dashboard → browser sends a request to
/api/pets/:id/location. - Worker receives the request, uses the KV‑stored cookie to authenticate with TryFi, runs the GraphQL query, and returns JSON.
- Frontend renders the map using Leaflet (or any map library) and updates the UI in real time.
- Every 5 minutes, the scheduled job stores a new row in D1, enabling historical charts and export features.
Getting Started
| Step | Command |
|---|---|
| 1️⃣ Clone | git clone https://github.com/xxdesmus/fi-worker.git && cd fi-worker |
| 2️⃣ Install backend | npm install |
| 3️⃣ Set secrets (TryFi email/password) | npx wrangler secret put TRYFI_EMAILnpx wrangler secret put TRYFI_PASSWORD |
| 4️⃣ Create KV namespace | npx wrangler kv:namespace create TRYFI_TOKENS |
| 5️⃣ Create D1 database | npx wrangler d1 create fi-dbnpx wrangler d1 execute fi-db --file=schema.sql |
| 6️⃣ Deploy worker | npx wrangler deploy |
| 7️⃣ Frontend | cd web && npm install |
8️⃣ Update API base (replace YOUR_WORKER_URL in src/lib/api.ts) | |
| 9️⃣ Build & deploy pages | npm run build && npx wrangler pages deploy dist |
After deployment, open the Pages URL in a browser. Cloudflare Access will handle authentication; once logged in, the dashboard shows all pets, maps, activity charts, and device status.
Recent Developments
The latest release adds a lightning‑bolt icon to the battery indicator, making it instantly clear when a device is charging.
Password‑based login has been removed in favour of Cloudflare Access, simplifying security and eliminating the need to store a site password.
Documentation now includes full GraphQL fragment definitions, the graphqlQuery helper used throughout the client, and an expanded D1 schema that captures timestamps with second‑level precision.
Conclusion
Fi Worker turns the powerful but complex TryFi GraphQL API into a developer‑friendly REST service while providing a polished Astro dashboard out of the box. By leveraging Cloudflare Workers, KV, and D1, it offers low‑latency, serverless operation, secure cookie‑based authentication, and persistent location history—features that would otherwise require a substantial amount of custom infrastructure.
Whether you’re building a mobile app, a home‑assistant integration, or simply want a ready‑made pet‑tracking dashboard, Fi Worker gives you a solid foundation with minimal overhead. Feel free to explore the source, contribute enhancements, or spin up your own instance on Cloudflare today.