Skip to the guide

Need help? Your SensibleStats contact can answer questions about any guide and send the three values. Write to solutions@sensiblestats.com.

Highlighted values such as YOUR_PUBLIC_KEY are placeholders. Replace them with the values we send you.

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:

  1. Get your operator id, public key and widget origin from your SensibleStats contact.
  2. Send your contact every origin you test and go live on.
  3. Install the package, render <StatsWidget> with baseUrl set, and pass the signed-in visitor's id.
  4. Set onAddToSlip, then test an add, a duplicate and a reject.
  5. 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.
  • matchOddsId is your sportsbook's own id for one selection: one outcome of one market.
  • operatorUserId is 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 usExampleWhat it is
Operator idYOUR_OPERATOR_IDYour account in our system. Part of every request.
Public keyYOUR_PUBLIC_KEYIdentifies your widget. Safe to ship in your app's bundle; it only works on your allowed domains.
Widget originhttps://your-widget-hostThe address the chat talks to. Goes in baseUrl.
To usExampleWhat it is
Allowed domainshttps://www.example.com, https://staging.example.comEvery 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#

Shell
npm install @sensiblestats/widget-react @sensiblestats/widget-sdk
# or
yarn add @sensiblestats/widget-react @sensiblestats/widget-sdk

Use @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:

TypeScript
// 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.

TSX
'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#

FieldTypeWhat it does
operatorIdstringYour operator id.
publicKeystringYour public key.
baseUrlURLThe 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#

FieldTypeDefaultWhat it does
userContext.operatorUserIdstringnoneThe signed-in visitor's id in your system. See section 5.
userContext.anonymousUserIdstringnoneYour own id for a visitor who is not signed in. See section 5.
userContext.defaultLanguagelanguage tag, e.g. en-GB, tryour account's default language (English unless you asked for another)The language of the chat and its answers.
localelanguage tagnoneThe same as userContext.defaultLanguage; when both are set, locale wins.
timeZoneIANA zone, e.g. Europe/Istanbulthe browser's zoneKick-off times and day names follow this zone. An unknown zone falls back to the browser's.
oddsFormatdecimal, american, fractionaldecimalHow 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#

FieldTypeDefaultWhat it does
greetingMessagestringnoneThe widget sends this once when it mounts, and the answer becomes the teaser. Use hello. Without it there is no greeting and no teaser.
greetingstringnoneFixed text shown in the teaser while there is no greeting answer.
pageobjectnoneThe page the visitor is on, so the greeting can lead with it. Section 6.
placeholderstringlocalizedText in the empty question box.
startersstring arraynoneSuggested questions shown in an empty chat.

Look#

FieldTypeDefaultWhat it does
themelight, dark, autoautoauto follows the visitor's system setting. A visitor who picks a theme in the chat keeps their choice.
colors{ light?, dark? }see section 10Your colours per theme.
logoUrlURLour markYour logo, shown on the icon and in the panel header.
headerTitlestringSensibleStatsThe panel's title.
positionleft, rightrightWhich 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.
radiusnumber, px16Corner radius of the panel.
launcherbooleantruefalse hides our icon and teaser so you draw your own (section 8).
launcherLabelstring"Chat with SensibleStats", localizedThe icon's label for screen readers.
pinIconpin, star, bookmarkpinThe icon visitors tap to follow a match or price.
injectStylesbooleantruefalse stops the widget adding its stylesheet, so you load it yourself (section 12).

Slip, callbacks and events#

FieldTypeWhat it does
onAddToSlip(selection) => resultAdds a price to your bet slip. Without it prices show with no button. Section 7.
slipSportsarray of basketball, americanfootball, tennisThe sports your onAddToSlip accepts besides football. Section 7.
onTeaser(teaser or null) => voidGives you the teaser to draw yourself. Section 8.
onUnavailable(reason) => voidTells you the chat cannot start. Section 11.
onEvent(event) => voidEvery widget event, for your own analytics. Section 9.
eventTextboolean, default falseAdds 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.
onOpenMatchfunctionDeprecated 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.

FieldTypeMeaning
sportfootball, basketball, americanfootball, tennisRequired when page is set.
kindsection, competition, matchA sport's front page, a competition page, or a match page. Absent reads as section.
matchIdnumber or stringYour sportsbook's id for the match on a match page.
competitionIdnumber or stringYour 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:

  1. The visitor taps "Add to slip" under a price.
  2. The widget calls onAddToSlip(selection). selection.matchOddsId is your sportsbook's own id for that selection, so you can look it up directly.
  3. Your code adds that selection to your slip and returns what happened, or a promise of it.
  4. 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

FieldTypeMeaning
matchOddsIdnumberYour sportsbook's id for the selection. Look it up in your slip.
matchIdnumberYour sportsbook's id for the match.
oddsDecimalnumberThe price the visitor saw, as a decimal. Always set.
odds{ format, text }, optionalThe 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.
quotedAtUtcISO time, optionalWhen that price was last confirmed.
sportbasketball, americanfootball, tennis, optionalAbsent for football.
tourstring, optionalTennis only: the tour the match id belongs to.
conversationId, insightIdstring, optionalWhich chat and which card the tap came from.
displayobject, optionalThe 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

ReturnWhenThe visitor sees (English)
{ status: 'added' } or nothingThe 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
reasonMeaningThe visitor sees (English)
login_requiredThe visitor must sign in first.Sign in to add to your slip
suspendedThe market is suspended.Market suspended
closedThe market or match is closed, e.g. it has started.Your message, else "This selection can't be added."
not_found, limit, unsupportedYou 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.

CallWhen
widgetHost.slipRemoved({ matchOddsId, sport? })The visitor removed a selection from your slip, "clear all" included. Clears its "In slip" mark.
widgetHost.betPlaced({ selections: [{ matchOddsId, sport? }], stake?, currency?, betId?, betType?, totalOdds? })The visitor placed a bet. Pass every leg; the widget reports only the ones it added, at most 25.
widgetHost.matchOpened({ matchId })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:

TSX
'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.

FieldTypeMeaning
textstring or nullThe greeting line.
asksarray of { index, label }Suggested questions. Show label; pass index to tapAsk.
ctastring, optionalA button label, e.g. "Build a bet".
price{ matchOddsId, marketLabel, label, odds }, optionalOne 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:

CallWhenWhat the widget does
widgetHost.teaserShown()You showed the teaser.Counts it as seen.
widgetHost.tapTeaser()The visitor tapped the teaser text.Opens the chat.
widgetHost.tapAsk(index)The visitor tapped a suggested question.Opens the chat and asks it.
widgetHost.tapCta()The visitor tapped the button.Opens the chat on it.
widgetHost.tapPrice()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.dismissTeaser()The visitor closed the teaser.Clears it; onTeaser(null) 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.

EventFields
launcher_clicknone
widget_opensource? (launcher, bubble, teaser, host, popup), first?
widget_closemethod (button, escape, host for your close(), native, back), tab, answering, openMs?
bubble_shown, bubble_click, bubble_dismissnone
bubble_ask_clickposition
tab_changefrom, to, source? (bar, link, auto)
question_askedturnId, source, length, text? (only with eventText), method?, chipId?, position?, actionRef?, retryOf?, matchId?
answer_receivedturnId, conversationId, latencyMs, cardTypes, firstByteMs?
answer_failedturnId, code
answer_stoppedturnId
add_to_slip_clickmatchOddsId, matchId, odds, market?, sport?, factKey?, surface?, turnId?
add_to_slip_resultthe same fields, plus outcome
pin_clickaction (add, remove), target (match, market), matchId?, market?, sport?, surface?, turnId?
combo_add_clicksurface (builder, chat), sport, legs, total, turnId?
combo_variant_clicksurface, sport, legs, total, variant
combo_swap_clicksurface, sport, legs, total
all_markets_clickmatchId, market?, surface
dashboard_tile_clickentityType, entityId
sport_switchsport
new_conversationnone
favourite_changekind, 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.

ColourUsed forLight defaultDark default
accentYour brand colour: the icon, links and highlights.#17936a#37c891
ctaPrice and "Add to slip" buttons.#f5a623#ffb638
surfaceThe panel's background.#ffffff#141b24
inkText.#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.

TSX
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.

reasonCauseFix
widget_disabledThe 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_failedThe 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-src needs 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 in img-src.
    • style-src: inline styles while injectStyles is on, because the widget adds its stylesheet as a <style> element.
    • Optional: style-src https://fonts.googleapis.com and font-src https://fonts.gstatic.com for 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. With injectStyles on, 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 use ss-w- class names only, so they do not change your page, but your own global CSS (for button, div or *) can reach the widget. Keep global selectors off it. To serve the stylesheet yourself, set injectStyles: false and import the file: import '@sensiblestats/widget-react/styles.css'.
  • Stacking. The icon and panel use position: fixed and z-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 with ss-w-.

13. Reference#

There is no handle to start or stop the widget: mounting <StatsWidget> starts it, unmounting it stops it.

<StatsWidget> props

PropTypeWhat it does
configStatsWidgetConfigEvery setting in section 4. Required.
hostWidgetHost, optionalThe object from createWidgetHost(). Sections 7 and 8.
onControl(control: PanelControl or null) => void, optionalGives you PanelControl once mounted, null on unmount.

PanelControl

MethodReturnsWhat it does
open(), close()nothingOpens or closes the chat panel.

WidgetHost (from createWidgetHost())

MethodReturnsWhat it does
slipRemoved, betPlaced, matchOpenednothingSection 7. Kept (last 20) while no widget is mounted.
teaserShown, tapTeaser, tapAsk, tapCta, dismissTeasernothingSection 8. Act only with launcher: false.
tapPrice()promise of PriceResult or nullSection 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.