How to Build a Football Match Page with Node.js
You are going to build a football match page in Node.js with Express and the SportAPI football API. One page covers the whole life of a match: before kick-off it shows the date, the stadium and the last meetings of the two teams, during the match the score and goals update by themselves, and after full time it adds the team stats and both line-ups.
The whole example is about 200 lines of JavaScript and one main template. It uses the Brazilian Serie A, and the full version of this idea is live at brasileirao.sportapi.ai.

What you need
You need Node.js 20 or newer and a free SportAPI key. Sign up, confirm your e-mail address and copy the key from your dashboard.
Download the complete example and install its two packages, Express and EJS:
cd football-match-page-example
npm installThe app reads your key from the SPORTAPI_KEY environment variable, so the key never ends up in your code. Start it like this:
export SPORTAPI_KEY="YOUR_API_KEY" # on Windows: set SPORTAPI_KEY=YOUR_API_KEY
npm startThen open http://127.0.0.1:3000 in your browser.
See what the API gives you for one match
Send your key in the X-API-Key header. /api/fixtures/{id} returns the match, both teams, the stadium, the coaches and the events in one answer:
curl -H "X-API-Key: YOUR_API_KEY" https://sportapi.ai/api/fixtures/16053417{
"success": true,
"fixture": {
"id": 16053417,
"home_id": 5794,
"away_id": 5784,
"kickoff_utc": "2026-11-06T23:00:00Z",
"status": "FT",
"minute": null,
"home_score": 0,
"away_score": 3,
"ht_home": 0,
"ht_away": 2,
"league_name": "Brazilian Serie A",
"home_team": "Vitória",
"away_team": "Fluminense",
"home_stadium": "Barradão",
"home_city": "Salvador",
"home_coach": "Jair Ventura",
"away_coach": "Marcão",
"penalty_home": null,
"penalty_away": null,
"events": [
{ "event_type": "assist", "team_side": "away", "player_name": "A. Canobbio", "minute": "15'", "extra_info": null },
{ "event_type": "goal", "team_side": "away", "player_name": "J. Savarino", "minute": "15'", "extra_info": "Goal" },
{ "event_type": "yellow_card", "team_side": "home", "player_name": "Mateus Silva", "minute": "44'", "extra_info": null }
]
}
}The status field decides what the page shows. These are the values you will meet:
Scheduled: the match hasn't started.LIVE: the match is on.minuteholds a value like61'orHT.FT,AETandPENS: the match is over, after 90 minutes, extra time or penalties.PostponedandSuspended: the match isn't being played as planned.
Be ready for empty fields. In some leagues a match can be LIVE while minute and the score are still null.
Team stats and line-ups have their own endpoints. Each answer has an available field, so check it before you read data. In our tests both answered "available": false before kick-off and during matches, and they were ready for finished matches. That's why this page asks for them only after full time.
{
"success": true,
"fixture_id": 16053417,
"available": true,
"data": {
"home": { "shots": 11, "shots_on_target": 5, "fouls": 13, "total_passes": 408, "pass_accuracy": 86, "tackles": 6, "saves": 4, "yellow_cards": 2 },
"away": { "shots": 14, "shots_on_target": 7, "fouls": 19, "total_passes": 539, "pass_accuracy": 88.5, "tackles": 9, "saves": 5, "yellow_cards": 0 }
}
}{
"success": true,
"fixture_id": 16053417,
"available": true,
"data": {
"home": {
"starters": [
{ "name": "Lucas Arcanjo", "position": "Goalkeeper", "shirt": 1, "is_captain": true, "mins_played": 90 }
],
"subs": []
},
"away": { "starters": [], "subs": [] }
}
}Write one helper with a cache
All requests go through one file. get() sends the key and keeps each answer in memory for as long as you tell it.
import { mkdir, readFile, writeFile } from 'node:fs/promises';
const API = 'https://sportapi.ai/api';
const KEY = process.env.SPORTAPI_KEY;
if (!KEY) throw new Error('Set the SPORTAPI_KEY environment variable');
const cache = new Map();
const pending = new Map();
async function request(path) {
const res = await fetch(API + path, {
headers: { 'X-API-Key': KEY },
signal: AbortSignal.timeout(10000),
});
if (!res.ok) throw Object.assign(new Error(`${res.status} on ${path}`), { status: res.status });
return res;
}
async function load(path, ttl, saved) {
try {
const data = await (await request(path)).json();
const seconds = typeof ttl === 'function' ? ttl(data) : ttl;
cache.set(path, { data, until: Date.now() + seconds * 1000 });
return data;
} catch (err) {
// API down or limit reached: show the last answer we have
if (saved && err.status !== 404) return saved.data;
throw err;
}
}
// ttl is a number of seconds, or a function that picks it from the answer
export async function get(path, ttl) {
const saved = cache.get(path);
if (saved && saved.until > Date.now()) return saved.data;
// Ten visitors at the same moment share one request
if (!pending.has(path)) {
pending.set(path, load(path, ttl, saved).finally(() => pending.delete(path)));
}
return pending.get(path);
}
// Downloads a team logo once and keeps it on disk
export async function logo(teamId) {
const file = `logos/${teamId}`;
try {
return await readFile(file);
} catch {
const image = Buffer.from(await (await request(`/teams/${teamId}/logo`)).arrayBuffer());
await mkdir('logos', { recursive: true });
await writeFile(file, image);
return image;
}
}Three details matter here:
ttlcan be a function. The helper reads the answer first and then decides how long to keep it, which the match page needs.pendingholds requests that are still running. If ten people open a page at the same moment, your app sends one request to the API, not ten.- If the API can't be reached or you hit your limit,
get()returns the last answer it has, so the page still works.
Keep your API key on the server. Never call the API from JavaScript in the browser: every visitor would be able to see your key.
Start the Express app
server.js starts with the settings. The API gives kick-off times in UTC, and Intl.DateTimeFormat turns them into the time zone of your readers. matchUrl() makes a readable address such as /match/vitoria-vs-fluminense-16053417, with the match ID at the end.
import express from 'express';
import { get, logo } from './sportapi.js';
const LEAGUE = 36; // Brazilian Serie A
const TIME_ZONE = 'America/Sao_Paulo';
const SITE = process.env.SITE_URL || 'http://127.0.0.1:3000';
const FINISHED = ['FT', 'AET', 'PENS'];
const app = express();
app.set('view engine', 'ejs');
app.use(express.static('public', { maxAge: '1h' }));
const kickoffText = new Intl.DateTimeFormat('en-GB', {
timeZone: TIME_ZONE, weekday: 'short', day: 'numeric', month: 'short',
year: 'numeric', hour: '2-digit', minute: '2-digit',
});
const LETTERS = { ø: 'o', æ: 'ae', ß: 'ss', ł: 'l', đ: 'd', ı: 'i' };
const slugify = (s) => s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
.replace(/[øæßłđı]/g, (c) => LETTERS[c]).replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
const matchUrl = (id, home, away) => `/match/${slugify(home)}-vs-${slugify(away)}-${id}`;List the matches
/api/leagues/36 returns the league with its last 20 results and next 20 matches, so one request is enough for the start page.
app.get('/', async (req, res) => {
const league = await get(`/leagues/${LEAGUE}`, 300);
res.render('list', { league, matchUrl, SITE });
});
Keep each answer for the right time
A finished match barely changes, and a live one changes all the time. So the cache time depends on the status in the answer:
function fixtureTtl({ fixture: f }) {
if (FINISHED.includes(f.status)) return 6 * 3600;
if (f.status === 'LIVE') return 60;
// Check every minute from half an hour before kick-off
return Date.parse(f.kickoff_utc) - Date.now() < 30 * 60 * 1000 ? 60 : 3600;
}
// Stats and line-ups can arrive a little after full time
const extrasTtl = (answer) => (answer.available ? 24 * 3600 : 600);Live data in the API changes about once a minute, so asking more often gains nothing. A match that starts in the next half hour is checked every minute too. Without that, the page could keep showing "vs" long after kick-off.
Stats and line-ups are kept for a day once they are there. If a finished match doesn't have them yet, the app asks again in ten minutes.
Build the timeline
The events list has goals, assists, cards and substitutions, each with a team_side. Substitutions are only there for some matches, so this page leaves them out and shows goals and cards.
An assist comes as its own event with the same minute and side as its goal, so the code puts the two together. Minutes in stoppage time look like 45'+2, and minuteValue() turns them into numbers that sort correctly.
const minuteValue = (minute) => {
const [base, extra = 0] = String(minute).replace(/'/g, '').split('+').map(Number);
return base + extra / 100;
};
function timeline(events) {
const assists = events.filter((e) => e.event_type === 'assist');
return events
.filter((e) => ['goal', 'yellow_card', 'red_card'].includes(e.event_type))
.map((e) => ({
...e,
assist: e.event_type === 'goal' && e.extra_info !== 'Own Goal'
? assists.find((a) => a.minute === e.minute && a.team_side === e.team_side)?.player_name
: undefined,
}))
.sort((a, b) => minuteValue(a.minute) - minuteValue(b.minute));
}extra_info tells you the kind of goal: Goal, Penalty or Own Goal. An own goal is listed under the team that got the goal, so you can add it to that side without any extra logic.
Write the title and structured data
This is where a match page earns its search traffic. People search for different things before and after a match, so each state gets its own title and description. The SportsEvent block tells search engines the teams, the date and the place in a form they can read without guessing.
function seoText(f, kickoff) {
const match = `${f.home_team} vs ${f.away_team}`;
const score = `${f.home_team} ${f.home_score}-${f.away_score} ${f.away_team}`;
if (FINISHED.includes(f.status)) {
return {
title: `${score}: goals, stats and line-ups`,
description: `${score} in the ${f.league_name}, played on ${kickoff}. See who scored, the team stats and both line-ups.`,
};
}
if (f.status === 'LIVE') {
return {
title: `Live: ${match}, score and goals`,
description: `Follow ${match} live in the ${f.league_name}: the score, goals and cards as they happen.`,
};
}
return {
title: `${match}: kick-off time and past meetings`,
description: `${match} in the ${f.league_name} kicks off on ${kickoff}. See the stadium and the last meetings of the two teams.`,
};
}
function jsonLd(f, canonical) {
const data = {
'@context': 'https://schema.org',
'@type': 'SportsEvent',
name: `${f.home_team} vs ${f.away_team}`,
url: canonical,
sport: 'Soccer',
startDate: f.kickoff_utc,
eventStatus: `https://schema.org/${f.status === 'Postponed' ? 'EventPostponed' : 'EventScheduled'}`,
homeTeam: { '@type': 'SportsTeam', name: f.home_team },
awayTeam: { '@type': 'SportsTeam', name: f.away_team },
location: { '@type': 'Place', name: f.home_stadium, address: f.home_city },
};
return JSON.stringify(data).replace(/</g, '\\u003c');
}The replace() on the last line stops a team name from closing the script tag. Test the result with the Schema Markup Validator.
Build the match route
The route gets the match first and then the other three blocks at the same time with Promise.all. Stats and line-ups are skipped until the match is over.
const STATS = [
['shots', 'Shots'], ['shots_on_target', 'Shots on target'], ['total_passes', 'Passes'],
['pass_accuracy', 'Pass accuracy', '%'], ['tackles', 'Tackles'], ['saves', 'Saves'],
['fouls', 'Fouls'], ['yellow_cards', 'Yellow cards'],
];
// A missing block must not take the whole page down
const optional = (promise) => promise.catch(() => null);
app.get('/match/:slug', async (req, res) => {
const id = req.params.slug.split('-').pop();
if (!/^\d+$/.test(id)) return res.status(404).render('error', { message: 'Match not found' });
const { fixture: f } = await get(`/fixtures/${id}`, fixtureTtl);
const path = matchUrl(f.id, f.home_team, f.away_team);
if (req.path !== path) return res.redirect(301, path);
const finished = FINISHED.includes(f.status);
const [stats, lineups, h2h] = await Promise.all([
finished ? optional(get(`/fixtures/${id}/stats`, extrasTtl)) : null,
finished ? optional(get(`/fixtures/${id}/lineups`, extrasTtl)) : null,
optional(get(`/fixtures/h2h/${f.home_id}/${f.away_id}`, 6 * 3600)),
]);
const kickoff = kickoffText.format(new Date(f.kickoff_utc));
const past = (h2h?.data ?? []).filter((m) => m.id !== f.id && FINISHED.includes(m.status)).slice(0, 5);
res.render('match', {
f, kickoff, finished, past, matchUrl, STATS,
events: timeline(f.events ?? []),
stats: stats?.available ? stats.data : null,
lineups: lineups?.available ? lineups.data : null,
seo: seoText(f, kickoff),
canonical: SITE + path,
ld: jsonLd(f, SITE + path),
});
});Three things keep the page solid:
- If someone opens the match with a wrong or old address, the 301 redirect sends them to the correct one, so each match has a single URL.
optional()means that if the last meetings can't be loaded, the page opens without that block instead of failing.- Express 5 passes errors from
asyncroutes to the error handler by itself, so the routes need notryandcatch.
The template shows each block only when there is data for it:
<%- include('_top', { title: seo.title, description: seo.description, canonical, ld }) %>
<main data-status="<%= f.status %>">
<p class="crumb"><a href="/">Matches</a> / <%= f.league_name %></p>
<h1 class="title"><%= f.home_team %> vs <%= f.away_team %></h1>
<section id="score" class="score">
<div class="side"><img src="/logos/<%= f.home_id %>" alt="" width="64" height="64"><span><%= f.home_team %></span></div>
<div class="result">
<% if (f.status === 'Scheduled') { %>
<b class="vs">vs</b>
<% } else if (f.home_score === null) { %>
<b>–</b>
<% } else { %>
<b><%= f.home_score %> - <%= f.away_score %></b>
<% } %>
<% if (f.status === 'LIVE') { %>
<span class="live"><%= f.minute || 'Live' %></span>
<% } else if (finished) { %>
<span><%= { FT: 'Full time', AET: 'After extra time', PENS: 'After penalties' }[f.status] %></span>
<% } else if (f.status !== 'Scheduled') { %>
<span><%= f.status %></span>
<% } %>
<% if (f.penalty_home !== null) { %><small>Penalties <%= f.penalty_home %> - <%= f.penalty_away %></small><% } %>
<% if (finished && f.ht_home !== null) { %><small>Half time <%= f.ht_home %> - <%= f.ht_away %></small><% } %>
</div>
<div class="side"><img src="/logos/<%= f.away_id %>" alt="" width="64" height="64"><span><%= f.away_team %></span></div>
</section>
<ul class="facts">
<li><time datetime="<%= f.kickoff_utc %>"><%= kickoff %></time></li>
<% if (f.home_stadium) { %><li><%= f.home_stadium %>, <%= f.home_city %></li><% } %>
<% if (f.home_coach && f.away_coach) { %><li>Coaches: <%= f.home_coach %>, <%= f.away_coach %></li><% } %>
</ul>
<section id="events">
<% if (events.length) { %>
<h2>Goals and cards</h2>
<ol class="events">
<% for (const e of events) { %>
<li class="<%= e.team_side %>">
<span class="min"><%= e.minute %></span>
<i class="ico <%= e.event_type %>"></i>
<span><b><%= e.player_name %></b>
<% if (e.extra_info === 'Penalty' || e.extra_info === 'Own Goal') { %><small>(<%= e.extra_info.toLowerCase() %>)</small><% } %>
<% if (e.assist) { %><small>assist: <%= e.assist %></small><% } %>
</span>
</li>
<% } %>
</ol>
<% } %>
</section>
<% if (stats) { %>
<h2>Team stats</h2>
<div class="stats">
<% for (const [key, label, unit = ''] of STATS) { %>
<% const h = Number(stats.home[key]) || 0, a = Number(stats.away[key]) || 0, share = h + a ? (h / (h + a)) * 100 : 50; %>
<div class="stat">
<b><%= h %><%= unit %></b><span><%= label %></span><b><%= a %><%= unit %></b>
<div class="bar"><i style="width:<%= share.toFixed(1) %>%"></i></div>
</div>
<% } %>
</div>
<% } %>
<% if (lineups) { %>
<h2>Line-ups</h2>
<div class="teams">
<% for (const [side, name] of [['home', f.home_team], ['away', f.away_team]]) { %>
<div>
<h3><%= name %></h3>
<ul class="squad">
<% for (const p of lineups[side].starters) { %>
<li><span class="no"><%= p.shirt %></span> <%= p.name %><%= p.is_captain ? ' (C)' : '' %> <small><%= p.position %></small></li>
<% } %>
</ul>
<h4>Substitutes</h4>
<ul class="squad subs">
<% for (const p of lineups[side].subs) { %>
<li><span class="no"><%= p.shirt %></span> <%= p.name %></li>
<% } %>
</ul>
</div>
<% } %>
</div>
<% } %>
<% if (past.length) { %>
<h2>Last meetings</h2>
<ul class="list">
<% for (const m of past) { %>
<li><a href="<%= matchUrl(m.id, m.home_team, m.away_team) %>"><span><%= m.date %></span> <%= m.home_team %> <b><%= m.home_score %> - <%= m.away_score %></b> <%= m.away_team %></a></li>
<% } %>
</ul>
<% } %>
</main>
<script src="/live.js" defer></script>
<%- include('_bottom') %>The stats and line-ups appear after full time:


Before kick-off the same template gives a much shorter page:

Update the score during the match
The browser must not call the API, because that would expose your key. It doesn't need to. This small script asks your own server for the same page once a minute and swaps in the parts that changed:
// While a match is on, fetch this same page once a minute and swap the parts that change
if (document.querySelector('main').dataset.status === 'LIVE') {
setInterval(async () => {
const res = await fetch(location.href, { cache: 'no-store' }).catch(() => null);
if (!res?.ok) return;
const page = new DOMParser().parseFromString(await res.text(), 'text/html');
// The match ended: reload to get the stats and line-ups
if (page.querySelector('main').dataset.status !== 'LIVE') return location.reload();
for (const id of ['score', 'events']) {
document.getElementById(id).replaceWith(page.getElementById(id));
}
}, 60000);
}The server has only one way of drawing a match, the template you already have, so there is no second version to keep in step. Each refresh comes from the cache: a thousand people watching the same match still cost one API request a minute. When the status stops being LIVE, the script reloads the page to bring in the stats and line-ups.

Serve the logos and handle errors
/api/teams/{id}/logo returns the logo of a team. The app downloads each one once and keeps it in the logos folder. Most logos are PNG files and some are SVG, and a browser won't show an SVG file sent as PNG, so the route checks the first byte.
app.get('/logos/:id', async (req, res) => {
if (!/^\d+$/.test(req.params.id)) return res.sendStatus(404);
const image = await logo(req.params.id);
// Most logos are PNG files, some are SVG: an SVG file starts with "<"
res.type(image[0] === 0x3c ? 'svg' : 'png').set('Cache-Control', 'public, max-age=604800').send(image);
});The last part of server.js shows a clear message when a match doesn't exist or the data can't be loaded:
app.use((err, req, res, next) => {
if (err.status === 404) return res.status(404).render('error', { message: 'Match not found' });
console.error(err.message);
res.status(503).render('error', { message: 'The data is not available right now. Please try again in a minute.' });
});
app.listen(process.env.PORT || 3000, '127.0.0.1');Run it on a server
On a server, keep the app running with a process manager such as PM2. Use one process: the cache lives in the memory of the process, and each extra process would keep its own copy and make its own requests.
npm install -g pm2
SPORTAPI_KEY=YOUR_API_KEY SITE_URL=https://example.com pm2 start server.js --name match-pageThen let nginx pass the requests to it:
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}Set SITE_URL to your real address, so the canonical links and the structured data point to it.
Stay within your request limit
The free plan includes 1,000 requests a day and 7,000 a month. Here is what this page costs:
- A match before kick-off: 2 requests when someone opens it, then about one an hour.
- A live match: 1 request a minute, but only while someone has the page open. That's about 115 requests for a whole match.
- A finished match: 4 requests the first time, then a few a day at most.
- Each team logo: 1 request, once.
One match at a time fits the free plan easily. Ten live matches watched from start to finish on the same day come to about 1,150 requests, which is over the daily limit, and a crawler that opens all 380 matches of a season needs about 1,500. For a public site, pick a bigger plan or make the pages in advance. brasileirao.sportapi.ai refreshes its data on a schedule and serves ready HTML files, so visitors and crawlers never cause a request.

Where to go next
- Save finished matches to files or a database, so they survive a restart of the app.
- Change
LEAGUEto show another competition./api/leagueslists them all. - Add a list of today's matches from
/api/fixtures/date/{date}, with links to these pages. - Link the player names to player pages with
/api/players/{slug}.
The full list of endpoints is in the API documentation, and the Football API page shows which leagues and data are covered.