Skip to content

Livematches in play

Demo: Matchboard, opens in a new tab

Tutorial

Build a live score app in JavaScript

This guide builds a live score app in JavaScript from one HTML file and one small server: every football match in play, its score, its status and a running clock, refreshed every 15 seconds. It runs on the Free plan, so you can follow it with a key made in a minute.

  • Free plan key
  • 20 min
  • JavaScript
  • Node.js
  • HTML
  • Updated

What you will build

A page that lists every football match being played right now, grouped by competition, with the crest of each team, the score and a clock that ticks between refreshes. The same app, grown up, is Matchboard, our demo built only on this API: open it to see where this guide can lead.

  • A tiny Node.js server that holds your API key and calls GET /v2/livescores. The key never reaches the browser.
  • One HTML page that asks your server for the matches every 15 seconds and draws them.
  • A clock computed in the browser from the fixture's clock object, so it moves every second without extra calls.

1. Get a key and make the first call

Create a free account on the sign-up page and copy the key from your dashboard. It starts with sk_live_. Keep it out of your code: put it in an environment variable.

Terminal
export DATASPORTSAPI_API_KEY="sk_live_…"

Then ask for the football matches in play. Every request carries the key as a Bearer token:

Terminal
curl -H "Authorization: Bearer $DATASPORTSAPI_API_KEY" \
  "https://api.datasportsapi.com/v2/livescores?sport=football"

The answer is the usual envelope: the matches in data, and in meta the sport and how many matches are live. One match, trimmed to the fields this app uses:

Response (trimmed)
{
  "data": [
    {
      "id": 1072150,
      "sport": "football",
      "status": { "type": "inprogress", "description": "2nd half", "period": "period2" },
      "startTime": "2026-11-18T11:00:00.000Z",
      "league": { "id": 860531, "name": "ASEAN Club Championship", "category": "Asia" },
      "home": { "name": "Công An Hồ Chí Minh City", "shortName": "Công An HCMC",
                "image": "https://cdn.datasportsapi.com/v2/teams/263892/logo" },
      "away": { "name": "Buriram United", "shortName": "Buriram",
                "image": "https://cdn.datasportsapi.com/v2/teams/211119/logo" },
      "homeScore": { "current": 0, "redCards": 0 },
      "awayScore": { "current": 0, "redCards": 0 },
      "clock": { "periodStartedAt": "2026-11-18T12:02:00.000Z", "periodOffsetSeconds": 2700 }
    }
  ],
  "meta": { "sport": "football", "count": 121 }
}

Change sport=football to basketball, tennis, ice-hockey or any of the 24 sports and the same code works: every sport answers in this shape.

2. A small server that keeps the key secret

Calling the API straight from the browser would publish your key to anyone who opens the developer tools. A few lines of Node.js (version 18 or later, which has fetch built in) sit in between. They also cache the answer for 15 seconds, so ten open tabs still cost one call:

server.mjs
// server.mjs: run with  node server.mjs
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";

const KEY = process.env.DATASPORTSAPI_API_KEY;
const API = "https://api.datasportsapi.com/v2/livescores?sport=football";
let cache = { at: 0, body: null };

async function liveScores() {
  if (Date.now() - cache.at < 15_000 && cache.body) return cache.body;
  const res = await fetch(API, { headers: { Authorization: `Bearer ${KEY}` } });
  if (res.status === 429) {
    // Over the per-minute limit: keep showing the last answer.
    return cache.body ?? JSON.stringify({ data: [], meta: { count: 0 } });
  }
  if (!res.ok) throw new Error(`API answered ${res.status}`);
  cache = { at: Date.now(), body: await res.text() };
  return cache.body;
}

createServer(async (req, res) => {
  try {
    if (req.url === "/api/live") {
      res.writeHead(200, { "Content-Type": "application/json" });
      return res.end(await liveScores());
    }
    res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
    res.end(await readFile(new URL("./index.html", import.meta.url)));
  } catch (err) {
    res.writeHead(502, { "Content-Type": "text/plain" });
    res.end(String(err));
  }
}).listen(3000, () => console.log("http://localhost:3000"));

If you prefer a client library, the datasportsapi package on npm wraps the same call: await client.get("/v2/livescores", { sport: "football" }).

3. The page: group, draw, refresh

The page asks /api/live for the matches, groups them by competition and draws one row per match. Text goes in with textContent, never as HTML, so a team name can never inject markup:

index.html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Live scores</title>
<style>
  body { font: 15px/1.4 system-ui, sans-serif; max-width: 720px; margin: 2rem auto; padding: 0 1rem; }
  h2 { font-size: .8rem; text-transform: uppercase; letter-spacing: .08em; color: #666; margin: 1.5rem 0 .4rem; }
  .row { display: grid; grid-template-columns: 4.5rem 1fr auto 1fr; gap: .6rem; align-items: center;
         padding: .45rem 0; border-top: 1px solid #eee; }
  .team { display: flex; gap: .4rem; align-items: center; }
  .team.away { justify-content: flex-end; flex-direction: row-reverse; }
  .team img { width: 20px; height: 20px; object-fit: contain; }
  .score { font-weight: 700; font-variant-numeric: tabular-nums; }
  .clock { color: #d00; font-variant-numeric: tabular-nums; }
</style>
<h1>Live football</h1>
<p id="summary">Loading…</p>
<main id="board"></main>
<script src="app.js"></script>
</html>
app.js
// app.js
const board = document.getElementById("board");
const summary = document.getElementById("summary");
let matches = [];

function el(tag, className, text) {
  const node = document.createElement(tag);
  if (className) node.className = className;
  if (text != null) node.textContent = text;
  return node;
}

function team(side, cls) {
  const box = el("span", "team " + cls);
  const img = el("img");
  img.src = side.image;
  img.alt = "";
  box.append(img, el("span", "", side.shortName || side.name));
  return box;
}

function draw() {
  board.replaceChildren();
  const byLeague = new Map();
  for (const m of matches) {
    const key = m.league.category + " · " + m.league.name;
    if (!byLeague.has(key)) byLeague.set(key, []);
    byLeague.get(key).push(m);
  }
  for (const [league, list] of byLeague) {
    board.append(el("h2", "", league));
    for (const m of list) {
      const row = el("div", "row");
      row.dataset.id = m.id;
      row.append(
        el("span", "clock", clockText(m)),
        team(m.home, "home"),
        el("span", "score", m.homeScore.current + " – " + m.awayScore.current),
        team(m.away, "away"),
      );
      board.append(row);
    }
  }
  summary.textContent = matches.length + " matches in play";
}

async function refresh() {
  try {
    const res = await fetch("/api/live");
    const body = await res.json();
    matches = body.data;
    draw();
  } catch {
    summary.textContent = "Could not reach the server; retrying.";
  }
}

refresh();
setInterval(refresh, 15_000);

4. A clock that ticks between refreshes

Refreshing every second would burn the free quota in a few minutes. You do not need to: each live fixture carries a clock object. periodStartedAt is when the current period began and periodOffsetSeconds is how many seconds of play came before it (2,700 at the start of a football second half). Minutes played are the offset plus the time since the period started:

app.js
// Add to app.js, above draw().
function clockText(m) {
  const c = m.clock;
  if (m.status.type !== "inprogress" || !c || !c.periodStartedAt) {
    return m.status.description; // the status in words, e.g. "Halftime"
  }
  const since = (Date.now() - Date.parse(c.periodStartedAt)) / 1000;
  const minute = Math.floor(((c.periodOffsetSeconds || 0) + since) / 60) + 1;
  return minute + "'";
}

// Redraw only the clocks once a second; no API calls.
setInterval(() => {
  for (const row of board.querySelectorAll(".row")) {
    const m = matches.find((x) => String(x.id) === row.dataset.id);
    if (m) row.querySelector(".clock").textContent = clockText(m);
  }
}, 1000);

Football minutes count from 1, which is why the code adds one. Other sports keep their own clocks, with periods of different lengths, and tennis has none at all. The data reference lists the clock fields per sport.

5. Stay inside the limits

Every answer carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers. Past the per-minute limit the API answers 429 with a Retry-After header: wait that many seconds, then carry on. The server above already keeps showing the last answer in that case. A few habits keep the free plan comfortable:

  • Cache on the server, as above. The number of visitors no longer changes the number of calls.
  • Refresh less when nothing is live. When meta.count is 0, check every few minutes instead of every 15 seconds.
  • Ask for one sport per call and only the sports you show.
Refresh everyCalls a minuteCalls a day (24 h)Fits the Free plan?
15 s45,760Per minute yes; per day only for about 4 hours of play
60 s11,440Per minute yes; per day for about 16 hours
90 s0.7960Yes, all day

For a site with an audience, Starter raises the limits to 120 a minute; for updates the moment they happen, without polling at all, the WebSocket stream pushes every change (Business plan).

Run it

Terminal
node server.mjs
# open http://localhost:3000

Put index.html, app.js and server.mjs in one folder, start the server and open the page. When no football is being played, try sport=basketball or sport=tennis in server.mjs: somewhere in the world a match is nearly always live.

Where to go next

More guides

Try it with your own key.

1,000 free requests a day during the beta. No card, no sales call.