Building an Odds Comparison Widget for Media Sites
An embeddable React widget that shows the best available price per outcome across books, backed by a server-side cache with predictable credit spend, plus compliance notes for publishers.
Sports publishers increasingly put live odds next to their coverage: a game preview with the current spread, a matchup page with moneylines from several books, a futures table in a season preview. Readers expect those numbers to be current, and a stale price on a news site damages trust faster than no price at all.
This post builds a compact odds comparison widget for that job. It shows, for each upcoming game, the best available price per outcome across a set of books you choose, refreshes on a schedule, and costs the same number of credits whether ten readers or ten million load the page. It is a narrower cousin of a full odds screen; if you need every book in every cell, read how to build a real-time odds screen instead.
What the odds comparison widget shows
One row per game, three markets, and for each outcome the best price and which books post it:
| Game | Spread | Total | Moneyline |
|---|---|---|---|
| Away team | +3.5 -105 (Book A) | O 47.5 -108 (Book B) | +155 (Book A, Book C) |
| Home team | -3.5 -110 (Book B) | U 47.5 -110 (Book A) | -170 (Book B) |
That is exactly what /v1/best-lines returns. For every comparable market it gives each outcome's best_price, the best_books tied at that price, and books_quoting, the number of books posting that market. Markets are grouped by key, period and line, so a spread of -3.5 and a spread of -3 are separate groups. Suspended markets are excluded, and a group only appears when at least two books quote it.
If your readers are new to comparing prices, the glossary entries on line shopping, the spread and American odds make good tooltip targets.
Architecture
PreciseAPI /v1/best-lines ──(every 2 min)──▶ your server cache ──▶ /widget/odds/nfl ──▶ React widget on article pages
Three rules shape an odds widget for media sites:
- The API key never reaches the browser. The API allows cross-origin requests, but anything you ship to a page can be read by anyone. Your server calls PreciseAPI; browsers call your server.
- One upstream request per refresh, however much traffic you get. Credit spend is set by your refresh interval, not by page views.
- The browser receives only what it renders. A small, display-ready payload is faster for readers, and it keeps you on the right side of the data license, which does not allow redistributing raw data as a feed.
Choosing the books
The books parameter controls which sources are compared. Most publishers restrict it to operators that are licensed where their readers are, and often to the ones they have commercial relationships with. In the catalog, these sportsbooks carry the regulated tag:
| Book | Source id |
|---|---|
| FanDuel | fanduel |
| DraftKings | draftkings |
| BetMGM | betmgm |
| Caesars | caesars |
| Fanatics | fanatics |
| BetRivers | betrivers |
| Hard Rock Bet | hardrock |
| theScore Bet | thescore |
| BetParx | betparx |
| Circa | circa |
A tag in our catalog is not a legal opinion about any particular state or country. Which operators you may show or link to is your decision. The free /v1/sportsbooks endpoint returns every source with its type and tags, and per-book pages such as FanDuel odds API list coverage. DFS pick'em apps are never included in /v1/best-lines, so the comparison is always sportsbook prices.
Step 1: Fetch and cache on the server
This Express route refreshes each league at most once every two minutes, shares one in-flight request between concurrent visitors, and keeps serving the last good copy if an upstream call fails.
import express from 'express';
const API = 'https://api.preciseapi.com/v1';
const KEY = process.env.PRECISEAPI_KEY;
const BOOKS = ['fanduel', 'draftkings', 'betmgm', 'caesars', 'fanatics', 'betrivers'];
const LEAGUES = new Set(['nfl', 'nba', 'mlb', 'nhl']);
const TTL_MS = 120_000;
async function api(path) {
const res = await fetch(`${API}${path}`, { headers: { Authorization: `Bearer ${KEY}` } });
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.error?.code}`);
return body;
}
const cache = new Map(); // key -> { value, expires }
const inflight = new Map();
function cached(key, ttlMs, load) {
const hit = cache.get(key);
if (hit && hit.expires > Date.now()) return Promise.resolve(hit.value);
if (inflight.has(key)) return inflight.get(key);
const p = load()
.then((value) => (cache.set(key, { value, expires: Date.now() + ttlMs }), value))
.catch((err) => {
if (hit) return hit.value; // stale beats broken; the widget shows its age
throw err;
})
.finally(() => inflight.delete(key));
inflight.set(key, p);
return p;
}
// Display names: /v1/sportsbooks is free, so refresh it daily.
const bookNames = () =>
cached('books', 86_400_000, async () => {
const { data } = await api('/sportsbooks?type=sportsbook');
return Object.fromEntries(data.map((b) => [b.id, b.name]));
});
const app = express();
app.get('/widget/odds/:league', async (req, res) => {
const league = req.params.league;
if (!LEAGUES.has(league)) return res.status(404).json({ error: 'unknown league' });
try {
const payload = await cached(`bl:${league}`, TTL_MS, async () => {
const [names, body] = await Promise.all([
bookNames(),
api(`/best-lines?league=${league}&books=${BOOKS.join(',')}&markets=moneyline,spread,total`),
]);
return toWidget(body, names);
});
// Our own derived payload can sit in a CDN briefly; credit spend is governed by TTL_MS.
res.set('Cache-Control', 'public, max-age=30');
res.json(payload);
} catch {
res.status(503).json({ error: 'odds temporarily unavailable' });
}
});
app.listen(3000);
Step 2: Reduce to a display-ready payload
/v1/best-lines may return more than one spread or total group per game when books sit on different lines. The widget shows one: the line quoted by the most books. Everything else is dropped before it leaves your server.
const KEYS = ['spread', 'total', 'moneyline'];
function mainGroup(markets, key) {
return markets
.filter((m) => m.key === key && m.period === 'full_game')
.sort((a, b) => b.books_quoting - a.books_quoting)[0];
}
function toWidget(body, names) {
const games = body.data
.filter((e) => e.status === 'scheduled')
.slice(0, 12)
.map((e) => ({
id: e.id,
start: e.start_time,
home: e.home.name,
away: e.away.name,
markets: Object.fromEntries(
KEYS.map((k) => [k, mainGroup(e.markets, k)])
.filter(([, m]) => m)
.map(([k, m]) => [
k,
m.outcomes.map((o) => ({
side: o.side,
point: o.point,
price: o.best_price,
books: o.best_books.map((id) => names[id] ?? id),
})),
]),
),
}));
return { updated_at: body.meta.generated_at, games };
}
Filtering to scheduled keeps the widget pre-game. In-play prices move by the second, and a two-minute refresh is too slow to present them honestly.
Step 3: The React component
import { useEffect, useState } from 'react';
const fmt = (n) => (n > 0 ? `+${n}` : `${n}`);
const label = (key, o) =>
key === 'total' ? `${o.side === 'over' ? 'O' : 'U'} ${o.point} ${fmt(o.price)}`
: key === 'spread' ? `${fmt(o.point)} ${fmt(o.price)}`
: fmt(o.price);
function Cell({ market, marketKey, side }) {
const o = market?.find((x) => x.side === side);
if (!o) return <td className="ow-empty">–</td>;
return (
<td>
<span className="ow-price">{label(marketKey, o)}</span>
<span className="ow-books">{o.books.join(', ')}</span>
</td>
);
}
export function OddsWidget({ league, footer }) {
const [data, setData] = useState(null);
const [error, setError] = useState(false);
useEffect(() => {
let alive = true;
const load = () =>
fetch(`/widget/odds/${league}`)
.then((r) => (r.ok ? r.json() : Promise.reject()))
.then((d) => alive && (setData(d), setError(false)))
.catch(() => alive && setError(true));
load();
const t = setInterval(load, 60_000);
return () => { alive = false; clearInterval(t); };
}, [league]);
if (!data) return <div className="ow">{error ? 'Odds unavailable.' : 'Loading odds…'}</div>;
const ageMin = Math.round((Date.now() - Date.parse(data.updated_at)) / 60_000);
return (
<div className="ow">
<table>
<thead><tr><th>Game</th><th>Spread</th><th>Total</th><th>Moneyline</th></tr></thead>
<tbody>
{data.games.flatMap((g) => [
[g.away, 'away', 'over'],
[g.home, 'home', 'under'],
].map(([team, side, totalSide]) => (
<tr key={`${g.id}-${side}`}>
<th scope="row">{team}</th>
<Cell market={g.markets.spread} marketKey="spread" side={side} />
<Cell market={g.markets.total} marketKey="total" side={totalSide} />
<Cell market={g.markets.moneyline} marketKey="moneyline" side={side} />
</tr>
)))}
</tbody>
</table>
<p className="ow-meta">
Best available price among selected books. Updated {ageMin < 1 ? 'just now' : `${ageMin} min ago`}. Odds change frequently.
</p>
{footer && <p className="ow-footer">{footer}</p>}
</div>
);
}
The age line is not decoration. If the upstream call fails, the server keeps serving the last good copy, and the timestamp is how readers know it is old.
Step 4: Embed odds in articles
Bundle the component with a tiny loader so editors can drop it into any article template:
import { createRoot } from 'react-dom/client';
import { OddsWidget } from './OddsWidget.jsx';
for (const el of document.querySelectorAll('[data-odds-widget]')) {
createRoot(el).render(<OddsWidget league={el.dataset.league} footer={el.dataset.footer} />);
}
<div data-odds-widget data-league="nfl"
data-footer="21+ where applicable. Gambling problem? Call 1-800-GAMBLER."></div>
<script src="/widgets/odds-widget.js" defer></script>
If your CMS mixes in third-party scripts or styles you don't control, serve the widget from its own page and embed it with an iframe instead. You lose a little layout flexibility and gain complete isolation.
Rendering and performance
A few details make the difference between an odds comparison widget that feels native and one that feels bolted on:
- Reserve space. Give the container a minimum height matching a typical slate so the article text doesn't jump when the table renders. Layout shift on article pages is both irritating and measurable.
- Server-render when you can. If your article pages are rendered on the server, inline the current payload into the HTML and let the component hydrate from it. Readers see prices immediately, and the first client-side refresh happens on the normal schedule.
- Use real table markup. Row headers with
scope="row"and column headers intheadlet screen readers announce "Spread, Away team, +3.5 -105" instead of a run of numbers. - Keep the bundle small. The component has no dependencies beyond React. If your site doesn't already ship React, a few kilobytes of plain DOM code rendering the same payload works just as well, because the server has done all the work.
Edge cases worth handling
Real slates are messier than the example table. Plan for these before the widget goes on a high-traffic page:
- Missing markets. A group only appears when at least two of your selected books quote it, so early in the week a game may have a moneyline but no total yet. Render a dash rather than hiding the row.
- Ties.
best_bookslists every book at the best price. Show them all, or show the first plus a count, but don't silently pick one. - Kickoff. When a game starts, it disappears from the widget on the next refresh because the server filters to
scheduled. If editors want the row to stay, switch it to a score line using/v1/scoresfrom the sports scores API (1 credit per call) instead of showing in-play prices. - Postponements and schedule changes. Event ids are stable, so key rows by
id, never by team names or start time. - Narrow book lists. With only two or three books selected, many groups will fail the two-book minimum. Six to eight books gives a fuller table for major leagues.
What it costs
/v1/best-lines costs 3 credits per call, and with the shared cache the odds comparison widget makes one call per league per refresh. Reader traffic does not appear anywhere in the formula.
| Refresh interval | Credits / day (24 h) | Credits / 30 days | 30 days, 16 active hours / day |
|---|---|---|---|
| 60 s | 4,320 | 129,600 | 86,400 |
| 120 s | 2,160 | 64,800 | 43,200 |
| 300 s | 864 | 25,920 | 17,280 |
| 600 s | 432 | 12,960 | 8,640 |
One league at a one-minute refresh fits within Edge's 100,000 monthly credits, even around the clock. Several leagues can share one request (league=nfl,nba) as long as the combined slate stays within the 200-event limit; split the response by league on your server. Pausing refreshes overnight, or when a league has no games that day, is the cheapest optimization available. The credits and rate limits guide has worked budgets for every plan, and odds API pricing lists what each plan includes.
Compliance notes for publishers
PreciseAPI is a data provider. It doesn't take bets, isn't affiliated with any operator whose prices appear in the data, and can't tell you what your content may show in a given market. The publisher is responsible for:
- Local law. Whether you may display odds, name operators or link to them depends on where your readers are. Many publishers geo-target the widget or hide it in jurisdictions where betting is not legal.
- Responsible-gambling messaging. Show age and helpline information next to the widget, using the wording required where you publish. The
footerprop exists for that, and its text should vary by region. Our responsible gaming page sets out what we expect from customers. - Affiliate disclosure. If an affiliate odds widget links cells to operators under commercial agreements, say so clearly.
- Accurate framing. "Best line" is arithmetic on posted prices: the highest price among the books you selected at refresh time. It is not a prediction, a pick or advice, and prices can change or be pulled before a reader acts. Avoid copy that implies otherwise.
- Data licensing. The license covers using data in your own applications; redistributing raw or substantially raw data, or offering it as a feed, requires a written agreement. Review the terms before syndicating widgets to other sites.
None of this is legal advice. If odds content is central to your business, have counsel review it for each market you publish in.
Going further
- Add futures boards for season previews using
/v1/futures(2 credits per call), cached for longer because futures move slowly. - Use league pages such as NFL odds API and NBA odds API to check which markets and periods each league supports.
- The odds API for affiliates use case and the odds comparison API page summarize the relevant endpoints, and the quickstart gets you a key.
Frequently asked questions
Can I call the API directly from the widget in the browser?
You can technically, but you shouldn't. Anyone can read a key shipped to a browser, and every page view would cost credits. Proxy through your server and cache.
Does more traffic cost more credits?
No. With a server-side cache, you make one /v1/best-lines call per league per refresh interval regardless of page views. Only the refresh interval and number of leagues affect spend.
Why does the widget show one spread when books disagree on the line?
/v1/best-lines groups markets by line, so books on -3 and -3.5 are compared separately. The widget picks the line quoted by the most books, which avoids comparing prices on different numbers.
Are DFS pick'em apps included in the comparison?
No. /v1/best-lines excludes DFS pick'em sources, so the widget compares sportsbook prices only. Use the books parameter to choose exactly which sportsbooks appear.
Who is responsible for responsible-gambling messaging and legal compliance?
The publisher. PreciseAPI supplies data only. Age requirements, helplines, advertising rules and whether odds may be shown at all depend on where your readers are, and you must handle them in your pages.