npm install @togohq/sdk-browser
Browser only, zero runtime dependencies, at most 23 KB minified. On a server init() returns a
client that does nothing and logs one warning; send server events with
@togohq/sdk-node.
Nothing on the client throws — not a bad key, not an oversized property, not a reserved name.
Each is a console.error prefixed [togo] that says what is wrong, and the call returns
normally, so analytics can never break the handler it sits in. To see these errors from your
visitors’ browsers too, pass onError.
init(options)
import { init } from '@togohq/sdk-browser';
const analytics = init({ writeKey: 'togo_pkt_…' });
Returns a client at once and never blocks; call it as early as you can. It checks the write key in the background. A rejected key logs one error, and the client stops sending while every call keeps returning normally; events already queued stay on the device and are retried on the next page load.
Options
| Option | Default | What it does |
|---|---|---|
writeKey |
— | Required. togo_pkt_… (test) or togo_pkl_… (live) |
endpoint |
https://in.togohq.ai |
Where events are sent: a proxy, or another ingress |
defaultProperties |
— | Properties added to every track() event, fixed for the client’s life |
appVersion |
— | Your app’s version, such as '2.4.0'. Read as $app_version, so a chart splits by release |
appBuild |
— | Your app’s build number, such as '412'. Read as $app_build |
pageContext |
true |
false sends no URL, path, referrer or campaign; the time zone is still sent |
sessionTimeoutSeconds |
1800 (30 min) |
The idle window that ends a session, in seconds. <= 0 turns sessions off |
sessionTimeoutMs |
— | Deprecated: the same window in milliseconds. Still honoured; sessionTimeoutSeconds wins |
consent |
'not_required' |
'not_required', 'pending', 'granted' or 'denied' |
consentBufferMaxEvents |
100 |
Events held in memory while consent is pending; the oldest are dropped |
onDenied |
'drop' |
What happens to an event under denied. 'drop' is the only value |
deviceId |
— | Your own device id, for a host that owns identity |
cookieDomain |
probed | The cookie’s domain. By default the widest one the browser accepts |
cookieSameSite |
'Lax' |
The cookie’s SameSite attribute |
onError |
— | Called for every event, or part of one, that will not be recorded. See onError |
experiments |
— | Experiment names to fetch at init(), so the first getExperiment() does not wait |
assignEndpoint |
https://assign.togohq.ai |
Where experiment assignments come from |
autocapture |
true |
false sends no page views. { pageViewed, pageLeft, scrollRoot } turns each event off, or names the element that scrolls. See Page views |
appVersion and appBuild are each 1–64 characters; a value that is not is left out, and the SDK
logs one error saying which. Neither is sent unless you set it.
On defaultProperties: an event’s own value for the same key wins, and the SDK logs one error for
the collision. They are kept through reset() and never added to identify() or
setPersonProperties().
Page views
The SDK sends two events for every page view, with no code from you. Each counts as an event.
$page_viewedwhen a page is shown: on load, on a single-page app’s change of path, and when the browser restores the page from its back/forward cache. A change of only the query string or the#fragmentis the same page.$page_leftwhen the view ends — the page is hidden for good, or the app changes path. It carries the page and session of the view it measures:visible_duration_ms: the time the page was visible, never time in a background tab. At most 24 hours.max_scroll_page_percent: how far down the visitor saw, as a percent of the page’s height,0.0–100.0. A page that fits the screen reads100.0.viewport_page_percent: what percent of the page one screen showed, measured at the same moment. A visitor who never scrolled reads this as their depth.
Compare scroll depth within one kind of device, never as one number across phones and desktops: a phone shows the same page as a much taller one.
init({ writeKey: 'togo_pkl_…', autocapture: false }); // no page views
init({ writeKey: 'togo_pkl_…', autocapture: { pageLeft: false } }); // $page_viewed only
init({ writeKey: 'togo_pkl_…', autocapture: { scrollRoot: '#main' } }); // the app scrolls #main
If your app scrolls an element instead of the page, pass that element’s selector as scrollRoot.
Without it, both scroll numbers are left out rather than reading 100.0 on every view.
Reserved names
Togo keeps every event and property name exactly as your code sends it. Two kinds of property name are refused:
- A name starting with
$, which is reserved for Togo. The OS, the page, the campaign and the rest of what the SDK records on its own are sent outside your properties and read as$os,$path,$utm_sourceand so on (Reserved properties). - A name Togo cannot use: longer than 255 characters, or holding a control character or an email address. Its value would be stored and could never be queried.
The SDK reports either one through onError and logs one [togo] error naming it, with
any email address in the name replaced by <email>. With a live key it drops the property from a
track() call, from defaultProperties and from setPersonProperties(), and sends the rest of the
call. With a test key it sends the property as well, so verify_tracking reports it
with its fix:
property_reserved or
property_name_invalid, and
person_property_reserved or
person_property_name_invalid on
a profile.
track(eventName, properties?)
analytics.track('checkout_started', { plan: 'pro', seats: 5 });
Queues one event. The name is any string that does not start with $; property values are
strings, numbers, booleans or null. Every event also carries the page’s URL and path (read at
each call), the referrer and the utm_* campaign values (read once, at init()), and the
visitor’s time zone. The query string and #fragment are never sent, and an email address in a
path, referrer or campaign value is replaced with REDACTED_EMAIL.
Returns the event’s eventId, or undefined when nothing will be sent — a refused name, consent
denied, or a client that does nothing (a malformed write key, a key already rejected, or on a
server). The key is checked in the background, so a call made before a rejection comes back still
returns an id. Under pending consent the event is held with that id and sent under it once
consent is granted, or discarded if it is denied. An id means the event was queued, not that it
arrived; the edge can still reject it. Your agent passes
these ids to verify_tracking_by_event_ids
to check exactly what a test run sent (Check that events arrive).
The SDK also sends one $session_started of its own when it creates a session, immediately before
the event that caused it, with that event’s time and page (Sessions). A
track() naming it is dropped.
identify(userId)
Links this browser to your user id. Call it after sign-in; repeating the same id does nothing, and
a different id resets first. Returns the eventId of the identify call it sent, or undefined when
it sends nothing — the same id again, consent denied, or a client that does nothing.
Identify people when they sign in.
setPersonProperties(ops)
analytics.setPersonProperties({
email: user.email,
name: user.displayName,
set: { plan: 'pro' },
setOnce: { first_plan: 'free' },
unset: ['trial'],
});
Updates the person’s profile. email and name set the reserved person properties $email and
$name (null removes one); in set, setOnce and unset only defined keys are kept, and an
email or name key there does not compile. Works before and after identify(). Returns the profile write’s eventId, or undefined when it sends
nothing — an empty call, consent denied, or a client that does nothing.
Set person properties.
reset()
Call on sign-out. Rotates the anonymous id and the session and keeps the device id, so the next person on this browser is not credited to the last.
flush()
await analytics.flush() sends everything queued now. Events otherwise go in batches — at 50
queued, or 5 seconds after the first, or as the visitor leaves the page (pagehide) — and the
batching is not configurable. Call flush() after an event that must leave before the page does,
such as a click that navigates to another site:
analytics.track('app_store_clicked', { store: 'ios' });
await analytics.flush();
window.location.href = appStoreUrl;
Never call flush() after every track(): each event then goes as its own request, from every
visitor’s browser. If events before a navigation go missing only in a browser test, the test is
holding the request — see
Events are missing after a click in a browser test.
getAnonymousId(), getDeviceId(), getSessionId()
Read the current ids, for example to forward them to your server.
Each returns undefined until the first event the visitor’s consent allows, and never creates an
id as a side effect. The person behind those ids is worked out by Togo once the events
arrive, so your code works with userId and these ids (People and identity).
setConsent(state) and getConsent()
Change or read the consent state. 'denied' deletes every key the SDK stored on the device.
Connect a consent banner.
getExperiment(name)
const result = await analytics.getExperiment('checkout_cta');
if (result.variant === 'one_click') renderOneClickCheckout();
else renderCurrentCheckout();
Which variant of an experiment this browser gets. Call it where the code branches, and always keep a default path. It returns a Promise that resolves within 800 ms and never rejects:
interface ExperimentResult {
experiment: string;
status: 'draft' | 'active' | 'finished' | 'not_found' | 'unavailable';
variant: string | null; // null: run what you would run without Togo
participating: boolean; // true only when this call counts the visitor as entered
}
status |
variant |
When |
|---|---|---|
active |
The assigned variant, or the baseline | Running. The baseline, with participating: false, for a visitor outside the participation rate or a call missing the experiment’s unit, such as a user_id experiment before identify() |
draft |
The assigned variant | Not started yet. Only a test key sees a draft |
finished |
The winner | Finished. Everyone gets the winner |
not_found |
null |
No experiment by this name, or a draft asked for with a live key |
unavailable |
null |
No answer: the network failed or timed out, or consent is pending or denied |
The answer is cached on the device for the session, so a visitor’s variant does not change
mid-visit; identify() and reset() ask again. Calls made together go out as one request, and
names listed in the experiments option are fetched at init() without counting
anyone as entered.
A participant’s first call sends $experiment_entered, once per experiment, and every later
track() event from this browser carries the variant until the experiment finishes, so a chart can
split by it. A track() naming $experiment_entered is dropped. With a test key every call asks
again and an entry is sent once per variant per page load, so a forced variant shows at once.
Run an A/B test.
onError
const analytics = init({
writeKey: 'togo_pkl_…',
onError: (error) => Sentry.captureMessage(error.message, { extra: error }),
});
Pass it to the error tracker your app already uses. It is called once for every event that will not be recorded, or value dropped or cut from one, and once when the client stops sending — in production as well as in development. With a test key it is also called for a property name production would drop (Reserved names). The console still shows every one.
interface TogoError {
code: TogoErrorCode; // what went wrong; permanent, never renamed
message: string; // what the console shows, without "[togo] "
eventIds: readonly string[]; // the events it is about, by the id track() returned
eventName?: string; // the event's name, when it concerns one event
property?: string; // the property's name, when it concerns one property — never its value
}
It runs after the call that caused it has returned, never inside it, and whatever it throws is
logged. It is not called for consent denied, for a no-op such as identify() with the same user,
or while an offline batch waits to be retried.
code |
What was lost |
|---|---|
event_name_empty, event_name_too_long |
The event: its name must be 1 to 255 characters |
event_name_reserved |
The event: $ names are Togo’s. Dropped with a live key; a test key sends it and Togo refuses it |
property_reserved, person_property_reserved |
A $ property name on an event or a profile write. Dropped with a live key, sent with a test key; the rest is sent. Once per name |
property_name_invalid, person_property_name_invalid |
A property name over 255 characters, or with a control character or an email address. Dropped with a live key, sent with a test key; the rest is sent. Once per name |
envelope_property_value_too_long |
The end of a string value over 1,024 characters: it is cut to its first 1,024 and the event is kept. eventIds is the kept event. Once per event and property |
envelope_properties_too_many |
The properties past 256 on an event, or on one map of a profile write: the first 256 by name are kept and the event is kept. eventIds is the kept event, and the message names the first ten dropped. Once per event |
queue_full |
Events evicted from the queue on this device, or from the buffer while consent is pending |
timestamp_too_old |
Queued events older than 7 days, which Togo would refuse |
write_key_invalid |
Everything: the key is not a write key, so the client sends nothing |
write_key_rejected |
Everything from this page: Togo refused the key. Queued events stay and are retried on the next load |
batch_too_large |
A batch Togo refused as too large — usually one very large property value |
batch_rejected |
A batch Togo could not read: a bug in the SDK |
A rejection code such as timestamp_too_far_future |
One event Togo refused when it arrived. The message links its fix |
Delivery and retries
A network error or a 5xx re-queues the batch, and each event keeps the same event id across
attempts, so a retry is recognised as the same event. A 4xx is not retried. Events queued while
offline are sent later and keep the time they happened.
Limits
| What | Limit |
|---|---|
| Property value length | 1,024 characters |
| Properties per event | 256 |
| A batch | 50 events, about 1 MiB, or 5 seconds after the first; as the page closes, at most 60,000 bytes |
| Events waiting on the device | 1,000 events or 1 MiB; past either, the oldest are dropped and reported as queue_full |
A string value over 1,024 characters is cut to its first 1,024 and the event is kept — usually a
long URL with a tracking query string. The SDK reports it to onError as
envelope_property_value_too_long, once per event and property. With a live key the SDK cuts the
value before sending it; with a test key it sends the value whole, so verify_tracking and Live
View show the cut.
An event with more than 256 properties — usually a whole object passed as its properties — keeps
the first 256 in sort order by name, and the event is kept. Sorting is by character code, so
upper-case names come before lower-case ones and item_10 before item_9. The email and
name you pass to setPersonProperties() are always kept. The SDK reports it to
onError as envelope_properties_too_many, once per event, naming the first ten properties it
dropped. With a live key the SDK drops them before sending; with a test key it sends them all, so
verify_tracking and Live View show which were dropped. See
Event diagnostics.