Skip to content

Flighty on my website

How my flights get from the Flighty app on my Mac to the Stats page, with a flag for every country, and the two bugs that had me showing a friend's travels instead of mine.

The Stats page now has a Flights section: how many flights I've taken, how far, how long in the air, the airports, airlines and countries, and my most flown routes. The numbers come from Flighty, the app I use to track every flight.

It works a lot like the Apple Health numbers: a token-protected POST, one private file in Vercel Blob, and a cache tag to clear. The difference is where the data comes from. Flighty has no API and no export, so this time I had to go and get it myself.

Where Flighty keeps your flights

Flighty has a Mac app, and like most Mac apps it keeps its data in a SQLite database inside its container:

~/Library/Containers/com.flightyapp.flighty/Data/Documents/MainFlightyDatabase.db

I found that thanks to flighty-mcp, an MCP server that lets AI assistants read the same database. Its queries showed me which tables matter: Flight, Airport, Airline, and UserFlight, which links flights to people.

I didn't use the MCP server itself, though. It's Python and talks to an assistant over stdio, and the site is deployed on Vercel, which can't see a file on my Mac anyway. What I needed was a script that runs on my Mac, works out the totals and sends them to the site. So I borrowed the queries and wrote it in TypeScript.

Reading SQLite with nothing to install

Node has a built-in SQLite module now, so the script has no dependencies at all. It opens the database read-only, so it can't damage anything Flighty needs, even while the app is open:

ts
import { homedir } from "node:os"import { DatabaseSync } from "node:sqlite"
const DB =  process.env.FLIGHTY_DB_PATH ??  `${homedir()}/Library/Containers/com.flightyapp.flighty/Data/Documents/MainFlightyDatabase.db`
const db = new DatabaseSync(DB, { readOnly: true })

Like the health pull script, it's plain TypeScript that Node runs directly, with no build step:

bash
pnpm flights:push

Which flights count

Every number on the page comes from the same set of flights, so it's defined once, and every other query reads from it. The queries live in src/lib/flights-db.ts, as one function the script calls:

ts
const flights = readFlights(db, owner[0].userId)

The flights come from two places, which I'll get to in a moment. Whichever table they're from, they come out with the same columns, so nothing after this needs to know the difference:

ts
const SOURCES = `  SELECT f.departureAirportId, f.scheduledArrivalAirportId AS arrivalAirportId,    f.airlineId, f.distance, f.departureScheduleGateOriginal AS departs,    COALESCE(f.arrivalScheduleGateActual, f.arrivalScheduleGateEstimated,      f.arrivalScheduleGateOriginal)    - COALESCE(f.departureScheduleGateActual, f.departureScheduleGateEstimated,      f.departureScheduleGateOriginal) AS seconds  FROM Flight f  JOIN UserFlight uf ON uf.flightId = f.id  WHERE uf.deleted IS NULL AND f.deleted IS NULL AND uf.userId = :owner    AND uf.isMyFlight    AND NOT f.isCancelled    AND f.departureScheduleGateOriginal < unixepoch()  UNION ALL  SELECT m.departureAirportId, m.scheduledArrivalAirportId, m.airlineId,    m.distance, m.departureScheduleGateOriginal,    COALESCE(m.arrivalScheduleGateActual, m.arrivalScheduleGateOriginal)    - COALESCE(m.departureScheduleGateActual, m.departureScheduleGateOriginal)  FROM ManualFlight m  JOIN UserManualFlight umf ON umf.flightId = m.id  WHERE umf.deleted IS NULL AND m.deleted IS NULL AND umf.userId = :owner    AND NOT m.isCancelled    AND m.departureScheduleGateOriginal < unixepoch()`
const FLOWN = `  FROM (${SOURCES}) f  JOIN Airport dep ON f.departureAirportId = dep.id  JOIN Airport arr ON f.arrivalAirportId = arr.id  JOIN Airline al ON f.airlineId = al.id`

uf.userId = :owner and uf.isMyFlight weren't there in the first version, and the numbers were wrong without them. More on that below.

Flighty stores times as Unix timestamps, so SQLite's unixepoch() is "now", and anything that hasn't left yet is skipped. Upcoming flights never leave my Mac.

Flights added by hand

Flighty's flight data only goes back so far, so older flights have to be added by hand, and Flighty keeps those in tables of their own: ManualFlight and UserManualFlight. They look almost exactly like Flight and UserFlight, minus the estimated times, which is why that half of the query goes straight from actual to scheduled.

My first version only read Flight, so anyone with flights added by hand would have been missing all of them. I don't have any myself, so my numbers didn't change, but the database on my Mac had some, and they had one more surprise: isMyFlight was 0 on every single one. Flighty still counts them in its passport card, though, so the manual half doesn't filter on it. Filtering on it would have added nothing at all.

That's easy to get wrong without noticing, so it has tests. They build a small Flighty database in memory, with Node's SQLite, and check that a flight added by hand is counted once, with its distance and hours:

ts
it("counts flights added by hand alongside Flighty's own, once each", () => {  const flights = readFlights(db, ME)  expect(flights).toMatchObject({    flights: 2,    distanceKm: 1264 + 5540,    hours: 10,    airports: 3,    countries: 3,    since: 2019,  })})

Another one adds ten flights that mustn't count, from someone else's to cancelled, deleted and not yet flown, from both tables, and checks the totals don't move.

The totals

Most of the totals are one query:

ts
const totals = db  .prepare(    `SELECT       COUNT(*) AS flights,       SUM(f.distance) AS distanceKm,       SUM(f.seconds) / 3600.0 AS hours,       MIN(strftime('%Y', f.departs, 'unixepoch')) AS since     ${FLOWN}`  )  .get(params)

Time in the air, the seconds from the flight sources above, takes the best time Flighty has for each end of each flight: what actually happened, or failing that its estimate, or failing that the schedule. My first version went straight from actual to scheduled and came out three hours short of what the app says. With the estimate in the middle, it matches to the hour: 9d 5h.

Airports and countries need both ends of every flight, so there's a second building block, with each end marked as a departure or an arrival:

ts
const ENDS = `  SELECT dep.iata AS iata, dep.city AS city, dep.country AS country,    dep.countryCode AS code, 0 AS arrival ${FLOWN}  UNION ALL  SELECT arr.iata, arr.city, arr.country, arr.countryCode, 1 ${FLOWN}`

Routes, both ways

London to Santiago and Santiago to London are the same route to me, so a route is grouped by its two airports in alphabetical order. SQLite's MIN and MAX take more than one argument, which makes that a one-liner:

ts
const topRoutes = db  .prepare(    `SELECT MIN(dep.iata, arr.iata) AS a, MAX(dep.iata, arr.iata) AS b,       COUNT(*) AS count     ${FLOWN}     GROUP BY a, b ORDER BY count DESC, a, b LIMIT 5`  )  .all(params)
topRoutes.map(({ a, b, count }) => ({ route: `${a} ⇄ ${b}`, count }))

Countries, by visits

A visit to a country is a landing there. A round trip from London to Spain is one visit to Spain and one to the UK, which is how I'd count it in my head. Countries I've only ever flown out of are still listed, with no visits:

ts
const countryVisits = db  .prepare(    `SELECT UPPER(code) AS code, country AS name, SUM(arrival) AS count     FROM (${ENDS})     GROUP BY UPPER(code) ORDER BY count DESC, name`  )  .all(params)

Every airport in Flighty has an ISO country code, like GB or ES, which is exactly what a flag component wants.

Domestic, international and long haul

Flighty's passport card says how many of my flights were long haul, but it doesn't store that anywhere I could find. So the script works out all three types itself.

A flight is domestic when both airports are in the same country, and international when they aren't. Long haul is 4,000 km or more, a common airline cut-off:

ts
// Long haul from 4,000 km, a common airline cut-offconst LONG_HAUL_KM = 4000const types = db  .prepare(    `SELECT       SUM(UPPER(dep.countryCode) = UPPER(arr.countryCode)) AS domestic,       SUM(UPPER(dep.countryCode) != UPPER(arr.countryCode)) AS international,       SUM(f.distance >= ${LONG_HAUL_KM}) AS longHaul     ${FLOWN}`  )  .get(params)

In SQLite a comparison is 1 or 0, so SUM of one counts the rows where it's true.

I checked the cut-off against Flighty's count. My five longest flights are all over 6,500 km and eight hours, and the next one is 2,710 km, so any of the usual definitions, by distance or by time, gives the same five as the app.

Only totals leave the Mac

The script sends a small JSON object and nothing else. No dates, no flight numbers, no seats, no booking references, and nothing that hasn't happened yet:

json
{  "flights": 90,  "distanceKm": 136067,  "hours": 221,  "airports": 16,  "airlines": 9,  "countries": 7,  "domestic": 8,  "international": 82,  "longHaul": 5,  "since": 2019,  "topRoutes": [{ "route": "LGW ⇄ SCQ", "count": 46 }],  "topAirlines": [{ "name": "Vueling", "count": 57 }],  "topAirports": [{ "iata": "LGW", "city": "London", "count": 69 }],  "countryVisits": [{ "code": "ES", "name": "Spain", "count": 42 }]}

The lists are trimmed here; the real ones have five rows, and every country.

Sending it is a fetch with the token:

ts
const response = await fetch(URL, {  method: "POST",  headers: {    Authorization: `Bearer ${TOKEN}`,    "Content-Type": "application/json",  },  body: JSON.stringify(flights),})if (!response.ok) {  console.error(`${URL}: ${response.status} ${await response.text()}`)  process.exit(1)}

URL is the live site unless FLIGHTS_API_URL says otherwise, so I can point it at the dev server while I'm working on the page.

Working on it offline

Before sending anything, the script also saves the totals to a file on my Mac, in exactly the shape the site stores:

ts
// Same file as src/lib/flights-store.ts reads in devconst FILE = ".flights/stats.json"
// Stamped here, as the endpoint does when it saves themconst saved: FlightStats = { ...flights, updatedAt: new Date().toISOString() }await mkdir(".flights", { recursive: true })await writeFile(FILE, `${JSON.stringify(saved, null, 2)}\n`)console.log(`Saved to ${FILE}`)if (LOCAL) process.exit(0)

In development, with no Blob store set up, the site reads that file instead of Blob, the same trick the health numbers use. So with --local, the script stops after saving, and I can work on the page on a plane, with no network and no token:

bash
pnpm flights:push --localpnpm dev

The token is only checked when there's something to send:

ts
const LOCAL = process.argv.includes("--local")const TOKEN = process.env.FLIGHTS_WEBHOOK_TOKENif (!LOCAL && !TOKEN) {  console.error("Missing FLIGHTS_WEBHOOK_TOKEN (or use --local)")  process.exit(1)}

.flights/ is in .gitignore, so the file never leaves the Mac either.

The endpoint

src/routes/api/flights.ts is a copy of the health webhook with a different parser: POST with the token saves the totals and clears the cache, GET is public.

ts
POST: async ({ request }) => {  const denied = checkToken(request)  if (denied) return denied
  let body: unknown  try {    body = JSON.parse(await request.text())  } catch {    return new Response("Expected a JSON body", { status: 400 })  }
  const flights = parseFlights(body)  if (!flights) {    return new Response("Expected flight totals", { status: 400 })  }  await saveFlights({ ...flights, updatedAt: new Date().toISOString() })  await clearFlightsCache()  return new Response(null, { status: 204 })},

Storage and caching are the same as for health, down to the names: one private file, flights/stats.json, and a flights cache tag that every push clears. The health post explains both.

Trust nothing, even from yourself

The only thing that can POST here is my own script, but the parser still checks every field and keeps only the ones it knows. If I ever send a booking reference by mistake, it's dropped before it's stored:

ts
const isCount = (value: unknown): value is number =>  typeof value === "number" && Number.isFinite(value) && value >= 0
/** Each row's text fields are strings and its count is a number. */function rows<T extends { count: number }>(value: unknown, keys: string[]) {  if (!Array.isArray(value)) return null  const valid = value.every(    (row) =>      row &&      isCount(row.count) &&      keys.every((key) => typeof row[key] === "string")  )  // Only the known fields, so nothing else a sender adds gets stored  return valid    ? (value.map((row) =>        Object.fromEntries(["count", ...keys].map((key) => [key, row[key]]))      ) as T[])    : null}

And there's a test that says so:

ts
it("drops fields it doesn't know", () => {  const parsed = parseFlights({    ...body,    pnr: "ABC123",    topRoutes: [{ route: "LHR ⇄ MAD", count: 5, seat: "12A" }],  })  expect(parsed).not.toHaveProperty("pnr")  expect(parsed?.topRoutes).toEqual([{ route: "LHR ⇄ MAD", count: 5 }])})

Empty means empty

Before the first push there's nothing to show, and the endpoint says so with a 204 No Content rather than a 200 with null in it. The health endpoint now does the same when the phone hasn't sent anything today:

bash
curl -i https://ryck.dev/api/flights# HTTP/2 200 with the totals, or HTTP/2 204 and no body

The numbers were someone else's

The first version worked first time, and the numbers looked great. Then I noticed a country I've never flown to.

Flighty lets you connect with friends and see their flights, and the database on my Mac had a friend's flights in it as well as mine. flighty-mcp works out whose flights are yours by counting who appears most in the list of friend connections. With one friend, we each appeared twice: a tie, and it picked them. Its fallback, whoever has the most flights, would have picked them too.

So for about ten minutes, my site was showing a friend's travels as mine.

The fix was to stop guessing. Flighty knows who's signed in, and keeps it in a User table:

ts
// The account signed in to Flighty on this Mac. The database also holds// friends' flights, and guessing by who has the most of them can pick a friendconst owner = db  .prepare(`SELECT remoteId AS userId FROM User WHERE remoteId IS NOT NULL`)  .all() as Array<{ userId: string }>if (owner.length !== 1) {  console.error(    `Expected one signed-in Flighty user, found ${owner.length}. Is Flighty signed in?`  )  process.exit(1)}

If that ever finds anything other than exactly one person, the script stops instead of picking one.

Flights I wasn't on

With the right person, the numbers were still too high: 128 flights, where Flighty's own "Flighty Passport" said 90. The other 38 were flights I'd tracked but wasn't on, like someone you're picking up from the airport. Flighty marks your own flights with isMyFlight, hence the AND uf.isMyFlight in the query above.

With both fixes, the flights, distance, airports, airlines and time in the air all match the app. That passport card made a very good test: a set of numbers I trust, worked out by someone else.

Both bugs are in flighty-mcp too, so I opened an issue with what I'd found.

On the page

The section is six stat cards and three top-five lists. Most of it reuses the components the rest of Stats already had. Three bits are new.

Flight types on hover

Hovering over the number of flights opens a card with the three types, each with an icon and its count in a badge. It's shadcn's hover card, built on Base UI's preview card:

tsx
<HoverCard>  <HoverCardTrigger    // A button, so it can be reached and opened from the keyboard too    render={<button type="button" className="cursor-help" />}  >    <AnimatedNumber value={stats.flights} />    {/* The card only shows on hover or focus, so it's read out here too */}    <span className="sr-only">: {summary}</span>  </HoverCardTrigger>  <HoverCardContent align="start" className="w-56">    <dl className="flex flex-col gap-2">      {types.map(({ label, icon: Icon, count }) => (        <div key={label} className="flex items-center gap-2">          <Icon aria-hidden="true" className="size-4 text-muted-foreground" />          <dt className="flex-1">{label}</dt>          <dd>            <Badge className="tabular-nums">{count}</Badge>          </dd>        </div>      ))}    </dl>  </HoverCardContent></HoverCard>

The trigger is a real <button>, not a <span> with a tabIndex, so the card opens when it's reached with the keyboard as well as the mouse; the linter wouldn't let me do it the other way anyway. A hover card is invisible to anyone who can't hover, so screen readers get the same numbers as text: "90: 8 domestic, 82 international, 5 long haul".

"Long haul" has a tooltip of its own, saying where the line is: 4,000 km or more.

Time like Flighty shows it

221 hours is hard to picture, so the page shows it as 9d 5h, like the app does:

tsx
<Stat  label="In the air"  icon={TimerIcon}  value={    <>      {stats.hours >= 24 && (        <>          <AnimatedNumber value={Math.floor(stats.hours / 24)} />          <span className="ms-1 me-2 text-sm font-normal text-muted-foreground">            d          </span>        </>      )}      <AnimatedNumber value={stats.hours % 24} />      <span className="ms-1 text-sm font-normal text-muted-foreground">h</span>    </>  }/>

A flag for every country

The Countries card has the flags of every country I've been to, scrolling past next to the number, most visited first. They come from flagcn, a shadcn registry of flags, so the component is copied into the project rather than installed:

bash
pnpm dlx shadcn@latest add @flagcn/flag
tsx
import { Flag } from "@/components/flags/flag"
<Flag code="es" width={32} alt="Spain: 42 visits" />

The scrolling is plain CSS. The list is there twice, side by side, and the pair slides left by half its width, which is exactly one list. When it gets to the end, the second copy is where the first one started, so the loop has no gap:

css
/* One copy's width; the second copy then sits where the first began */@keyframes marquee {  to {    translate: -50%;  }}
tsx
<div className="overflow-hidden mask-x-from-90% motion-reduce:overflow-x-auto">  <div    className="flex w-max animate-[marquee_var(--duration)_linear_infinite] hover:[animation-play-state:paused] motion-reduce:animate-none"    style={{ "--duration": `${countries.length * 2}s` } as CSSProperties}  >    {list(false)}    {list(true)}  </div></div>

A few details make it nicer to use:

  • It pauses on hover, so you can read a flag's tooltip: the country and how many times I've been.
  • It stands still for people who turn off animation. The copy is hidden, and the row scrolls by hand instead.
  • Screen readers hear each country once. The copy is aria-hidden, and its flags have empty alt text.
  • The speed depends on the length. Each country adds two seconds, so a long list doesn't race past.
  • The edges fade out, with Tailwind's mask-x-from-90%, so flags slide in and out instead of being cut off.
  • The flags load straight away. Images lazy-load when they're about to scroll into view, but these are clipped sideways inside the card, so the browser would think they're never going to be seen.

After a trip

When I land, I run one command on my Mac, and the page updates a few seconds later:

bash
pnpm flights:push
┌───────────────┬────────┐│ (index)       │ Values │├───────────────┼────────┤│ Flights       │ 90     ││ Distance (km) │ 136067 ││ Hours         │ 221    ││ Airports      │ 16     ││ Airlines      │ 9      ││ Countries     │ 7      ││ Since         │ 2019   │└───────────────┴────────┘Saved to .flights/stats.jsonSent to https://ryck.dev/api/flights

It isn't automatic like the health numbers, and I'm fine with that. My flights change a few times a month at most, not every hour.

What I learnt

  • Check your numbers against a number you trust. Everything looked right until I compared it with the app.
  • Don't guess who the user is when the data can tell you.
  • Only send what you'll show. The site never sees a flight, just the totals.
  • Your own Mac is a fine server for data that changes a few times a year.