@metrickle/sdk
v0.2.0
Published
Metrickle analytics SDK for web and React Native
Maintainers
Readme
@metrickle/sdk
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, u-turns, form abandonment) 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 and session replay are configured in the Metrickle dashboard. Their UI and recorder load only when you turn them on.
Install
npm install @metrickle/sdkWeb
import { init } from "@metrickle/sdk";
const metrickle = init({
writeKey: "mk_pub_...", // 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 bannerThe 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, error clicks, u-turns, form errors and abandonment |
| a11y | true | Accessibility settings as event context |
| research | true | Surveys, feedback, heatmaps and replay 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, debug | | |
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_..."></script>This exposes window.metrickle. Add data-cookieless for cookieless tracking, and data-link-domains="example.com shop.example.net" for linkDomains.
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 resumesoptOut() 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_...", 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 at stake, and cases count it as money lost. Attempts without one count at the average value of a success. Only revenue counts as revenue, so cart values never inflate it.
value must be a number on one of your own events: a numeric string such as "89.50" is ignored. The same goes for revenue, which you put 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-storageimport 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_...",
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.
Accessibility context
Pass AccessibilityInfo and PixelRatio.getFontScale to init to report screen reader, reduced motion, reduced transparency, bold text, grayscale, inverted colors, 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.
License
MIT
