Most “build a live score app” tutorials make the same mistake in the first five minutes: they call the sports API straight from the browser, which means your API key ships to every visitor.
In this tutorial we’ll build a football dashboard in Next.js (App Router + TypeScript) the right way:
A server-side proxy so the API key never reaches the browser
Fixtures by date, grouped by competition, with search and pagination
A live ticker that refreshes automatically
Caching and error handling so your dashboard survives rate limits
We’ll use the Orbistats Sports Data API, but the architecture works with any REST sports provider.
What We’re Building
Browser (React UI)
│ GET /api/fixtures?date=2026-11-21
▼
Next.js Route Handler ──(adds Bearer key, caches 60s)──► api.orbistats.com/v1
▲
└── JSON back to the UI
The browser only ever talks to your /api/* routes. Your key lives in a server environment variable.
Prerequisites
Node.js 20+
Basic React and TypeScript
An Orbistats API key: request access (the Free plan gives a 1-hour window, plenty to follow along), or try the sandbox first
Step 1: Create the Project
bash
npx create-next-app@latest football-dashboard --typescript --app --eslint
cd football-dashboard
Add your key to .env.local (this file is git-ignored by default):
bash
ORBISTATS_API_KEY=your_api_key_here
Never prefix it with NEXT_PUBLIC_. That prefix exposes a variable to the browser.
Step 2: Types
The fixtures endpoint returns data, meta and pagination. Create lib/types.ts:
ts
export interface Fixture {
fixture_id: string;
home_team: string;
away_team: string;
kickoff: string;
competition: string;
}
export interface FixturesResponse {
data: Fixture[];
meta: { sport: string; count: number };
pagination: {
page: number;
per_page: number;
total_pages: number;
total_results: number;
};
}
export interface LiveMatch {
match_id: string;
status: string;
minute?: number;
home: { name: string; score: number };
away: { name: string; score: number };
}
You don’t need to model every field. Add more as your UI needs them. Check the API reference for the full response fields.
Step 3: A Tiny, Reusable API Client
Create lib/orbistats.ts. This is the only file that knows about authentication.
ts
const BASE_URL = "https://api.orbistats.com/v1";
export class OrbistatsError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
type Params = Record;
export async function orbistats(
path: string,
params: Params = {},
revalidateSeconds = 30
): Promise {
const key = process.env.ORBISTATS_API_KEY;
if (!key) throw new OrbistatsError(500, "ORBISTATS_API_KEY is not set");
const url = new URL(${BASE_URL}${path});
for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== "") url.searchParams.set(k, String(v));
}
const res = await fetch(url, {
headers: { Authorization: Bearer ${key}, Accept: "application/json" },
next: { revalidate: revalidateSeconds }, // server-side cache
});
if (!res.ok) throw new OrbistatsError(res.status, await res.text());
return res.json() as Promise;
}
next: { revalidate } tells Next.js to cache the upstream response. If 500 visitors load the same date within a minute, you make one upstream request instead of 500. That one line protects both your bill and your rate limit.
Step 4: The Fixtures Route Handler
Create app/api/fixtures/route.ts:
ts
import { NextRequest, NextResponse } from "next/server";
import { orbistats, OrbistatsError } from "@/lib/orbistats";
import type { FixturesResponse } from "@/lib/types";
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
export async function GET(req: NextRequest) {
const sp = req.nextUrl.searchParams;
const date = sp.get("date") ?? new Date().toISOString().slice(0, 10);
const page = Math.max(1, Number(sp.get("page") ?? 1));
if (!DATE_RE.test(date)) {
return NextResponse.json({ error: "date must be YYYY-MM-DD" }, { status: 400 });
}
try {
const data = await orbistats(
"/football/fixtures",
{ date, page, per_page: 50 },
60
);
return NextResponse.json(data);
} catch (e) {
if (e instanceof OrbistatsError) {
if (e.status === 429) {
return NextResponse.json({ error: "Busy right now, retry shortly." }, { status: 429 });
}
console.error("Orbistats error", e.status); // never log the key
return NextResponse.json({ error: "Upstream error" }, { status: 502 });
}
return NextResponse.json({ error: "Unexpected error" }, { status: 500 });
}
}
Two details worth copying into every integration:
Validate input before forwarding it upstream.
Translate errors into safe messages. Never return the raw upstream body to the browser.
Step 5: The Live Route
Live scores change every few seconds, so cache briefly. Create app/api/live/route.ts:
ts
import { NextResponse } from "next/server";
import { orbistats, OrbistatsError } from "@/lib/orbistats";
import type { LiveMatch } from "@/lib/types";
export async function GET() {
try {
const json = await orbistats(
"/football/matches/live",
{},
10 // 10-second cache is plenty for a ticker
);
const matches = Array.isArray(json) ? json : json.data ?? [];
return NextResponse.json({ matches });
} catch (e) {
const status = e instanceof OrbistatsError && e.status === 429 ? 429 : 502;
return NextResponse.json({ matches: [], error: "Live data unavailable" }, { status });
}
}
The normalisation line (Array.isArray(json) ? json : json.data) makes the handler tolerant of either response shape. Confirm the final live schema in the documentation.
Step 6: The Live Ticker Component
Create components/LiveTicker.tsx:
tsx
"use client";
import { useEffect, useState } from "react";
import type { LiveMatch } from "@/lib/types";
export default function LiveTicker() {
const [matches, setMatches] = useState([]);
const [error, setError] = useState(false);
useEffect(() => {
let alive = true;
const controller = new AbortController();
async function load() {
try {
const res = await fetch("/api/live", { signal: controller.signal });
const json = await res.json();
if (alive) { setMatches(json.matches ?? []); setError(!res.ok); }
} catch {
if (alive) setError(true);
}
}
load();
const id = setInterval(load, 15_000);
return () => { alive = false; controller.abort(); clearInterval(id); };
}, []);
if (error && matches.length === 0) return
Live scores temporarily unavailable.
;if (matches.length === 0) return
No live matches right now.
;return (
-
{matches.map((m) => (
- {m.home.name} {m.home.score} – {m.away.score}{" "} {m.away.name} {m.minute !== undefined && · {m.minute}'} ))}
);
}
Polling every 15 seconds through your cached route is a sensible starting point. When you need true real-time, move to the WebSocket API or webhooks (more on that at the end).
Step 7: The Fixtures Browser
Create components/Fixtures.tsx with a date picker, search box, grouping and pagination:
tsx
"use client";
import { useEffect, useMemo, useState } from "react";
import type { Fixture, FixturesResponse } from "@/lib/types";
const today = () => new Date().toISOString().slice(0, 10);
export default function Fixtures() {
const [date, setDate] = useState(today());
const [page, setPage] = useState(1);
const [query, setQuery] = useState("");
const [state, setState] = useState<{ loading: boolean; error?: string; res?: FixturesResponse }>({ loading: true });
useEffect(() => {
const controller = new AbortController();
setState((s) => ({ ...s, loading: true, error: undefined }));
fetch(`/api/fixtures?date=${date}&page=${page}`, { signal: controller.signal })
.then(async (r) => {
const json = await r.json();
if (!r.ok) throw new Error(json.error ?? "Request failed");
setState({ loading: false, res: json });
})
.catch((e) => {
if (e.name !== "AbortError") setState({ loading: false, error: e.message });
});
return () => controller.abort();
}, [date, page]);
const grouped = useMemo(() => {
const q = query.trim().toLowerCase();
const items = (state.res?.data ?? []).filter(
(f) => !q || ${f.home_team} ${f.away_team} ${f.competition}.toLowerCase().includes(q)
);
return items.reduce>((acc, f) => {
(acc[f.competition] ||= []).push(f);
return acc;
}, {});
}, [state.res, query]);
const totalPages = state.res?.pagination.total_pages ?? 1;
return (
{ setDate(e.target.value); setPage(1); }} />
setQuery(e.target.value)} />
{state.loading && <p>Loading fixtures…</p>}
{state.error && <p role="alert">⚠️ {state.error}</p>}
{Object.entries(grouped).map(([competition, fixtures]) => (
<div key={competition} style={{ marginBottom: 20 }}>
<h3>{competition}</h3>
<ul>
{fixtures.map((f) => (
<li key={f.fixture_id}>
{new Date(f.kickoff).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}{" "}
— {f.home_team} vs {f.away_team}
</li>
))}
</ul>
</div>
))}
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<button disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>← Prev</button>
<span>Page {page} / {totalPages}</span>
<button disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Next →</button>
</div>
</section>
);
}
Notes:
AbortController cancels in-flight requests when the user changes date quickly, which prevents out-of-order updates (old response overwriting new one).
toLocaleTimeString renders kickoff in the viewer’s timezone. Store and transmit UTC, display locally.
Step 8: Put It Together
Replace app/page.tsx:
tsx
import Fixtures from "@/components/Fixtures";
import LiveTicker from "@/components/LiveTicker";
export default function Home() {
return (
⚽ Football Dashboard
Live now
Fixtures
);
}
Run it:
bash
npm run dev
Open http://localhost:3000, pick a date and you should see fixtures grouped by competition.
Step 9: Make It Production-Ready
Rate limits: the server-side cache above is your first defence. Add per-IP rate limiting to /api/* (for example with Upstash Ratelimit) so your own users can’t burn your quota.
Timeouts: add signal: AbortSignal.timeout(8000) to the upstream fetch.
Secrets: set ORBISTATS_API_KEY in your hosting dashboard (Vercel, Netlify, etc.), never in the repo.
Observability: log status codes and latency, never headers.
Licensing: read the data licensing terms before displaying data publicly.
Going Real-Time and Multi-Sport
Polling is a fine start, but it has limits. For instant updates, subscribe your server to the WebSocket stream and relay to browsers via Server-Sent Events. The Live Scores API is designed for that pattern.
Because the API is multi-sport, turning this into a cricket, tennis or basketball dashboard is mostly a path change. Orbistats covers football, basketball, cricket, tennis and nine more sports, so make sport a route parameter (/api/[sport]/fixtures) and you have a multi-sport app.
Don’t want to build UI at all? Drop-in widgets give you live scores with a snippet.
Related Tutorials
Consuming a Sports Data API in Go with net/http
Build a Cricket Fixtures Finder + Live Scoreboard in Node.js
Recap
You built a football dashboard that:
Keeps the API key server-side
Caches upstream calls to protect quota
Handles errors and cancellation properly
Shows fixtures, grouping, search and pagination
Includes a live ticker you can upgrade to WebSockets
Grab a key via Request Access, follow the quickstart, compare plans on the pricing page, or explore the SDKs.
What sport should I build next? Tell me in the comments. 👇
Top comments (0)