Sideband React SDK
Sideband adds in-app Pulse prompts and event tracking to React apps.
Requirements
- React 18.3 or React 19, with React DOM of the same version
- A Sideband API key
- Your application's version
For a site without React, or to start the SDK outside the React tree, use
@sidebandai/sideband-web,
which has no framework dependency. Its README has a server-rendered React 18
example that starts the SDK once per page load under StrictMode.
Install
npm install @sidebandai/sideband-react
Configure
Import the stylesheet once and render SidebandProvider once, near the root of
your app. Pass your API key and application version through its config prop:
import { SidebandProvider } from '@sidebandai/sideband-react'
import '@sidebandai/sideband-react/style.css'
function App() {
return (
<SidebandProvider config={{ apiKey: 'YOUR_API_KEY', appVersion: '1.0.0' }}>
<AppContent />
</SidebandProvider>
)
}
AppContent represents your existing application content. Replace 1.0.0 with
your application's version, not the SDK version. appVersion must be a
non-empty string of at most 64 characters.
The provider presents available Pulses automatically. It renders them in a
portal on document.body, not inside its children, so it can wrap your app as
above or sit beside it with no children:
function App() {
return (
<>
<SidebandProvider config={{ apiKey: 'YOUR_API_KEY', appVersion: '1.0.0' }} />
<AppContent />
</>
)
}
Components that call useSideband() must be inside the provider. When the
provider sits beside your app, connect your app to it as shown in
Calls from outside the provider.
The provider reads config once, when it mounts, and keeps it until it
unmounts. A later change to the config prop, such as a new API key or
context.language, does not reach the SDK. Some callbacks are exceptions:
shouldPresentPulse and onRateApp: the provider calls the latest ones.
onError is split. Errors from showing a pulse go to the latest onError:
for example a pulse that is not valid, or a shouldPresentPulse or
onRateApp that throws. Errors from sending and from the SDK's own checks go
to the onError the provider mounted with: for example a failed or rejected
send, an answer that cannot be stored, or a tagUser ID that is too long.
To send every error to one handler, pass an onError that does not change
during the provider's life, or one that calls your current handler through a
ref. To apply a new config, remount the provider, for example with a React
key:
<SidebandProvider key={language} config={{ apiKey: 'YOUR_API_KEY', appVersion: '1.0.0', context: { language } }} />
A remount stops the SDK, discards events not yet sent, and starts it again,
which sends a new system_app_launch. If the provider wraps your app, a new
key also remounts your app; render the provider beside your app to avoid that.
The API key goes to the browser, so anyone can read it in your page or its
network requests, as with a key in a mobile app. That is expected: the key can
only send events and pulse answers for its channel and receive that channel's
pulses.
Server rendering
SidebandProvider can render on the server. It starts the SDK in an effect, so
the server render creates no SDK, sends nothing, and renders no pulse. In the
browser, the SDK starts after hydration.
- In frameworks with React Server Components, such as the Next.js App Router,
render the provider from a Client Component (a file that starts with
'use client'). The package does not mark its modules as client code.
- In other server-rendering frameworks, such as React Router or Remix, render it
like any other component.
Content Security Policy
If your site sends a Content Security Policy, allow the Sideband API origin in
connect-src. Without it, the browser blocks every send: no events arrive and
no pulses show.
| Channel |
connect-src |
img-src (pulse images) |
| Development or Production |
https://api.sideband.ai |
https://images.sideband.ai |
If your policy restricts images, img-src must allow data: (the close
button's icon is a data: image in the stylesheet) and the image host above.
The React package does not inject a <style> element. When your bundler
extracts style.css into a stylesheet file, it does not need 'unsafe-inline'
in style-src; your policy must allow that file (usually 'self'). A bundler
that injects CSS as a <style> element, as some do in development, changes
this: that element then needs whatever your policy requires for inline styles.
A blocked send appears in the browser console as a Content Security Policy
error, and onError receives a network error.
What was checked with the React package, in a production build of a
server-rendered React 18.3 app: its policy had a nonce in script-src,
style-src 'self' 'unsafe-inline', and img-src with data: and https:.
Adding the API origin to connect-src was the only change it needed, and the
browser reported no policy violation. The bundler extracted style.css into a
stylesheet file, which the app loaded like its other stylesheets, with the
page's nonce. A style-src without 'unsafe-inline' has not been checked with
the React package.
Consent
Your app decides when Sideband runs. If Sideband needs consent on your site,
render SidebandProvider only after the user gives it, and remove it when the
user withdraws it. Mounting the provider starts the SDK; unmounting it stops the
SDK and discards events not yet sent. The SDK has no consent setting of its own,
and there is no config setting that pauses it. Which consent category applies
is your decision; this README does not give legal advice.
Gate the provider, not your app. If the provider wraps your app, adding or
removing it remounts your whole app, which loses its state. Render it beside
your app instead:
function SidebandWhenAllowed({ allowed }: { allowed: boolean }) {
if (!allowed) return null
return (
<SidebandProvider config={{ apiKey: 'YOUR_API_KEY', appVersion: '1.0.0' }}>
<SidebandBridge />
</SidebandProvider>
)
}
function App() {
const allowed = useAnalyticsConsent() // your app's consent state
return (
<>
<SidebandWhenAllowed allowed={allowed} />
<AppContent />
</>
)
}
SidebandBridge connects your app's code to the provider; see the next section.
A user who declines sends no events and sees no pulses.
Calls from outside the provider
useSideband() works only inside SidebandProvider; outside it, it throws. If
your app tracks events through its own analytics module, or from code that is
not a React component, give that module the SDK functions from a small
component inside the provider:
// analytics.ts: your app's analytics module
type SidebandApi = {
track: (name: string, metadata?: Record<string, string>) => void
tagUser: (userId: string) => void
untagUser: () => void
}
let sideband: SidebandApi | null = null
let user: { id: string | null } | null = null // null until your app calls identify
export function attachSideband(api: SidebandApi | null) {
sideband = api
// Apply the current user when Sideband starts, for example after consent.
if (api && user) {
if (user.id !== null) api.tagUser(user.id)
else api.untagUser()
}
}
export function track(name: string, metadata?: Record<string, string>) {
sideband?.track(name, metadata) // dropped while Sideband is not running
}
export function identify(id: string | null) {
user = { id }
if (id !== null) sideband?.tagUser(id)
else sideband?.untagUser()
}
// SidebandBridge.tsx
import { useEffect } from 'react'
import { useSideband } from '@sidebandai/sideband-react'
import { attachSideband } from './analytics'
export function SidebandBridge() {
const { track, tagUser, untagUser } = useSideband()
useEffect(() => {
attachSideband({ track, tagUser, untagUser })
return () => attachSideband(null)
}, [track, tagUser, untagUser])
return null
}
Render <SidebandBridge /> inside the provider, as in the consent example.
The SDK does not queue calls made outside the provider. Calls that your module
makes while the bridge is not attached are dropped: before consent, before the
bridge's effect runs after hydration, and after the provider unmounts. The
module above keeps the user, so a user who signed in before Sideband started is
tagged when it starts. If you need events from before Sideband starts, hold a
short, capped list in your module after your app decides to start Sideband (not
before consent), and send it when the bridge attaches. The
@sidebandai/sideband-web README shows this pattern under "Events before
Sideband starts". Inside the provider, calls made before the SDK has finished
starting are queued and sent once it starts.
Metadata values must be strings: convert numbers and booleans in your module
(for example with String(value)).
Language
The SDK reports the browser's language (for example de from de-AT). The
server shows a pulse only when that language matches the pulse's base language
or one of its published translations. If nothing matches, the pulse is not
shown, even without a language rule in its targeting. There is no fallback
language today.
If your site has one UI language, you can report that language instead, so
pulses match the page rather than the browser:
<SidebandProvider config={{ apiKey: 'YOUR_API_KEY', appVersion: '1.0.0', context: { language: 'en' } }}>
If your site is translated, pass the page's current language the same way. Test
with a browser set to a language that differs from your site's language.
Identify users
Tag the signed-in user wherever your app knows who they are: after sign-up and
sign-in, and when your app restores a signed-in session. Clear the identity at
sign-out.
import { useSideband } from '@sidebandai/sideband-react'
const { tagUser, untagUser } = useSideband()
tagUser(user.id) // after sign-up, sign-in, or restoring a signed-in session
untagUser() // at sign-out
Pass your own stable user ID, not an email address or name. A user ID can have at most 256 characters (Unicode code points). A longer ID is
rejected without changing the current identity, and onError receives the reason. The SDK
keeps the ID in the browser's localStorage and restores it on the next page
load. Call useSideband() in components inside SidebandProvider.
Track events
useSideband() returns track. Call it once per user action, after the action
succeeds:
function SendInvoiceButton({ invoice }: { invoice: { id: string } }) {
const { track } = useSideband()
const send = async () => {
await sendInvoice(invoice.id)
track('invoice_sent', { source: 'invoice_detail', item_type: 'invoice', invoice_id: invoice.id })
}
return <button onClick={send}>Send</button>
}
Pass metadata as string key-value pairs. Use metadata to describe an event
without creating a separate event name for each source, item type, or mode.
Only these six keys support Pulse trigger filters and event-history conditions:
| Key |
Value format |
Example |
source |
String |
'home' |
item_type |
String |
'article' |
mode |
String |
'manual' |
variant |
String |
'control' |
count |
Integer sent as a string |
'3' |
duration |
Seconds sent as a string; fractions allowed |
'12.5' |
Use the exact lowercase key names. The server trims and lowercases values for
source, item_type, mode, and variant, and compares them with equals and
not-equals. It compares count and duration numerically. Send duration in
seconds, not milliseconds. count: '3.5' and count: '3.0' are invalid; use
count: '3'.
Custom keys such as content_id, screen, or plan are stored unchanged, but
cannot be used in Pulse targeting. A missing key does not match any filter,
including not-equals. The server stores at most 20 metadata properties per
event: valid targeting keys first, then custom keys in sorted key order. It
drops empty keys and invalid targeting values without rejecting the event.
When the page is hidden or unloads, the SDK tries to send queued events with
keepalive. This is best effort: a send already in progress can delay it. For an
event tracked just before your code navigates away, await flush() from useSideband() first.
A pulse answer is sent when the user presses the final button (for example
Done), or closes the pulse, which sends the answers given so far. As in the iOS
and Android SDKs, nothing is sent while the thank-you screen is showing, so
answers are kept across a page load only after Done or a close; leaving the page
on the thank-you screen loses them. If the user leaves the page before the
server accepts the answer, the SDK tries again after the next page load in the
same tab. This is best effort.
The SDK keeps pending answers in the tab's sessionStorage, separately for each
API key and endpoint, and sends each answer only while the same user is tagged
(or the same context.user_id is configured). An answer is still lost when:
- storage is unavailable or full (
onError receives a
PendingInteractionStorageError with reason storage_unavailable or
storage_write_failed);
- more than 10 answers are pending: the oldest are not kept (
reason
queue_full);
- it is still unsent 24 hours after it was given;
- the server rejects it permanently, with a 4xx response other than 408, 425 or
429 (
onError receives the error);
- the user closes the tab, or does not return to that tab with the same user
and configuration.
Events the SDK sends itself
Do not track these yourself:
| Event |
When |
system_app_launch |
The SDK starts when SidebandProvider mounts, usually once per page load. |
system_app_background |
The page is hidden or unloaded: another tab, a minimized window, navigation away. |
system_app_foreground |
The page is visible again after system_app_background. |
system_login |
tagUser sets a new user ID. metadata.user_id is the new ID. |
system_logout |
untagUser clears the user ID, or tagUser replaces it. metadata.user_id is the previous ID. |
system_did_present_pulse |
A Pulse is shown to the user. |
A snackbar or bar counts as shown only when a person can see it: the tab is
visible, the entry is rendered (not display: none or visibility: hidden) and
inside the viewport, and it is not clipped away by a scrolling container. Until
then the SDK checks again about every 200 ms. The browser's
IntersectionObserver decides the viewport and clipping part; in a browser
without it, the SDK uses its own approximate geometry check. A close, Escape or answer by the
person also counts. If the SDK runs in an iframe, the SDK also checks the
<iframe> element in the parent page, but only when the parent is on the same
origin. A cross-origin parent cannot be read, so a cross-origin <iframe> that
the parent hides with CSS (for example visibility: hidden) can still be counted
as shown.
Switching from user A to user B sends system_logout for A, then system_login
for B, with the same timestamp. Repeating the same ID, clearing an ID that is
not set, and restoring the stored ID on a page load send nothing.