Widget guides / React
Chat widget on your website: React and Next.js
Add one React component to your app and visitors get a chat that answers questions about matches, teams and players, with stats and your prices. This guide covers every setting, callback and object the React package gives you. If your site is not a React app, use the script tag guide instead.
Checklist:
- Get your operator id, public key and widget origin from your SensibleStats contact.
- Send your contact every origin you test and go live on.
- Install the package, render
<StatsWidget>withbaseUrlset, and pass the signed-in visitor's id. - Set
onAddToSlip, then test an add, a duplicate and a reject. - Set
onUnavailable, and add our hosts to your Content Security Policy.
1. What your visitors get#
- A chat icon in a bottom corner, with a teaser beside it: a short greeting about a game, often with one of your prices and a few suggested questions.
- A chat panel where visitors ask in their own words and get answers as text and cards: stats, form, line-ups, standings and your prices.
- Add to slip. A price in the chat carries a button that hands the selection to your code (section 7).
Terms used in this guide:
- Operator id and public key identify your account to our server.
- Widget origin is the address of our server for your account, shown here as
https://your-widget-host. - Teaser is the short greeting bubble next to the chat icon.
- Bet slip (or slip) is the list of selections a visitor collects on your site before placing a bet.
- Price is your odds for one selection.
matchOddsIdis your sportsbook's own id for one selection: one outcome of one market.operatorUserIdis your id for the signed-in visitor (section 5).
2. Before you start#
You need three values from your SensibleStats contact and must send them one list.
| From us | Example | What it is |
|---|---|---|
| Operator id | YOUR_OPERATOR_ID | Your account in our system. Part of every request. |
| Public key | YOUR_PUBLIC_KEY | Identifies your widget. Safe to ship in your app's bundle; it only works on your allowed domains. |
| Widget origin | https://your-widget-host | The address the chat talks to. Goes in baseUrl. |
| To us | Example | What it is |
|---|---|---|
| Allowed domains | https://www., https://staging. | Every origin where the widget runs: scheme and host (and port, if not the default). No paths. A page on any other origin gets no widget. |
Test before you go live. Send your SensibleStats contact every origin you test on, including
http://localhost:3000 and your staging host. Matching is exact: https://example.com and
https://www.example.com are two entries, and wildcards don't work.
3. Add the widget#
npm install @sensiblestats/widget-react @sensiblestats/widget-sdk
# or
yarn add @sensiblestats/widget-react @sensiblestats/widget-sdkUse @sensiblestats/widget-react 0.161.0 or later. react and react-dom 18 or 19 are peer
dependencies. @sensiblestats/widget-react brings @sensiblestats/widget-sdk with it; add it
yourself only to import its types (SlipSelection, AddToSlipResult, Teaser, PriceResult,
UnavailableReason), which the React package does not re-export. The event types
(WidgetTrackingEvent, WidgetTrackingEventName, AddToSlipOutcome) come from
@sensiblestats/widget-react itself.
Create the host object once, in its own file, so every component imports the same one:
// widget-host.ts
import { createWidgetHost } from '@sensiblestats/widget-react'
export const widgetHost = createWidgetHost()Render <StatsWidget> once, in a part of your app that stays mounted while visitors move between
pages: your app shell or root layout, not a routed page. Unmounting it closes the chat and stops it.
'use client'
import { StatsWidget, type StatsWidgetConfig } from '@sensiblestats/widget-react'
import type { AddToSlipResult, SlipSelection } from '@sensiblestats/widget-sdk'
import { widgetHost } from './widget-host'
const SLIP_SPORTS = ['basketball', 'tennis'] as const
async function addToSlip(selection: SlipSelection): Promise<AddToSlipResult> {
try {
await mySlip.add(selection.matchOddsId)
return { status: 'added' }
} catch {
return { status: 'rejected', reason: 'not_found' }
}
}
export const baseConfig: StatsWidgetConfig = {
operatorId: 'YOUR_OPERATOR_ID',
publicKey: 'YOUR_PUBLIC_KEY',
baseUrl: 'https://your-widget-host',
greetingMessage: 'hello',
onAddToSlip: addToSlip,
slipSports: SLIP_SPORTS,
}
export function ChatWidget({ userId }: { userId?: string }) {
const config: StatsWidgetConfig = {
...baseConfig,
userContext: { operatorUserId: userId, defaultLanguage: 'en-GB' },
page: { sport: 'football', kind: 'match', matchId: 19432556 },
}
return <StatsWidget config={config} host={widgetHost} />
}Names that start with my or My stand for your own code.
baseUrl is required and there is no default address. Without it, or with a blank value, the widget
logs [StatsWidget] failed to initialize: [StatsWidgetClient] baseUrl is required and renders
nothing.
Next.js App Router. The package does not mark itself as a client component, so put
'use client' at the top of the file that renders <StatsWidget>, as above, and render that file
from your root app/layout.tsx. Build config inside the client file: functions such as
onAddToSlip cannot be passed from a Server Component as props. The root layout is not rendered
again on navigation, so the chat stays open across pages.
createWidgetHost() touches no browser API, so creating the host at module scope is safe when
Next.js renders on the server.
Keep these stable. The widget rebuilds its slip handling when onAddToSlip or slipSports
changes identity, and reattaches when host does. Define them at module scope (as above) or with
useMemo/useCallback. onEvent, onTeaser, onUnavailable and onControl are read fresh
every time, so a new function each render is fine.
4. Settings#
Every setting is a field of the config prop (StatsWidgetConfig).
Required#
| Field | Type | What it does |
|---|---|---|
operatorId | string | Your operator id. |
publicKey | string | Your public key. |
baseUrl | URL | The widget origin: https://your-widget-host. |
With any of the three empty, the widget logs [StatsWidget] failed to initialize: followed by
operatorId is required, publicKey is required or baseUrl is required, and renders nothing.
Visitor, language and time#
| Field | Type | Default | What it does |
|---|---|---|---|
userContext. | string | none | The signed-in visitor's id in your system. See section 5. |
userContext. | string | none | Your own id for a visitor who is not signed in. See section 5. |
userContext. | language tag, e.g. en-GB, tr | your account's default language (English unless you asked for another) | The language of the chat and its answers. |
locale | language tag | none | The same as userContext.; when both are set, locale wins. |
timeZone | IANA zone, e.g. Europe/ | the browser's zone | Kick-off times and day names follow this zone. An unknown zone falls back to the browser's. |
oddsFormat | decimal, american, fractional | decimal | How prices are written. A visitor who picks a format in the chat's settings keeps their choice. |
userContext.oddsFormat exists in the type but does nothing; use oddsFormat.
The chat thread is kept per language. Changing the language while the widget is mounted moves the visitor to that language's thread, or starts a new one.
Greeting and page#
| Field | Type | Default | What it does |
|---|---|---|---|
greetingMessage | string | none | The widget sends this once when it mounts, and the answer becomes the teaser. Use hello. Without it there is no greeting and no teaser. |
greeting | string | none | Fixed text shown in the teaser while there is no greeting answer. |
page | object | none | The page the visitor is on, so the greeting can lead with it. Section 6. |
placeholder | string | localized | Text in the empty question box. |
starters | string array | none | Suggested questions shown in an empty chat. |
Look#
| Field | Type | Default | What it does |
|---|---|---|---|
theme | light, dark, auto | auto | auto follows the visitor's system setting. A visitor who picks a theme in the chat keeps their choice. |
colors | { light?, dark? } | see section 10 | Your colours per theme. |
logoUrl | URL | our mark | Your logo, shown on the icon and in the panel header. |
headerTitle | string | SensibleStats | The panel's title. |
position | left, right | right | Which bottom corner the icon sits in. |
offset | { x?, y? }, numbers in px | { x: 20, y: 20 } | Distance from the side and from the bottom of the window. |
radius | number, px | 16 | Corner radius of the panel. |
launcher | boolean | true | false hides our icon and teaser so you draw your own (section 8). |
launcherLabel | string | "Chat with SensibleStats", localized | The icon's label for screen readers. |
pinIcon | pin, star, bookmark | pin | The icon visitors tap to follow a match or price. |
injectStyles | boolean | true | false stops the widget adding its stylesheet, so you load it yourself (section 12). |
Slip, callbacks and events#
| Field | Type | What it does |
|---|---|---|
onAddToSlip | ( | Adds a price to your bet slip. Without it prices show with no button. Section 7. |
slipSports | array of basketball, americanfootball, tennis | The sports your onAddToSlip accepts besides football. Section 7. |
onTeaser | ( | Gives you the teaser to draw yourself. Section 8. |
onUnavailable | ( | Tells you the chat cannot start. Section 11. |
onEvent | ( | Every widget event, for your own analytics. Section 9. |
eventText | boolean, default false | Adds the visitor's question text to question_asked events. Answer text is never sent. |
transport | { client?, fetch? } | Advanced. fetch replaces the network call the widget makes, for example to observe it. Leave it out unless your contact asks for it. |
onOpenMatch | function | Deprecated and never called. Kept so older code still compiles. |
An oddsFormat outside the allowed list reads as decimal. An empty colour value is ignored.
5. The signed-in visitor#
Pass your id for the signed-in visitor in userContext.operatorUserId. Use a random, non-guessable
id that never changes for that account and that you map to the customer on your side (a UUID works).
Never use a customer number, email address or name: the id comes from the visitor's browser, and
anyone who knows it can act as that visitor. It must be 1 to 128 printable ASCII characters; any
other value is not sent.
With the id, the visitor's chat, followed matches and favourites belong to their account, and the greeting can lead with the teams and markets they bet on.
Visitors who are not signed in can use the chat today. The React widget does not make an id for
them: to give such a visitor favourites, pass your own random id in userContext.anonymousUserId
(same rules as above). With neither id, favourites are off. A signed-in visitor will be required in a
later release, as it already is in our mobile apps, so plan for it now.
When the visitor signs in, signs out or switches account, pass the new operatorUserId (or
none). The widget then:
- starts again for that visitor, without a remount;
- shows that visitor's own chat thread if they used it in the last hour, or greets them afresh;
- switches to that visitor's followed matches;
- clears its "In slip" marks.
The same rebuild happens when operatorId, publicKey, baseUrl, anonymousUserId or timeZone
changes.
6. The page the visitor is on#
Tell the widget which page it sits on and the greeting leads with that game, competition or sport.
| Field | Type | Meaning |
|---|---|---|
sport | football, basketball, americanfootball, tennis | Required when page is set. |
kind | section, competition, match | A sport's front page, a competition page, or a match page. Absent reads as section. |
matchId | number or string | Your sportsbook's id for the match on a match page. |
competitionId | number or string | Your sportsbook's id for the competition on a competition page. |
In a single-page app, pass the new page on every route change, or leave page out on a page that
is about no sport. If the visitor has not typed or tapped anything yet, the widget greets again for
the new page (after 300 ms, so quick changes count once). Once they have, a page change does not
re-greet.
7. Add to slip#
The chat shows your prices, and with onAddToSlip set, each price gets an "Add to slip" button.
This is how a tap reaches your slip:
- The visitor taps "Add to slip" under a price.
- The widget calls
onAddToSlip(selection).selection.matchOddsIdis your sportsbook's own id for that selection, so you can look it up directly. - Your code adds that selection to your slip and returns what happened, or a promise of it.
- The widget shows the visitor a short note in their language, such as "Added to slip".
You have 10 seconds to answer. No answer in time, an error thrown, or an answer that is not one of the results below counts as a failure: the visitor sees "Couldn't add to slip. Try again."
We don't cancel your handler at 10 seconds, so give your slip call its own timeout under 10 seconds, and don't add the selection after it fires.
What the widget sends: SlipSelection
| Field | Type | Meaning |
|---|---|---|
matchOddsId | number | Your sportsbook's id for the selection. Look it up in your slip. |
matchId | number | Your sportsbook's id for the match. |
oddsDecimal | number | The price the visitor saw, as a decimal. Always set. |
odds | { format, text }, optional | The same price in your oddsFormat (not the visitor's own pick), e.g. { format: 'american', text: '+150' }. Absent when we have no text in that format: use oddsDecimal. |
quotedAtUtc | ISO time, optional | When that price was last confirmed. |
sport | basketball, americanfootball, tennis, optional | Absent for football. |
tour | string, optional | Tennis only: the tour the match id belongs to. |
conversationId, insightId | string, optional | Which chat and which card the tap came from. |
display | object, optional | The pick in words, for showing only: home, away, kickoffUtc, market, marketLabel, selection, line, player. Never price or settle a bet from these. |
What you return: AddToSlipResult
| Return | When | The visitor sees (English) |
|---|---|---|
{ status: 'added' } or nothing | The selection is in the slip. You can add slip: { selectionCount, totalOddsDecimal }; it is not shown to the visitor today. | Added to slip |
{ status: 'duplicate' } | It was already in the slip. | Already in your slip |
{ status: 'price_changed', newOdds: '2.10', accepted: true } | The price moved and you added it at the new price. newOdds is the new price as text. | Added at 2.10 (was 1.95) |
{ status: 'price_changed', newOdds: '2.10', accepted: false } | The price moved and you did not add it. | Price moved to 2.10 (was 1.95). Tap to add. |
{ status: 'rejected', reason, message? } | You did not add it. reason is one of the values below. | See below |
reason | Meaning | The visitor sees (English) |
|---|---|---|
login_required | The visitor must sign in first. | Sign in to add to your slip |
suspended | The market is suspended. | Market suspended |
closed | The market or match is closed, e.g. it has started. | Your message, else "This selection can't be added." |
not_found, limit, unsupported | You don't know this selection; the slip is full or a limit is reached; you don't take this kind of selection. | Your message, else "Couldn't add to slip. Try again." |
Other languages show the same notes, translated. message is your own text, shown as is: write it
in the visitor's language. It is ignored for login_required and suspended.
An added or duplicate selection shows "In slip" on its button. Without a host (below), that stays
until the page reloads.
Other sports. Football prices get the button once onAddToSlip is set. Basketball, American
football and tennis prices get it only when slipSports lists that sport, as in section 3, so a
handler that only knows football never receives them.
For these sports the prices come from our own data, so matchOddsId and matchId are our ids, not
your sportsbook's. Find the selection from display (teams, kick-off, market, selection and line)
and tour for tennis, and return not_found when you cannot. Branch on sport: a basketball id can
equal a football id.
Telling the widget what happened next (optional). These calls go through the host object from
section 3, passed as the host prop. Only an object made by createWidgetHost() works; an object
you build yourself is ignored. Use one host for one mounted widget.
| Call | When |
|---|---|
widgetHost. | The visitor removed a selection from your slip, "clear all" included. Clears its "In slip" mark. |
widgetHost. | The visitor placed a bet. Pass every leg; the widget reports only the ones it added, at most 25. |
widgetHost. | The visitor opened a match page. Counts only after the visitor has opened the chat in that tab, at most once per match every 30 minutes. |
Ids must be positive whole numbers; others are ignored, numeric strings included. Echo sport back
for a non-football leg. stake and totalOdds must be numbers and currency, betId and
betType strings; a field of another type is dropped. No method throws.
Calls made while no widget is mounted are kept (the last 20) and sent once one mounts. They live in the page, so a full page load drops them.
8. The icon and teaser#
By default the widget draws its own icon and teaser. To draw them yourself, in your site's design,
set launcher: false, pass onTeaser and the host, and take the open and close controls from
onControl:
'use client'
import { useRef, useState } from 'react'
import { StatsWidget, type PanelControl } from '@sensiblestats/widget-react'
import type { Teaser } from '@sensiblestats/widget-sdk'
import { widgetHost } from './widget-host'
import { baseConfig } from './ChatWidget'
export function ChatWithMyLauncher({ userId }: { userId?: string }) {
const [teaser, setTeaser] = useState<Teaser | null>(null)
const panel = useRef<PanelControl | null>(null)
return (
<>
<MyLauncher
teaser={teaser}
onShown={() => widgetHost.teaserShown()}
onIconClick={() => panel.current?.open()}
onAsk={(index: number) => widgetHost.tapAsk(index)}
onClose={() => widgetHost.dismissTeaser()}
/>
<StatsWidget
config={{ ...baseConfig, userContext: { operatorUserId: userId }, launcher: false, onTeaser: setTeaser }}
host={widgetHost}
onControl={(control) => { panel.current = control }}
/>
</>
)
}onTeaser receives a Teaser when there is one, and null when it is gone (and when the widget
unmounts). It is also called when you keep our icon (launcher left on), but then the host's teaser
calls below do nothing: on the web our own icon owns the teaser.
| Field | Type | Meaning |
|---|---|---|
text | string or null | The greeting line. |
asks | array of { index, label } | Suggested questions. Show label; pass index to tapAsk. |
cta | string, optional | A button label, e.g. "Build a bet". |
price | { matchOddsId, marketLabel, label, odds }, optional | One price: the market's name, the selection's name and the price as text. |
Call these on the host when the visitor acts on your teaser:
| Call | When | What the widget does |
|---|---|---|
widgetHost. | You showed the teaser. | Counts it as seen. |
widgetHost. | The visitor tapped the teaser text. | Opens the chat. |
widgetHost. | The visitor tapped a suggested question. | Opens the chat and asks it. |
widgetHost. | The visitor tapped the button. | Opens the chat on it. |
widgetHost. | The visitor tapped the price. | Checks the price again, then calls your onAddToSlip. Returns a promise of a PriceResult (below), or null when there is no price. |
widgetHost. | The visitor closed the teaser. | Clears it; onTeaser( follows. |
Unlike the slip calls, teaser calls are never kept for later: with no widget mounted they do nothing.
With our own icon on the page they also do nothing, and tapPrice() resolves null.
PriceResult is { matchOddsId, outcome, text }. text is the note to show the visitor, or
null.
outcome is added (the selection is in the slip: added, already there, or added at a new price),
gone (the price is no longer offered), cool_off (too many requests; try again shortly) or failed
(not added: your handler refused it or did not answer).
To open the chat from anywhere else (a menu item, a button on a match page), use the
PanelControl that onControl gives you: open() and close(). onControl is called with null
when the widget unmounts.
9. Events for your analytics#
Every visitor action is passed to onEvent, so you can forward it to your own analytics. Type the
handler with WidgetTrackingEvent from @sensiblestats/widget-react. An error in your handler, or a
rejected promise, never reaches the widget. Keep the handler short: it runs on the page. The widget
does not check consent; gate your own sending on it.
Every event carries name, at (epoch ms, when it happened), operatorId and widgetVersion, and
when known language, conversationId, operatorUserId, anonymousUserId and page. A ? marks
a field that can be absent.
| Event | Fields |
|---|---|
launcher_click | none |
widget_open | source? (launcher, bubble, teaser, host, popup), first? |
widget_close | method (button, escape, host for your close(), native, back), tab, answering, openMs? |
bubble_shown, bubble_click, bubble_dismiss | none |
bubble_ask_click | position |
tab_change | from, to, source? (bar, link, auto) |
question_asked | turnId, source, length, text? (only with eventText), method?, chipId?, position?, actionRef?, retryOf?, matchId? |
answer_received | turnId, conversationId, latencyMs, cardTypes, firstByteMs? |
answer_failed | turnId, code |
answer_stopped | turnId |
add_to_slip_click | matchOddsId, matchId, odds, market?, sport?, factKey?, surface?, turnId? |
add_to_slip_result | the same fields, plus outcome |
pin_click | action (add, remove), target (match, market), matchId?, market?, sport?, surface?, turnId? |
combo_add_click | surface (builder, chat), sport, legs, total, turnId? |
combo_variant_click | surface, sport, legs, total, variant |
combo_swap_click | surface, sport, legs, total |
all_markets_click | matchId, market?, surface |
dashboard_tile_click | entityType, entityId |
sport_switch | sport |
new_conversation | none |
favourite_change | kind, id, outcome, sport?, surface?, before? |
add_to_slip_result.outcome is added, duplicate, price_changed, timeout or the reason you
rejected with. timeout covers any failed add, not only a late one. odds in events is always a
decimal number.
tab, from and to are one of chat, live, matches, builder, following, trends,
games, fixtures, standings, squad, records. question_asked.source is one of typed,
starter, action, tile, preset, live_fact, bubble_ask, retry, match_sheet.
10. Colours#
Each theme has four colours. A colour you leave out keeps ours. The dark theme reads only the dark colours, never the light ones.
| Colour | Used for | Light default | Dark default |
|---|---|---|---|
accent | Your brand colour: the icon, links and highlights. | #17936a | #37c891 |
cta | Price and "Add to slip" buttons. | #f5a623 | #ffb638 |
surface | The panel's background. | #ffffff | #141b24 |
ink | Text. | #14181d | #e8edf2 |
Use hex colours (#rgb or #rrggbb). Other CSS colours are passed through, but the filled buttons
work their contrast out from accent and surface only when those are hex; otherwise they stay on
our default accent.
Set surface and ink together: the teaser, lines and faint text are then mixed from them.
colors: {
light: { accent: '#0b5fff', cta: '#ffcc00' },
dark: { accent: '#5c93ff', cta: '#ffd633', surface: '#0d1117', ink: '#f0f3f6' },
}11. When the chat cannot start#
When our server refuses the widget, it calls onUnavailable(reason) once. The widget stays on the
page, so remove it yourself: stop rendering <StatsWidget> when this is called.
reason | Cause | Fix |
|---|---|---|
widget_disabled | The widget is off for your account, or the operator id is not one we know. | Check the id. If it is right, ask your SensibleStats contact to switch the widget on. |
auth_failed | The public key is wrong or empty, or the page's origin is not an allowed domain. | Check the key; send your contact the origin. |
The widget also draws nothing, without calling onUnavailable, in two cases. If operatorId,
publicKey or baseUrl is empty, the console says [StatsWidget] failed to initialize: and names
the missing one. If the language is not English, the visitor has no stored copy of the widget's
labels in that language and we could not send them, there is no icon and no message; the widget
keeps asking, unless our server refused the request, and appears once the labels arrive.
12. Platform notes#
- Content Security Policy. The widget's code is part of your bundle, so
script-srcneeds nothing new. Allow these:connect-src:https://your-widget-host.img-src: your logo's host. Your SensibleStats contact sends you the image hosts to allow inimg-src.style-src: inline styles whileinjectStylesis on, because the widget adds its stylesheet as a<style>element.- Optional:
style-src https://fonts.googleapis.comandfont-src https://fonts.gstatic.comfor the games tab's font. Without them a fallback font is used.
- Styles. There is no shadow root: the widget renders a
<div class="ss-w-root">in your React tree. WithinjectStyleson, it adds<style id="ss-w-styles">to<head>(or to the shadow root it sits in, if you render it inside one). Its rules usess-w-class names only, so they do not change your page, but your own global CSS (forbutton,divor*) can reach the widget. Keep global selectors off it. To serve the stylesheet yourself, setinjectStyles: falseand import the file:import '@sensiblestats/widget-react/styles.css'. - Stacking. The icon and panel use
position: fixedandz-index: 2147483000. - Small screens. Below 640 px wide the panel fills the screen.
- Stored data. The widget keeps the chat thread (for one hour after its last change), followed
matches, settings and its labels in the visitor's
localStorage, under keys that start withss-w-.
13. Reference#
There is no handle to start or stop the widget: mounting <StatsWidget> starts it, unmounting it
stops it.
<StatsWidget> props
| Prop | Type | What it does |
|---|---|---|
config | StatsWidgetConfig | Every setting in section 4. Required. |
host | WidgetHost, optional | The object from createWidgetHost(). Sections 7 and 8. |
onControl | (, optional | Gives you PanelControl once mounted, null on unmount. |
PanelControl
| Method | Returns | What it does |
|---|---|---|
open(), close() | nothing | Opens or closes the chat panel. |
WidgetHost (from createWidgetHost())
| Method | Returns | What it does |
|---|---|---|
slipRemoved, betPlaced, matchOpened | nothing | Section 7. Kept (last 20) while no widget is mounted. |
teaserShown, tapTeaser, tapAsk, tapCta, dismissTeaser | nothing | Section 8. Act only with launcher: false. |
tapPrice() | promise of PriceResult or null | Section 8. |
Other exports: WIDGET_REACT_VERSION (the package version), WIDGET_CSS (the stylesheet as a
string), and the event types WidgetTrackingEvent, WidgetTrackingEventName, WidgetTrackingTab,
QuestionSource and AddToSlipOutcome.