Web and React Native SDK
Last updated
Use this SDK to add Metrickle to a website, a single-page app or a React Native app. On the web it records pageviews, friction and accessibility settings on its own, so most sites only add a few track() calls for the moments that matter. If you just want the snippet, see Install Metrickle. For what each event means and how to name your own, see Events, people and properties.
Accessibility-first product analytics and UX research for web and React Native.
On web, the SDK captures pageviews, sessions, sources, web vitals, outbound links, rage clicks, errors and friction (dead clicks, slow controls, u-turns, up-and-down scrolling, form abandons) automatically. It also records accessibility context such as reduced motion, contrast, text size and keyboard navigation, so you can segment every journey by assistive tech. Surveys, the feedback widget, heatmaps, session replay and accessibility scans in visitors' browsers are configured in the Metrickle dashboard. Their UI, recorder and checker (axe-core) load only when you turn them on.
Install
npm install @metrickle/sdk
Web
import { init } from "@metrickle/sdk";
const metrickle = init({
writeKey: "mk_pub_YOUR_WRITE_KEY", // from your app's Settings page
// cookieless: true, // no localStorage; no consent banner needed
});
metrickle.track("signup", { plan: "pro" });
metrickle.identify(user.id, { plan: user.plan }); // after login
metrickle.reset(); // on logout
// Research features (enable under Settings → Research)
metrickle.consent({ replay: true }); // from your consent banner
The SDK tracks SPA navigations through the History API by default. It honors Do Not Track and Global Privacy Control by default (respectDnt). That opt-out is not stored: it is checked on every page load, so a visitor who turns the signal off is tracked again, as the same visitor.
Options
| Option | Default | |
|---|---|---|
writeKey | required | Public write key. It can only send events. |
host | https://in.metrickle.com | Ingest endpoint |
cookieless | false | Use a daily-rotating server-side visitor hash instead of storage |
autoPageviews | true | Track SPA navigations |
outboundLinks, webVitals, rageClicks, errors | true | Automatic capture |
friction | true | Dead clicks, slow controls, error clicks, u-turns (across full page loads too, except in cookieless mode), up-and-down scrolling, form errors, form abandons and long pauses before a form is sent or a data-mk-primary control is pressed |
a11y | true | Accessibility settings as event context |
research | true | Surveys, feedback, heatmaps, replay and accessibility scans as configured in the dashboard |
respectDnt | true | Honor doNotTrack / globalPrivacyControl |
linkDomains | Your other domains (subdomains included): one visitor and session across them. See below | |
beforeSend | (event) => event | null, called before each event is queued. Return null to drop it, or a copy without fields you don’t want sent (e.g. PII scrubbing) | |
sessionTimeoutMs | 1800000 (30 min) | Inactivity that ends a session |
flushIntervalMs | 5000 | How often queued events are sent |
appVersion | Your app’s version, such as "4.12". Each new version becomes a release that protected tasks are judged against, and lets two versions be compared side by side | |
debug | false | Log what the SDK does to the console |
Script tag
If you don’t use a bundler, paste this before </head>:
<script defer src="https://app.metrickle.com/m.js" data-key="mk_pub_YOUR_WRITE_KEY"></script>
This exposes window.metrickle. The script tag reads these attributes:
| Attribute | Option | |
|---|---|---|
data-key | writeKey | Required |
data-cookieless | cookieless | On when present, unless set to "false" |
data-link-domains | linkDomains | Space- or comma-separated, such as "example.com shop.example.net" |
data-host | host | Defaults to the script’s own origin with app. replaced by in. |
data-debug | debug | On when present, unless set to "false" |
Every other option keeps its default. In particular the script tag can’t set appVersion, so a site that loads it gets releases from the deploy hook instead. Use the npm package if you want versions on your events.
Signed-in users and devices
Call identify(user.id) after sign-in and reset() on sign-out. Metrickle then counts one person as one visitor: what they did before signing in, after it, and on every other device they sign in on. Send an opaque id, not an email. A refund or cancel you send from your server with only the user id lands on the same person, so it takes back the right completion.
There is no alias(): identify() is enough, and the server joins the anonymous visitor to the user. reset() forgets the user, the session and every property set with register(), and starts a new anonymous visitor, so the next person on a shared device doesn’t inherit any of it.
Opting out
metrickle.optOut(); // stops tracking and remembers it
metrickle.optOut({ persist: false }); // for this page load or app session only
metrickle.optIn(); // tracking resumes
optOut() drops anything not yet sent and removes the anonymous id and session from the device. An opted-out visitor keeps no anonymous id: none is created on later visits or by reset(), and surveys don’t show. The user id you passed to identify() and consent choices are kept. optIn() creates a new anonymous id (on React Native it also fetches survey and feedback settings again). optOut({ persist: false }) stops tracking without storing anything or removing stored ids; Do Not Track and Global Privacy Control use it, so switching them off carries on as the same visitor.
Feedback from your own UI
if (metrickle.feedback.isEnabled) showFeedbackButton();
metrickle.feedback.open(); // opens the feedback dialog, even when the floating button is hidden
await metrickle.feedback.submit({ category: "bug", message: "Pay button does nothing" });
Feedback can be switched off per platform under Settings → Research in the dashboard. While it’s off for web, isEnabled is false and open() and submit() do nothing.
More than one domain
If people move between your own domains (a marketing site and the app, a store and its checkout), list them:
init({ writeKey: "mk_pub_YOUR_WRITE_KEY", linkDomains: ["example.com", "checkout.example.net"] });
Install the SDK with the same write key on each domain, and add every domain to the app’s allowed origins. Links and forms between them carry a short-lived _mk parameter with the anonymous and session ids. The page it lands on removes it from the address bar straight away. It only counts within two minutes and from a listed domain, so a copied URL can’t merge two people. It never carries the user id. Without it, a funnel that crosses domains shows everyone leaving at the hand-off.
Cart value
Put a numeric value on the events that change what someone is about to buy:
metrickle.track("cart_updated", { value: 89.5, currency: "EUR", items: 3 });
When a task attempt is abandoned, the last such value inside it is what was lost, and cases count it in the money Lost so far. Attempts without one count at the average value of a success. Only revenue is added to revenue on Overview, pages, sources and goals, so cart values never inflate them.
Money on tasks, cases and releases reads each event in one order: revenue first, then value, then nothing (that event adds no money). A completed attempt is worth the revenue on the event that completed it, or its value when it has no revenue, and a task’s Revenue kept counts it.
value must be a number of 0 or more on one of your own events: a numeric string such as "89.50" is ignored. revenue must be a number too, and goes on a purchase event (track("purchase", { revenue: 89.5, currency: "EUR" })). A negative revenue is a refund.
Revenue from Stripe or RevenueCat
Connect your Stripe account or RevenueCat project in the dashboard (Integrations → Revenue) and purchases, renewals, refunds and subscription cancels arrive server-side, without track() calls. A refund then takes back the task that person completed, and subscription_canceled can be a task’s revoke step. Give the provider the same id you pass to identify():
// Server, when you create the Checkout Session
await stripe.checkout.sessions.create({
// …
client_reference_id: user.id,
subscription_data: { metadata: { metrickle_user_id: user.id } }, // subscriptions
});
// Or once on the customer: metadata: { metrickle_user_id: user.id }
With RevenueCat in a React Native app, log in with the same id: await Purchases.logIn(user.id). If you already send revenue on a client-side purchase event, drop it there so revenue isn’t counted twice.
The feedback button
When the floating feedback button is on, it stays clear of keyboard focus on your page: the widget sets scroll-padding-bottom on <html> to the button’s height plus its margin, and adds the same space at the end of the page, so a focused link or field is never scrolled underneath it (WCAG 2.4.11 and 2.4.12). It does this only when your page hasn’t set its own scroll-padding-bottom; set one, even 0, to manage the space yourself. On screens 480px wide or less the button shows its icon only, keeping its label as the accessible name.
Survey follow-ups and studies
A survey can end with an invite into a study: a booked video call (moderated) or a self-guided usability test (unmoderated). You set this up in the dashboard, and the web SDK shows the invite in the survey card when the answers match. It only shows when the study is still taking people.
Participants in an unmoderated test arrive on your site with #mk_study=<token> in the URL. The SDK takes the token off the URL before the first pageview, then shows each task in a docked panel. The panel never takes focus on its own, and participants can fold it away while they work. It notices when a task’s success step happens, counts friction during each task and asks how easy it was. It also keeps its place across page loads in the same tab. While a test runs, surveys wait. If the participant agreed to recording on the study page, the session is recorded even when replay is off for your app. Cookieless mode records nothing.
In a moderated session, a participant who opens a link with the same kind of token sees a small notice that the visit is shared with the research team, with an “End session” button.
React Native
npm install @metrickle/sdk @react-native-async-storage/async-storage
import AsyncStorage from "@react-native-async-storage/async-storage";
import { AccessibilityInfo, AppState, Dimensions, PixelRatio, Platform } from "react-native";
import { init } from "@metrickle/sdk/react-native";
export const metrickle = init({
writeKey: "mk_pub_YOUR_WRITE_KEY",
storage: AsyncStorage,
appState: AppState,
os: Platform.OS,
osVersion: String(Platform.Version),
screen: Dimensions.get("screen"),
appVersion: "1.0.0",
accessibility: AccessibilityInfo, // screen reader, reduced motion, bold text, …
fontScale: PixelRatio.getFontScale, // reports large_text above 1.15
});
// With React Navigation: onStateChange={() => metrickle.screen(currentRouteName)}
metrickle.screen("Home");
metrickle.track("checkout_started", { items: 3 });
// Render surveys with your own components (see below). Returns an unsubscribe function.
const stopSurveys = metrickle.surveys.onShow((survey) => showSurveySheet(survey));
// Feedback (screenshot optional, as a data URL)
await metrickle.feedback.submit({ category: "bug", message: "Pay button does nothing" });
// Form validation errors: plain identifiers, never what the user typed
metrickle.formError("checkout", "card_number", "invalid");
Feedback can be switched off per platform under Settings → Research in the dashboard. While it’s off, metrickle.feedback.isEnabled is false and submit sends nothing, so use it to hide your feedback button.
init also takes debug, beforeSend, sessionTimeoutMs and flushIntervalMs, as on web. Pass storage: null for cookieless mode: no ids are kept on the device and surveys stay off. With storage, unsent events are saved (mk_queue, at most 1000) so they survive the app being killed; events older than 7 days are not sent. optOut(), optIn() and reset() work as on web, and an opt-out also clears the saved events.
Surveys and follow-ups
Your onShow callback gets an ActiveSurvey. Call survey.shown() once it’s on screen, survey.answer(question, answer) for each question in survey.campaign.questions, and survey.complete() after the last one, or survey.dismiss(index) if the user closes it. Calling the function onShow returned stops surveys from starting until you call onShow again.
A survey can end with an invite into a study. When survey.followUp is set, it says what to offer: kind ("moderated", a booked video call, or "unmoderated", a self-guided test that runs on the web), prompt (your heading), and optional incentive and durationMin. After the last answer:
import { Linking } from "react-native";
async function finish(survey: ActiveSurvey) {
survey.complete();
if (!survey.followUp || !survey.qualifies()) return showThankYou();
const url = await survey.invite(); // the respondent's personal link, or null
if (!url) return showThankYou();
survey.followUpOffered();
showInvite({
heading: survey.followUp.prompt,
action: survey.followUp.kind === "moderated" ? "Choose a time" : "Take part",
incentive: survey.followUp.incentive, // "As a thank-you: …"
onAccept: () => {
survey.followUpAccepted();
void Linking.openURL(url); // opens in the browser: say so in the button's accessibilityHint
showThankYou();
},
onDecline: showThankYou, // "No thanks"
});
}
invite() resolves null when the study stopped taking people, the response doesn’t qualify, the visitor opted out or the request failed. followUpOffered() and followUpAccepted() each record $survey_follow_up once per response.
Rage taps
Three taps within a second in the same spot (30pt) are sent as $rage_click. It’s opt-in: attach the handler to your root view.
<View style={{ flex: 1 }} onTouchStart={metrickle.touch}>
<App />
</View>
// To name the view in the event's selector, pass its testID:
<Pressable testID="pay-button" onTouchStart={(e) => metrickle.touch(e, "pay-button")} />
Without a testID the event’s selector is null. text is always null on React Native.
Dead and slow taps
A tap on a button that does nothing is the React Native version of a dead click. It’s opt-in: wrap the pressable component you use once, then use the wrapped one in its place.
import React from "react";
import { Pressable } from "react-native";
export const Tap = metrickle.pressable(Pressable, React); // also works with TouchableOpacity or your own button
<Tap testID="pay-button" accessibilityLabel="Pay now" onPress={pay}>…</Tap>
Each press is judged the way the web SDK judges clicks. If the app answers within a second, nothing is sent. An answer between 1 and 4 seconds sends $slow_click with ms, and no answer within 4 seconds sends $dead_click. An answer is any of:
- the wrapped component re-rendering (state above it changed),
- the wrapped component unmounting (the screen changed),
- any event the SDK records, such as
screen(), your owntrack(), or the app going to the background to open a link.
Both events carry selector (the testID, or null), text (the accessibilityLabel, at most 80 characters, or null), input: "touch" and affordance: control when the component has an onPress or onLongPress, pointer when it has neither and only looks pressable. Your handlers run unchanged. Presses on a disabled component never reach the wrapper, so they aren’t judged.
Accessibility context
Pass AccessibilityInfo and PixelRatio.getFontScale to init to report screen reader, reduced motion, reduced transparency, bold text, greyscale, inverted colours, high contrast and large text. The keyboard flag (a hardware keyboard) isn’t reported on React Native, which has no JavaScript API for it.
Other platforms
@metrickle/sdk/core exports the platform-agnostic MetrickleClient. You provide the storage and transport. For Swift, Kotlin, Flutter or server code, post batches to the HTTP API at POST https://in.metrickle.com/v1/batch.