Skip to content
← All posts
Product8 min read

Build a live F1 fantasy leaderboard in TypeScript

Stream live race events into the open-source RaceHooks fantasy scorer and serve a league leaderboard that updates mid-race. Custom rules included.

Most fantasy leaderboards update after the checkered flag. By the end of this post you'll have one that updates during the race: a small TypeScript service that takes live race events from RaceHooks, scores every roster in your league with the open-source fantasy scorer, and prints standings each time a points-relevant event arrives. An overtake, a fastest lap, a retirement or a pit stop moves the table straight away.

It's about a hundred lines. The scoring logic is open source under the MIT licence and has no runtime dependencies, so you can read every rule that touches a user's score.

What you're building

Three pieces, wired in a straight line:

  1. The events.race feed. Discrete race events (session start, overtakes, fastest laps, pit stops, retirements, position changes, session complete), delivered over SSE or to your webhook. Every event uses one envelope: { feed, sessionId, event, lap, utc, data }.
  2. @racehooks/f1-fantasy-scorer. An open-source package that turns those events into fantasy points. It ships an F1-style preset (OfficialF1ScoringRules), an illustrative DFS-style preset, a validator for your own rules, and a budget-aware roster optimizer.
  3. Your leaderboard. One scorer per league entry, summed and sorted.

events.race is a live feed, so you need the Developer plan or higher. Plans are on the pricing page.

Two ways to get fantasy points

You can score events yourself with the open-source package (this post), or read points we've already computed: the fantasy.scores feed pushes a per-driver breakdown whenever a score changes, and GET /v1/fantasy/session/:sessionId/scores returns live provisional scores. Both need Developer or higher. Our built-in rules are a separate ruleset from the package presets, so pick one source per league. The fantasy docs cover both.

Step 1: install the scorer

npm install @racehooks/f1-fantasy-scorer

The package has no runtime dependencies, so the install is a single package.

Each FantasyScorer takes a ruleset plus, optionally, a roster of driver TLAs, a boost (a "captain" multiplier on one driver) and a Driver of the Day nomination. Drivers outside the roster are still tracked, so positions stay correct, but they earn that scorer nothing.

import { FantasyScorer, OfficialF1ScoringRules } from "@racehooks/f1-fantasy-scorer";

const scorer = new FantasyScorer({
  rules: OfficialF1ScoringRules,
  roster: ["LEC", "NOR", "RUS", "ALB", "HUL"],
  boost: { driver: "LEC", multiplier: 2 },
});

Step 2: subscribe to race events

The simplest transport is Server-Sent Events. Open GET /v1/stream?feeds=events.race with your token in an Authorization: Bearer header. Each frame is event: events.race followed by a data: line holding the JSON envelope. If your plan does not include the feed, you get a 403 before the stream opens, not an empty stream.

If you would rather receive pushes, create a webhook with feedId: "events.race". RaceHooks POSTs the same JSON envelope to your URL with X-RaceHooks-* headers, including the HMAC X-RaceHooks-Signature on every delivery. Your first live F1 webhook in Node.js covers signature checks and the rest of the setup. Either way the payload is identical, so the scoring code below does not change.

Step 3: score a league and print standings

Here is the whole service. It uses Node 18+ built-in fetch, so there is nothing else to install.

// leaderboard.ts
import {
  FantasyScorer,
  OfficialF1ScoringRules,
  type RaceEventPayload,
} from "@racehooks/f1-fantasy-scorer";

type Entry = { name: string; scorer: FantasyScorer };

const league: Entry[] = [
  { name: "Box Box Box", roster: ["LEC", "NOR", "RUS", "ALB", "HUL"], captain: "LEC" },
  { name: "Undercut FC", roster: ["VER", "PIA", "HAM", "GAS", "OCO"], captain: "VER" },
  { name: "Sector Three", roster: ["NOR", "SAI", "ANT", "STR", "BEA"], captain: "NOR" },
].map(({ name, roster, captain }) => ({
  name,
  scorer: new FantasyScorer({
    rules: OfficialF1ScoringRules,
    roster,
    boost: { driver: captain, multiplier: 2 },
  }),
}));

function standings() {
  return league
    .map(({ name, scorer }) => ({
      name,
      points: Object.values(scorer.getScores()).reduce((a, b) => a + b, 0),
    }))
    .sort((a, b) => b.points - a.points);
}

function onRaceEvent(payload: RaceEventPayload) {
  if (payload.feed !== "events.race") return;
  // ingest() routes the event and finalises the session on session.complete
  // (finishing positions, beat-your-teammate bonuses).
  for (const { scorer } of league) scorer.ingest(payload);

  console.clear();
  console.log(`Lap ${payload.lap ?? "-"} · ${payload.event}`);
  standings().forEach((s, i) => console.log(`${i + 1}. ${s.name.padEnd(14)} ${s.points}`));
}

async function main() {
  const res = await fetch("https://api.racehooks.io/v1/stream?feeds=events.race", {
    headers: { Authorization: `Bearer ${process.env.RACEHOOKS_TOKEN}` },
  });
  if (!res.ok || !res.body) throw new Error(`stream refused: ${res.status}`);

  const decoder = new TextDecoder();
  let buffer = "";
  const reader = res.body.getReader();
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });
    let end: number;
    while ((end = buffer.indexOf("\n\n")) !== -1) {
      const frame = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      const data = frame
        .split("\n")
        .filter((line) => line.startsWith("data:"))
        .map((line) => line.slice(5).trim())
        .join("");
      if (data) onRaceEvent(JSON.parse(data));
    }
  }
}

main();

A few details are worth knowing:

To serve standings instead of printing them, return standings() from an HTTP handler, or push it to browsers over your own SSE endpoint each time onRaceEvent runs. If you want per-event animation, subscribe with scorer.on("scoreUpdate", (scores, entry) => ...). The log entry tells you which driver scored, how many points and why.

Custom scoring rules

A ruleset is a plain object, so the usual approach is to spread a preset and override what your game does differently, then validate it before kickoff:

import {
  FantasyScorer,
  OfficialF1ScoringRules,
  ScoringRulesValidator,
  type ScoringRules,
} from "@racehooks/f1-fantasy-scorer";

const myLeagueRules: ScoringRules = {
  ...OfficialF1ScoringRules,
  name: "My League 2026",
  fastestLapPoints: 5,       // the F1-style preset has none
  overtakePoints: 2,         // reward racing, not just results
  raceDnfPoints: -10,        // softer than the preset's -20
  defaultBoostMultiplier: 3, // high-risk captain picks
};

const { valid, errors, warnings } = ScoringRulesValidator.validate(myLeagueRules);
if (!valid) throw new Error(errors.join("\n"));
warnings.forEach((w) => console.warn(w));

const scorer = new FantasyScorer({ rules: myLeagueRules, roster: ["LEC", "NOR"] });

The constructor validates too and throws on an invalid ruleset, so a typo fails loudly at startup instead of scoring a whole race wrong. Every field you can set, from position tables to pit-stop bands, is documented in the package README.

For reference, here is how the two shipped presets differ:

RuleF1-styleDFS-style (illustrative)
Race winner2545
Places scoredTop 10Top 20
Position gained / lost+1 / −1+3 / −3
Overtake+10
Fastest lap05
Race DNF−200
Boost multiplier2×1.5×
Sprint, qualifying, pit-stop bandsYesNo

Pick rosters with the optimizer

If your product suggests a lineup, RosterOptimizer fills a roster under a budget. You supply prices and projected points:

import { RosterOptimizer } from "@racehooks/f1-fantasy-scorer";

const pick = RosterOptimizer.optimize(candidates, { budget: 100, rosterSize: 5 });
// { drivers, totalPrice, totalProjectedPoints, remainingBudget }

It throws if no roster fits the budget, so you never get a quiet four-driver lineup back. You supply the projections, and our models can help there (see below).

Test it on a whole race weekend

You do not need to wait for a live session to see the leaderboard move. Simulate replays a recorded session through your own webhook, so the scorer receives the same events.race payloads it will see on race day. Replay deliveries carry X-RaceHooks-Mode: replay and the replay session headers, so you can keep test runs out of production standings.

Inputs the feed does not carry

Driver of the Day is an editorial award, not a race event. Nominate it with scorer.setDriverOfTheDay("LEC") once it is announced. The scorer's F1-style preset is built from publicly posted rules only. RaceHooks has no connection to the championship's own fantasy game.

Where the model layer fits

The scorer tells you what happened. For what is likely to happen, the Custom plan adds our model outputs: finishing-position distributions, expected place differential, a live per-driver DNF risk (the retirement probability that decides a captain pick), and Friday pre-race previews. They fit straight into projectedPoints in the optimizer, or into a "captain risk" badge next to each pick. The fantasy page covers what Custom includes.

The takeaway

Subscribe to events.race, give each league entry its own FantasyScorer, and sum getScores() to get a leaderboard that moves during the race. Spread a preset to write your own rules, validate them before kickoff, and rehearse the whole weekend with Simulate before race day.

RaceHooks is a motorsport analytics API with fourteen production ML models enriching live race data, delivered to you in real time.