DEV Community

Cover image for Build a Live Football Scoreboard in 20 Minutes with JavaScript and a Sports API
orbistats
orbistats

Posted on

Build a Live Football Scoreboard in 20 Minutes with JavaScript and a Sports API

A live scoreboard looks simple until you ship it. The demo works, then real life shows up: your API key leaks into the browser, ten open tabs burn your quota, a background tab keeps polling for no reason, and the score changes so quietly that users never notice the goal.

In this tutorial we build a React scoreboard that avoids all four problems, using a tiny Node proxy and the Orbistats Live Scores API. You will have a working app in about 20 minutes, and you can build the whole UI without an API key, using a built-in mock feed.

Disclosure: I work on Orbistats, the data source used here. The pattern works with any sports API that returns live match JSON.

What we are building
A React + Vite scoreboard that shows live and finished matches.
A tiny Express proxy that keeps your API key on the server and caches responses so ten tabs cost one upstream call.
A useLiveScores hook with adaptive polling: faster when matches are live, slower when idle, paused when the tab is hidden.
A goal flash so users actually see a score change.
Mock mode, so you can finish the UI before you touch a key.
Step What you do Time
1 Create the project 2 min
2 Write the proxy with mock mode 4 min
3 Write the hook 5 min
4 Build the UI and styles 6 min
5 Switch to real data 3 min
Prerequisites
Node.js 20.6 or newer (we use the built-in --env-file flag and fetch).
Basic React. You only need components and hooks.
An Orbistats API key is optional until Step 5. If you want to look at real payloads first, the sandbox lets you try requests, and the quickstart covers authentication.
Step 1: Create the project (2 min)
bash
npm create vite@latest live-scoreboard -- --template react
cd live-scoreboard
npm install
npm install express

Create a .env file in the project root. These variables are read by the server only, so they never reach the browser:

bash
USE_MOCK=1
ORBISTATS_API_KEY=your_key_here
ORBISTATS_BASE=https://api.orbistats.com/v1
ORBISTATS_LIVE_PATH=/football/matches/live

Add .env to .gitignore, then add a script to package.json:

json
"scripts": {
"dev": "vite",
"server": "node --env-file=.env server.js"
}

Finally, tell Vite to forward /api calls to our proxy. Replace vite.config.js:

js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
plugins: [react()],
server: { proxy: { "/api": "http://localhost:4000" } },
});
Step 2: The proxy, with a mock feed (4 min)

Why a proxy? If you call the API straight from the browser, your key is visible to anyone who opens DevTools. A proxy also gives you one place to cache.

Create server.js:

js
import express from "express";

const app = express();
const KEY = process.env.ORBISTATS_API_KEY;
const BASE = process.env.ORBISTATS_BASE ?? "https://api.orbistats.com/v1";
const LIVE_PATH = process.env.ORBISTATS_LIVE_PATH ?? "/football/matches/live";
const USE_MOCK = process.env.USE_MOCK === "1" || !KEY;
const TTL_MS = 5000; // one upstream call per 5 seconds, however many tabs

// Mock data uses the same shape as the live-match example in the docs
const mock = [
{ match_id: "m1", status: "live", minute: 61,
home: { name: "Manchester City", score: 2 }, away: { name: "Arsenal", score: 1 } },
{ match_id: "m2", status: "live", minute: 34,
home: { name: "Real Madrid", score: 0 }, away: { name: "Barcelona", score: 0 } },
{ match_id: "m3", status: "finished", minute: 90,
home: { name: "Inter", score: 1 }, away: { name: "Milan", score: 1 } },
];

// Advance the fake matches so you can watch scores change
setInterval(() => {
for (const m of mock) {
if (m.status !== "live") continue;
m.minute = Math.min(90, m.minute + 1);
if (Math.random() < 0.1) (Math.random() < 0.5 ? m.home : m.away).score += 1;
if (m.minute === 90) m.status = "finished";
}
}, 3000);

let cache = { at: 0, body: null };

app.get("/api/live", async (_req, res) => {
if (USE_MOCK) return res.json(mock);

const now = Date.now();
if (cache.body && now - cache.at < TTL_MS) return res.json(cache.body);

try {
const r = await fetch(${BASE}${LIVE_PATH}, {
headers: { Authorization: Bearer ${KEY} },
});
if (!r.ok) return res.status(r.status).json({ error: Upstream ${r.status} });
const body = await r.json();
cache = { at: now, body };
res.json(body);
} catch {
res.status(502).json({ error: "Upstream unreachable" });
}
});

app.listen(4000, () => {
console.log(API proxy on http://localhost:4000 (${USE_MOCK ? "mock" : "live"} mode));
});

Start it with npm run server, then open http://localhost:4000/api/live. You should see the mock matches as JSON.

Step 3: The useLiveScores hook (5 min)

All the data-fetching logic lives in one hook, so the UI stays dumb and you can swap polling for a push connection later without touching components.

First, a small normalizer so the UI never depends on the raw API shape. Create src/normalize.js:

js
// Maps the API's live-match shape into the shape our UI uses.
// Check the API reference for the exact response envelope.
export function normalize(raw) {
const list = Array.isArray(raw) ? raw : raw?.data ?? raw?.matches ?? [raw];
return list.filter(Boolean).map((m) => ({
id: m.match_id,
status: m.status,
minute: m.minute ?? null,
home: m.home?.name,
homeScore: m.home?.score ?? 0,
away: m.away?.name,
awayScore: m.away?.score ?? 0,
}));
}

Now the hook. Create src/useLiveScores.js:

js
import { useEffect, useRef, useState } from "react";
import { normalize } from "./normalize";

export function useLiveScores({ liveMs = 5000, idleMs = 30000 } = {}) {
const [matches, setMatches] = useState([]);
const [status, setStatus] = useState("loading"); // loading | ok | error
const [updatedAt, setUpdatedAt] = useState(null);
const timer = useRef(null);

useEffect(() => {
let stopped = false;

function schedule(ms) {
  timer.current = setTimeout(load, ms);
}

async function load() {
  // Don't poll while the tab is hidden
  if (document.hidden) return schedule(idleMs);
  try {
    const res = await fetch("/api/live");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const list = normalize(await res.json());
    if (stopped) return;
    setMatches(list);
    setStatus("ok");
    setUpdatedAt(new Date());
    // Poll fast only while at least one match is live
    schedule(list.some((m) => m.status === "live") ? liveMs : idleMs);
  } catch {
    if (stopped) return;
    setStatus("error");
    schedule(idleMs);
  }
}

// Refresh immediately when the user comes back to the tab
const onVisible = () => {
  if (!document.hidden) {
    clearTimeout(timer.current);
    load();
  }
};

document.addEventListener("visibilitychange", onVisible);
load();

return () => {
  stopped = true;
  clearTimeout(timer.current);
  document.removeEventListener("visibilitychange", onVisible);
};
Enter fullscreen mode Exit fullscreen mode

}, [liveMs, idleMs]);

return { matches, status, updatedAt };
}

Three small decisions make this production-friendly: adaptive intervals (5 s while live, 30 s when idle), no polling in background tabs, and an immediate refresh when the user returns.

Step 4: The UI (6 min)

Create src/MatchCard.jsx. The useRef trick compares the previous score with the new one, so the card flashes only when a goal actually happens:

jsx
import { useEffect, useRef, useState } from "react";

export default function MatchCard({ m }) {
const prev = useRef({ h: m.homeScore, a: m.awayScore });
const [flash, setFlash] = useState(false);

useEffect(() => {
if (prev.current.h !== m.homeScore || prev.current.a !== m.awayScore) {
prev.current = { h: m.homeScore, a: m.awayScore };
setFlash(true);
const t = setTimeout(() => setFlash(false), 1500);
return () => clearTimeout(t);
}
}, [m.homeScore, m.awayScore]);

const live = m.status === "live";

return (

  • {m.home}
    {m.homeScore} – {m.awayScore}
    {m.away}
    {live ? LIVE ${m.minute ?? ""}' : m.status}

  • );
    }

    Replace src/App.jsx:

    jsx
    import { useLiveScores } from "./useLiveScores";
    import MatchCard from "./MatchCard";
    import "./App.css";

    export default function App() {
    const { matches, status, updatedAt } = useLiveScores();

    return (


    Live Football Scores


    {status === "loading" &&

    Loading matches…

    }
    {status === "error" &&

    Connection problem. Retrying…

    }
    {status === "ok" && matches.length === 0 &&

    No matches right now.

    }
      {matches.map((m) => ( ))}

    {updatedAt && Updated {updatedAt.toLocaleTimeString()}}

    );
    }

    Replace src/App.css:

    css
    :root { color-scheme: light dark; font-family: system-ui, sans-serif; }
    main { max-width: 560px; margin: 2rem auto; padding: 0 1rem; }
    ul { list-style: none; padding: 0; display: grid; gap: .75rem; }
    .card {
    display: grid; grid-template-columns: 1fr auto 1fr auto;
    align-items: center; gap: .75rem; padding: .9rem 1rem;
    border: 1px solid #8884; border-radius: 12px;
    }
    .team.away { text-align: right; }
    .score { font-weight: 700; font-size: 1.25rem; font-variant-numeric: tabular-nums; }
    .badge { font-size: .75rem; padding: .2rem .5rem; border-radius: 999px; background: #8883; }
    .badge.live { background: #e11d48; color: #fff; animation: pulse 1.4s infinite; }
    .flash { animation: flash 1.5s ease-out; }
    .warn { color: #b45309; }
    @keyframes pulse { 50% { opacity: .55; } }
    @keyframes flash { 0% { background: #22c55e55; } 100% { background: transparent; } }

    Run npm run dev in a second terminal and open the URL Vite prints. You should see three matches. Within a few seconds the minutes advance, and when a mock goal lands the card flashes green. You now have the whole UI working without spending a single API request.

    Step 5: Switch to real data (3 min)
    Get your key. Request access; after approval you receive an activation link. The access window starts when you open that link, so do this only now that your UI is ready.
    Confirm the endpoint path in the API reference and update ORBISTATS_LIVE_PATH in .env if needed. The live-match example in the documentation uses /football/matches/live.
    Edit .env: set USE_MOCK=0 and paste your key.
    Restart the proxy: npm run server. It should print live mode.

    Reload the page. The same UI now shows real matches. The proxy keeps your key private, and the 5-second cache means ten tabs still cost one upstream call every 5 seconds.

    Football is one of 13 sports. To show another sport, change the path segment (for example /basketball/...) and check the exact route on the sport’s page and in the docs.

    Common problems
    Symptom Likely cause Fix
    401 from the proxy Key missing, wrong, or .env not loaded Start with npm run server (it uses --env-file), and check the Bearer header
    CORS error in the browser console Calling the API directly from React Always call /api/live, never the upstream URL
    Empty scoreboard but no error Response envelope differs from normalize() console.log the raw JSON and adjust the list line
    Cards never flash Unstable React key, so cards remount Use the match id as key, as in App.jsx
    Quota disappears quickly Every tab or user hits the API directly Keep the proxy cache, and keep background-tab polling off
    Access window ended mid-tutorial Activation link opened too early Build in mock mode first, open the link at Step 5
    Finished matches show a raw status text Status values differ from "live" Check status values in the docs and map them to friendly labels
    Taking it further
    Go from polling to push. Because the data logic is isolated in one hook and one proxy, you can replace the proxy’s polling with a WebSocket connection and stream updates to the browser. The WebSocket API docs have the URL and message format, and this walkthrough covers the pattern end to end: Build a Live Sports Scoreboard in 50 Lines of JavaScript with a WebSocket API.
    Use webhooks on your backend if you need to react to events (goals, cards) without keeping a connection open: webhooks API.
    Add fixtures and standings with the Sports Data API so the page shows upcoming matches too.
    New to REST? Start with How to Make Your First API Request.

    Check the numbers on your side. The WebSocket feed targets under 500 ms, but latency depends on your region and network, so measure from where your server runs. Service health is public on the status page, and plan details are on the pricing page.

    Wrap-up

    You built a scoreboard that keeps secrets on the server, shares one upstream call between many users, polls only when it matters, and highlights goals. You also built it in an order that never wastes a request: mock first, real data last.

    If you want to try it on live data, request the free hour and run Step 5. Which would you like next: a WebSocket version of this hook, or an odds ticker on the same scoreboard? Tell me in the comments.

    Top comments (0)