Skip to content
← All posts
Product7 min read

Receive your first live F1 webhook in 5 minutes (Node.js)

Get a token, register an F1 webhook, and verify the HMAC signature in a short Node.js receiver, on the Free tier and without waiting for a race.

By the end of this post you'll have a Node.js server that receives live Formula 1 events from RaceHooks, rejects anything we didn't sign, and prints a line every time the race leader starts a new lap or the track status changes. It takes four API calls and one file of about 55 lines. All of it runs on the Free tier, and you don't have to wait for a race weekend to test it.

What you'll build

StepCallWhat you get back
1. Get a tokenPOST /v1/oauthA Bearer token valid for 12 hours
2. Register an endpointPOST /v1/webhooksA webhookId and a signing webhookSecret
3. Receive and verifyyour serverSigned JSON deliveries, one per event
4. Test without a raceSimulateA past session replayed into your endpoint
5
feeds on the Free tier, including lap count and track status

Sign up at racehooks.io/signup, verify your email, then open the API Keys page in the console and create a client. You'll get a client_id and a client_secret.

Step 1: Exchange credentials for a Bearer token

curl -X POST https://api.racehooks.io/v1/oauth \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "YOUR_CLIENT_ID",
    "client_secret": "YOUR_CLIENT_SECRET",
    "grant_type": "client_credentials"
  }'

The response holds access_token, token_type: "Bearer" and expires_in: 43200, which is 12 hours. Export the token as TOKEN. Every other call sends it in the Authorization: Bearer header.

Step 2: Register a webhook

One endpoint can subscribe to several feeds. All of them share a single signing secret. On Free, we'll subscribe to the two feeds that best show a race unfolding: session.lap-count (the current lap and the total) and session.track-status (green, yellow, safety car, VSC, red).

curl -X POST https://api.racehooks.io/v1/webhooks \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "webhookUrl": "https://your-app.example.com/racehooks",
    "feedIds": ["session.lap-count", "session.track-status"]
  }'

The response's data object contains webhookId, your subscriptions and webhookSecret. Store the secret as RACEHOOKS_WEBHOOK_SECRET. If you lose it, GET /v1/webhooks/:id/secret returns it again, and POST /v1/webhooks/:id/rotate-secret issues a new one.

A few rules the API enforces:

Step 3: A receiver that verifies every delivery

Every delivery is an HTTP POST with a JSON body and these headers:

HeaderWhat it carries
X-RaceHooks-Signaturesha256= followed by the hex HMAC-SHA256 of the raw body, keyed with your webhookSecret
X-RaceHooks-Delivery-IdA UUID. It stays the same across retries of one delivery, so use it to dedupe
X-RaceHooks-Sent-AtSend time of this attempt, as epoch milliseconds
X-RaceHooks-FeedThe feed id, e.g. session.lap-count
X-RaceHooks-Modelive, replay (Simulate) or test (a manual ping)

Every tier signs its deliveries. The signature covers the exact bytes of the body and nothing else. If you parse the JSON before checking the signature, re-serializing it can change the bytes, and valid deliveries will fail. So the receiver below reads the raw body with express.raw, compares signatures in constant time, and parses only after the check passes.

npm init -y && npm install express
// server.mjs — run with: RACEHOOKS_WEBHOOK_SECRET=... node server.mjs
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";

const SECRET = process.env.RACEHOOKS_WEBHOOK_SECRET;
if (!SECRET) throw new Error("Set RACEHOOKS_WEBHOOK_SECRET");

function isValidSignature(rawBody, header) {
  if (typeof header !== "string" || !header.startsWith("sha256=")) return false;
  const expected = Buffer.from(
    "sha256=" + createHmac("sha256", SECRET).update(rawBody).digest("hex"),
  );
  const received = Buffer.from(header);
  // timingSafeEqual throws on unequal lengths, so check length first
  return received.length === expected.length && timingSafeEqual(received, expected);
}

const seen = new Set(); // swap for Redis or your DB in production

const app = express();

app.post(
  "/racehooks",
  express.raw({ type: "application/json", limit: "1mb" }),
  (req, res) => {
    if (!isValidSignature(req.body, req.get("X-RaceHooks-Signature"))) {
      return res.status(401).send("invalid signature");
    }

    const deliveryId = req.get("X-RaceHooks-Delivery-Id");
    if (seen.has(deliveryId)) return res.sendStatus(200); // a retry we already handled
    seen.add(deliveryId);

    const mode = req.get("X-RaceHooks-Mode"); // live | replay | test
    const event = JSON.parse(req.body.toString("utf8"));

    if (mode === "test") {
      console.log(`[test] ping for ${event.feed}`);
      return res.sendStatus(200);
    }

    switch (event.feed) {
      case "session.lap-count":
        console.log(`[${mode}] Lap ${event.data.currentLap}/${event.data.totalLaps}`);
        break;
      case "session.track-status":
        console.log(`[${mode}] Track: ${event.data.status} (${event.data.message})`);
        break;
      default:
        console.log(`[${mode}] ${event.feed}`, event.data);
    }

    res.sendStatus(200);
  },
);

app.listen(3000, () => console.log("Listening on :3000/racehooks"));

During a session, the output looks like this:

[live] Lap 42/78
[live] Track: safetyCar (SAFETY CAR)

Every feed uses the same envelope, { feed, sessionId, utc, data }, so this one switch can route every feed you add later. To check connectivity right away, send yourself a signed ping with POST /v1/webhooks/:id/test. It arrives in the same envelope with X-RaceHooks-Mode: test and placeholder data, which is why the receiver checks the mode first.

Freshness isn't signed

The HMAC covers the body only. X-RaceHooks-Sent-At isn't part of the signature, and it changes on every retry attempt. Use it as a staleness hint, and rely on X-RaceHooks-Delivery-Id for deduplication.

What happens when you don't return 2xx

Your endpoint has 10 seconds to respond. What happens next depends on your status code:

Your responseWhat RaceHooks does
2xxSuccess. Your failure streak resets to zero
Timeout, connection error, 5xx or 429Retries after about 1s, then 5s, then 30s, each with ±25% jitter. That's four attempts in total
Any other 4xx (400, 401, 404…)Treated as a permanent rejection. No retry

Each delivery that still fails after its retries adds one to the endpoint's failure count. After 10 consecutive failed deliveries, RaceHooks disables the endpoint and emails you. PATCH it back to active: true once it's fixed. In practice: answer 200 quickly and do slow work after you respond. Send 401 only when the signature really fails, because a run of rejections will disable the endpoint. Details are in /docs/webhooks.

Test it without a live race

You don't need a race weekend to see this working. Open Simulate in the console, pick one of this season's sessions and replay it into your registered endpoints in real time or sped up (10× runs a full race in about nine minutes). Deliveries arrive signed, in the same envelope, with X-RaceHooks-Mode: replay, so the receiver above works without changes. If your production pipeline should act only on real sessions, filter on mode === "live". Free accounts can replay up to 5 distinct current-season sessions. The walkthrough is in our post on the Simulate tool.

A replay sends the payloads a real session produced, in the order they happened, so your receiver sees the safety cars and red flags a hand-written fixture tends to leave out.

The shorter path: our Node SDK

The racehooks npm package handles the token exchange and refresh, endpoint registration, and signature checks:

npm install racehooks express
// sdk.mjs
import express from "express";
import { RaceHooks, webhookHandler } from "racehooks";

const rh = new RaceHooks({
  clientId: process.env.RACEHOOKS_CLIENT_ID,
  clientSecret: process.env.RACEHOOKS_CLIENT_SECRET,
});

// One-time setup: register the endpoint, then store the secret
const { webhook, webhookSecret } = await rh.webhooks.create({
  feedId: "session.track-status",
  webhookUrl: "https://your-app.example.com/racehooks",
});
console.log(webhook.webhookId, webhookSecret);

// The receiver: verifies, parses, and replies 200 (or 400 on a bad signature)
const app = express();
app.post(
  "/racehooks",
  express.raw({ type: "application/json", limit: "1mb" }),
  webhookHandler(webhookSecret, async (event) => {
    console.log(event.feed, event.data);
  }, { toleranceSeconds: 300 }), // reject deliveries more than 5 minutes old
);
app.listen(3000);

webhookHandler needs the raw body, just as the hand-rolled version does. Mount express.raw before it, or the handler rejects the request. If you'd rather handle errors yourself, use constructEvent(), which throws a typed error, or safeConstructEvent(), which returns { valid, event | error }.

Where to go next

The takeaway

A verified F1 webhook comes down to three things: read the raw body, compare the sha256= HMAC in constant time, and return 200 fast.

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