Cricket’s next eight months are packed: the IPL 2027 auction, the Border-Gavaskar Trophy, the WTC Final at The Oval, then the Ashes. In this tutorial you will build a small Node.js tool that finds fixtures for any window, shows a live scoreboard, and receives full-time results by webhook, using the Orbistats cricket API. The full calendar is in the cricket data API guide.
What you will build
A resilient API helper with retries
A fixtures finder for any date window
A live scoreboard (polling first, then WebSocket)
An odds call and a signed webhook receiver
Prerequisites: Node 18+ (for built-in fetch) and a free API key from signup. Test in the sandbox first, since the same endpoints return sample data.
bash
mkdir cricket-live && cd cricket-live
npm init -y && npm i ws express
export ORBISTATS_API_KEY="your_key_here"
Set "type": "module" in package.json so you can use import.
- A resilient API helper
Every response uses one envelope: data, meta and errors. The helper below retries only the safe errors (500, 502, 503, 504) with exponential backoff and jitter, and never retries a 4xx. See the API reference for the full error list.
javascript
// orbistats.js
const BASE = "https://api.orbistats.com/v1";
const RETRYABLE = new Set([500, 502, 503, 504]);
export async function api(path, params = {}, { retries = 3 } = {}) {
const url = new URL(BASE + path);
for (const [k, v] of Object.entries(params)) {
if (v != null) url.searchParams.set(k, v);
}
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url, {
headers: { Authorization: Bearer ${process.env.ORBISTATS_API_KEY} },
signal: AbortSignal.timeout(10_000),
});
const body = await res.json();
if (res.ok) return body;
const err = body.errors?.[0] ?? {};
if (!RETRYABLE.has(res.status) || attempt >= retries) {
throw Object.assign(new Error(err.message ?? res.statusText), {
status: res.status,
code: err.code,
requestId: body.meta?.request_id,
});
}
} catch (e) {
if (e.status || attempt >= retries) throw e; // API error, or out of retries
}
const delay = Math.min(8000, 500 * 2 ** attempt) + Math.random() * 250;
await new Promise((r) => setTimeout(r, delay));
}
}
- Find the competition slugs
Never guess a league slug. Slugs are case-sensitive and sport-scoped, so list them from /competitions.
javascript
// slugs.js
import { api } from "./orbistats.js";
const { data } = await api("/cricket/competitions", { per_page: 100 });
const wanted = /ipl|ashes|border|test championship|bbl|sa20|ilt20/i;
for (const c of data.filter((c) => wanted.test(c.name))) {
console.log(c.slug.padEnd(28), "→", c.name);
}
- Pull fixtures for any window
Fixtures default to the next 14 days, so pass date_from and date_to for anything further out. This loops through every page.
javascript
// fixtures.js
import { api } from "./orbistats.js";
export async function fixtures(league, dateFrom, dateTo) {
const out = [];
for (let page = 1, pages = 1; page <= pages; page++) {
const { data, meta } = await api("/cricket/fixtures", {
league, date_from: dateFrom, date_to: dateTo, page, per_page: 100,
});
out.push(...data);
pages = meta.pagination.total_pages;
}
return out;
}
// Example: Border-Gavaskar window, Jan 21 – Mar 3, 2027
const list = await fixtures("YOUR_SLUG", "2027-01-21", "2027-03-03");
for (const f of list) {
console.log(f.kickoff, "|", f.home_team, "v", f.away_team, "|", f.venue ?? "TBC");
}
Keep fixture_id (the fx_… value). It is the key for odds, events, webhooks and WebSocket filters.
- A live scoreboard by polling
Start simple: poll every 5–10 seconds. The Live Scores API returns every match in play with the score, period and latest event. Cricket innings detail appears in score.detail when relevant.
javascript
// poll.js
import { api } from "./orbistats.js";
async function tick() {
const { data } = await api("/cricket/matches/live");
console.clear();
for (const m of data) {
console.log(
${m.home_team} v ${m.away_team} | ${JSON.stringify(m.score)} | last: ${m.last_event?.type ?? "-"}
);
}
}
setInterval(() => tick().catch(console.error), 8000);
- Upgrade to WebSocket
Polling wastes requests and adds delay. The WebSocket API pushes updates over one connection. Four rules make it production-safe: re-subscribe after every reconnect, treat silence as a dead connection, resync over REST when seq jumps, and back off with jitter.
javascript
// stream.js
import WebSocket from "ws";
import { api } from "./orbistats.js";
const URL = wss://stream.orbistats.com/v1?token=${process.env.ORBISTATS_API_KEY};
const board = new Map(); // fixture_id → latest snapshot
let attempt = 0, lastSeq = null, first = true;
async function resync() {
const { data } = await api("/cricket/matches/live"); // REST is the source of truth
board.clear();
data.forEach((m) => board.set(m.fixture_id, m));
}
function connect() {
const ws = new WebSocket(URL);
let watchdog;
const arm = () => {
clearTimeout(watchdog);
watchdog = setTimeout(() => ws.terminate(), 45_000); // silent = dead
};
ws.on("open", async () => {
attempt = 0; lastSeq = null; arm();
ws.send(JSON.stringify({ subscribe: "cricket.live" })); // always re-subscribe
if (!first) await resync(); // fill the gap
first = false;
});
ws.on("message", async (raw) => {
arm();
let msg;
try { msg = JSON.parse(raw); } catch { return; }
if (msg.type === "score_update" || msg.type === "match_event") {
if (lastSeq !== null && msg.seq > lastSeq + 1) await resync(); // missed messages
lastSeq = msg.seq;
const prev = board.get(msg.data.fixture_id) ?? {};
board.set(msg.data.fixture_id, { ...prev, ...msg.data });
}
});
ws.on("error", (e) => console.error("ws error:", e.message));
ws.on("close", () => {
clearTimeout(watchdog);
const delay = Math.min(30_000, 1000 * 2 ** attempt++) + Math.random() * 1000;
setTimeout(connect, delay);
});
}
await resync();
connect();
- Add odds
Odds use the same fixture ID. Pass it as match_id. The endpoint is plan-dependent, so a 403 plan_restricted means your plan does not include it. See the Odds API page and the pricing page.
javascript
const { data: odds } = await api("/cricket/odds", { match_id: "fx_123456" });
for (const q of odds.markets?.["1X2"] ?? []) console.log(q.bookmaker, q);
- Receive full-time results by webhook
Webhooks remove polling for results. Webhooks are signed with HMAC-SHA256 over {timestamp}.{raw_body}. Verify against the raw body, reject old timestamps, and de-duplicate on the event id.
javascript
// webhook.js
import express from "express";
import crypto from "node:crypto";
const app = express();
const SECRET = process.env.ORBISTATS_WEBHOOK_SECRET;
const seen = new Set(); // use Redis or a DB with a TTL in production
function verify(raw, h) {
const ts = h["x-orbistats-timestamp"];
const sig = (h["x-orbistats-signature"] ?? "").replace(/^sha256=/, "");
if (!ts || !sig || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
const expected = crypto.createHmac("sha256", SECRET).update(${ts}.${raw}).digest("hex");
const a = Buffer.from(sig, "hex"), b = Buffer.from(expected, "hex");
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
app.post("/webhooks/orbistats", express.raw({ type: "application/json" }), (req, res) => {
const raw = req.body.toString("utf8");
if (!verify(raw, req.headers)) return res.sendStatus(401);
res.sendStatus(200); // acknowledge fast
const evt = JSON.parse(raw);
if (seen.has(evt.id)) return; // retries can repeat events
seen.add(evt.id);
if (evt.event === "fixture.finished") {
console.log("finished:", evt.data.fixture_id, evt.data.final_score);
}
});
app.listen(3000);
Troubleshooting
Symptom Likely cause Fix
401 invalid_api_key Header missing the word Bearer Authorization: Bearer YOUR_API_KEY, no extra quotes
Fixtures come back empty Default window is 14 days, or off-season Pass date_from and date_to
404 not_found Wrong league slug or ID from another sport Take slugs from /competitions and IDs from fixtures
403 plan_restricted Endpoint not in your plan Check pricing or drop the call
Webhook returns 401 Parsed JSON before verifying, or wrong secret Verify against the raw body
Scoreboard freezes Silent socket drop Keep the watchdog and resync on reconnect
Which plan for which event?
A single T20I or ODI day: Starter (24 hours).
A five-day Test, such as the WTC Final or an Ashes Test: Growth (5 days).
A month-long league window: Unlimited (30 days).
Your access timer starts when you open the activation link, so you choose when to go live. Compare plans on the pricing page.
Where to go next
You now have fixtures, a live board, odds and settlement. Next, explore the SDKs, read the documentation, watch the status page, and see history for backtesting. Start free at orbistats.com.
Not betting advice. Dates in the calendar are announced or reported and may change.
Top comments (0)