Starter project

Next.js NBA scoreboard with a server-side API key

This tutorial builds a Next.js App Router page that lists today's NBA games using one server-side DunkAPI call, cached for 60 seconds so all visitors share a single request. The key stays in a server-only module and never reaches the browser bundle. Four small files on top of create-next-app.

What you will build

A single page at / that shows today's NBA games. Each row has the away team, the home team and either the tip time in Eastern Time (for games not yet started) or the score and status. If the API is unreachable or the key is missing, the page shows a short message instead of crashing.

Sample page text from a real run on 2026-12-06 (seven games):

NBA scoreboard
2026-12-06
Sacramento Kings    Denver Nuggets          9:00 PM ET
LA Clippers         Minnesota Timberwolves  7:00 PM ET
Los Angeles Lakers  Oklahoma City Thunder   7:00 PM ET
Orlando Magic       Cleveland Cavaliers     6:00 PM ET
Washington Wizards  New York Knicks         6:00 PM ET
Milwaukee Bucks     Utah Jazz               5:00 PM ET
Phoenix Suns        Houston Rockets         3:30 PM ET

On screen it is a plain single-column list on an off-white background: the heading, the date under it, then one grid row per game with the two team names, the two scores right-aligned in bold once a game has started, and a grey status on the right. There is no client-side JavaScript to hydrate beyond what Next.js ships by default.

Prerequisites

  • Node.js 20 or newer (the run below used Node 26 with Next.js 15.5.9).
  • A DunkAPI key. Each page regeneration costs 2 credits.
  • Basic familiarity with React components.

The project

Start from the standard scaffold, then add or replace the files below.

npx create-next-app@15.5.9 nba-scoreboard --ts --app --no-tailwind --eslint --no-src-dir --import-alias "@/*" --use-npm
cd nba-scoreboard
npm i server-only
nba-scoreboard/
  .env.local            DUNKAPI_KEY=...  (not committed)
  app/
    layout.tsx          replaced: plain layout, no web fonts
    page.tsx            replaced: the scoreboard
    globals.css         replaced: a few lines of styling
  lib/
    dunk.ts             new: server-only API client

lib/dunk.ts

// Server-only DunkAPI client. The key never leaves the server.
import "server-only";

const BASE = process.env.DUNKAPI_BASE ?? "https://mcp.dunkapi.com/v1";

export type Game = {
  game_id: string;
  status: string; // "scheduled" | "final" | other in-progress values
  starts_at: string;
  home: { abbrev: string; name: string; score: number | null };
  away: { abbrev: string; name: string; score: number | null };
  venue?: string;
};

export async function listGames(date: string): Promise<Game[]> {
  const key = process.env.DUNKAPI_KEY;
  if (!key) throw new Error("DUNKAPI_KEY is not set");

  const res = await fetch(`${BASE}/list_games`, {
    method: "POST",
    headers: { "x-api-key": key, "Content-Type": "application/json" },
    body: JSON.stringify({ date, limit: 30 }),
    next: { revalidate: 60 }, // reuse the response for 60 seconds across all visitors
  });
  if (!res.ok) throw new Error(`DunkAPI ${res.status}`);

  const body = await res.json();
  return (body.data ?? body).games as Game[];
}

app/page.tsx

import { listGames, type Game } from "@/lib/dunk";

export const revalidate = 60; // regenerate this page at most once a minute

// "Today" in US Eastern, the timezone the API uses for game dates.
function todayEastern(): string {
  return new Date().toLocaleDateString("en-CA", { timeZone: "America/New_York" });
}

function tipTime(iso: string): string {
  return new Date(iso).toLocaleTimeString("en-US", {
    timeZone: "America/New_York",
    hour: "numeric",
    minute: "2-digit",
  }) + " ET";
}

function Row({ g }: { g: Game }) {
  const started = g.status !== "scheduled";
  return (
    <li className="game">
      <span>{g.away.name}</span>
      <strong>{started ? g.away.score : ""}</strong>
      <span>{g.home.name}</span>
      <strong>{started ? g.home.score : ""}</strong>
      <em>{started ? g.status : tipTime(g.starts_at)}</em>
    </li>
  );
}

export default async function Page() {
  const date = todayEastern();
  let games: Game[] = [];
  let error: string | null = null;
  try {
    games = await listGames(date);
  } catch (e) {
    error = e instanceof Error ? e.message : "Could not load games";
  }

  return (
    <main>
      <h1>NBA scoreboard</h1>
      <p>{date}</p>
      {error && <p role="alert">Scores are unavailable right now: {error}</p>}
      {!error && games.length === 0 && <p>No games today.</p>}
      <ul>{games.map((g) => <Row key={g.game_id} g={g} />)}</ul>
    </main>
  );
}

app/layout.tsx

import type { Metadata } from "next";
import "./globals.css";

export const metadata: Metadata = {
  title: "NBA scoreboard",
  description: "Today's NBA games, fetched on the server with a 60 second cache.",
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

app/globals.css

body { font-family: system-ui, sans-serif; margin: 0; background: #fafafa; color: #111; }
main { max-width: 640px; margin: 0 auto; padding: 24px 16px; }
ul { list-style: none; padding: 0; }
.game { display: grid; grid-template-columns: 1fr 2.5rem 1fr 2.5rem 5.5rem; gap: 8px;
        padding: 12px 0; border-bottom: 1px solid #ddd; align-items: center; }
.game strong { text-align: right; }
.game em { color: #555; font-style: normal; text-align: right; }

Create .env.local with one line, DUNKAPI_KEY=your-key-here. The name has no NEXT_PUBLIC_ prefix, which is what keeps it out of browser code.

How to run it

npm run dev          # development, http://localhost:3000
npm run build        # production build
npm start            # serve the production build

In development the page renders on every request. In the production build the page is generated once, served from cache, and regenerated in the background at most once a minute.

How it works

A server-only client. lib/dunk.ts imports server-only, a tiny package that makes the build fail if a client component ever imports the file. That turns a security habit into a compile error. The key is read from process.env.DUNKAPI_KEY, which Next.js only exposes to server code because it lacks the public prefix. The request itself is a POST to the list_games tool with the x-api-key header, so the key only ever travels from your server to the API.

Why `list_games` with a date. The tool returns games for one date with scores and a status, sorted newest first, for 2 credits. It does the job of a scoreboard without needing a separate call per game. The date is computed in US Eastern, because the API groups games by their Eastern date. If you used the visitor's or the server's local date, an evening game could land on the wrong day for anyone outside the Eastern zone.

Two layers of caching. The fetch call carries next: { revalidate: 60 }, which tells Next.js to reuse the response for 60 seconds. The page also exports revalidate = 60, which regenerates the whole page on the same schedule. Together they mean that one request per minute reaches the API no matter how many people load the page. The build output shows this in its route table, which lists / with a one minute revalidate. If you want a longer window on days with no games, raise the number.

Failure handling. listGames throws if the key is missing or the API returns an error. The page catches that and renders a message with role="alert". This matters in one place in particular: when you build without a key, Next.js prerenders the page, and without the catch the build would fail. With it, the build succeeds and the first revalidation after deploy fills in real data.

Status display. A game that has not started shows its tip time. Anything else shows the status string the API returns, for example final. The API documents scheduled and final; the page treats every other value as in progress without guessing at its wording, so it keeps working if the API adds states.

Ways to extend it

  1. Add a date picker. Read a date search parameter in the page, validate it against YYYY-MM-DD, and pass it to listGames. Each date becomes its own cached entry because the request body is part of the cache key.
  2. Show standings beside the scores. Add a getStandings function that calls get_standings (2 credits) and render the top of each conference in a second column. Use a longer revalidate, such as 3,600 seconds, since standings change once per game day.
  3. Link to box scores. Add a route at app/game/[id]/page.tsx that calls get_game (5 credits) and shows both box scores. Give it a longer revalidate for final games.
  4. Add team logos. list_teams returns a logo URL for each team. Fetch it once with a revalidate of a day and match on abbreviation.

Limits and when not to use this

  • Not a live ticker. Freshness is the API's update cadence plus up to 60 seconds of cache. For second-by-second play-by-play, use a different design with a streaming source.
  • Cache is per server instance. On a host that runs several instances or regions, each keeps its own cache, so the call rate scales with instances. At 2 credits a call, budget accordingly.
  • Credit use is steady. One call a minute is about 2,900 credits a day whenever traffic is continuous. For a hobby page, a 5 minute revalidate cuts that to under 600.
  • Eastern dates. The page shows the Eastern date. If you want the viewer's date, you need a client component or a date parameter, and a new cache entry per date.
  • Terms. Showing scores to your own users is fine. Reselling or redistributing the raw data as a feed or API of its own is not. See the DunkAPI documentation for the full terms.
  • One league. The code uses the default league, the NBA. Other leagues take a league parameter and have their own seasons and calendars.

FAQ

Will the API key be exposed to visitors? No. The fetch runs in a server component through a module marked server-only, and the key is read from a non-public environment variable. The build fails if client code imports that module. We checked the built HTML and static chunks for the key.

How many credits does this use? One list_games call costs 2 credits. With a 60 second revalidate, the page makes at most one call a minute per server instance, about 2,900 credits a day if someone is always visiting, however many visitors there are.

Are these scores live? They are as fresh as the API's data plus up to 60 seconds of cache. The page shows whatever status the API reports for each game. It is a scoreboard, not a play-by-play ticker.

Live from the API

Free to embed on your own site, with no key needed. Get the embed code.

Get a free key Or download whole seasons as Parquet

Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.