Web Analytics by ostr.io
ostr.io provides lightweight, privacy-respectful, real-time web analytics for modern SPAs and MPAs. The tracker works out-of-the-box with all websites and webpages, including: WordPress, WebFlow, React, Next.js, Vue, Nuxt, Svelte, Angular, Meteor/Blaze, Backbone, Ember, and vanilla JS.
- 👐 Open-source tracking code
- 📦 Lightweight
- 🚀 Real-time metrics
- 😎 No DOM mutations; no heavy CPU tasks; no extra script chains
- 📡 Supports various transports:
fetch,img,beacon; falls back gracefully - 🤝 SPA-friendly: HTML5 History API and navigation events support out-of-the-box
- ⚡️ AMP tracking
- 🛑 AdBlock detection
- 🔍 Transparent data collection; GDPR/CCPA-aligned controls
- 🙆 Easy, hosted opt-out for end-users
- 🐞 Global runtime error reporting (including
unhandledPromise rejections)
- Real-time users, sessions, unique users.
- Pageviews
- Page title
- Page URL (sanitized per your config)
- Demographics
- Country
- City
- System
- Device (mobile/desktop)
- Browser
- OS
- Behavior
- Custom events (see
pushEvent) - Referrers
- Custom events (see
- Global script errors & exceptions
- Error message and source
- Browser and OS
- Device data
- File name and line/column
To get your trackingId, open the Analytics section in your ostr.io dashboard, select the domain, then click Show integration guide.
Tip
Easiest way — no build tooling required.
See "integration guide" at ostr.io analytics panel to copy-paste <script> element
<link rel="preconnect" href="https://analytics.ostr.io/" crossorigin>
<link rel="dns-prefetch" href="https://analytics.ostr.io/">
<script async defer src="https://analytics.ostr.io/{{trackingId}}.js"></script>Important
When tracking code is loaded from analytics.ostr.io via script-tag it will automatically execute in "auto" mode and will be available in the global scope as OstrioTracker.
Example: OstrioTracker.pushEvent(foo, bar);
Install from NPM or YARN
npm install ostrio-analytics --saveThen import or require()
// TypeScript
import Analytics from "ostrio-analytics/source";
const analyticsTracker = new Analytics('{{trackingId}}');
// ESM
import Analytics from 'ostrio-analytics';
const analyticsTracker = new Analytics('{{trackingId}}');
// CommonJS
const analyticsClass = require('ostrio-analytics');
const analyticsTracker = new analyticsClass('{{trackingId}}');Copy-paste minified version of the analytics script. Or use Unpkg/JSDelivr to load minified version from CDN.
<script src="https://unpkg.com/ostrio-analytics@2.0.0/dist/ostrio-analytics.min.js"></script><script src="https://cdn.jsdelivr.net/npm/ostrio-analytics@2.0.0/dist/ostrio-analytics.min.js"></script>Note
After adding minified analytics code to a project (using any of the methods above) — it will be available as OstrioTrackerClass in the global scope
// Example:
const analyticsTracker = new OstrioTrackerClass('{{trackingId}}');
// Example 2:
const analyticsTracker = new window.OstrioTrackerClass('{{trackingId}}');Use default settings or extend with additional options object
new Analytics(trackingId: string, options?: OstrioWebAnalyticsConfig);
interface OstrioWebAnalyticsConfig {
auto?: boolean; // default: true
trackErrors?: boolean; // default: true
trackHash?: boolean; // default: true
trackQuery?: boolean; // default: true
ignoredQueries?: string[]; // case-insensitive query keys to drop
ignoredPaths?: (string|RegExp)[]; // '/path/*' prefix, '/path/' exact, or RegExp
transport?: 'fetch' | 'beacon' | 'img'; // default: 'fetch'
}Important
Constructor throws Error('[init] {{trackingId}} is missing or incorrect!') if the trackingId is not a 17-char string
trackingId{string} - [Required] Website' identifier. To obtaintrackingIdgo to Analytics section and select a domain name;options- {OstrioWebAnalyticsConfig} - [Optional]options.auto- {boolean} - Set tofalseto disable automated page navigation trackingoptions.trackErrors- {boolean} - Set tofalseto disable automated page-level JS errors and exceptions trackingoptions.trackHash- {boolean} - Set tofalseto disable automated tracking of changes in#hashof the page; All reported URLs will have hash omittedoptions.trackQuery- {boolean} - Set tofalseto disable tracking changes in get query?get=query; All reported URLs will have get-query omittedoptions.ignoredQueries- {string[]} - Array of case-insensitive query keys to exclude from analytics trackingoptions.ignoredPaths- {(string|RegExp)[]} - Array of case-sensitive paths and RegExp with URI paths that will be ignored and excluded from web analytics; Use/*to define "beginning" or the path; Use to exclude "service" URLs from tracking like/admin/*; Examples:['/path/starts/with/*', '/exact-path/', /^\/category\/[0-9a-zA-Z]{10}\/?$/]options.transport- {'fetch' | 'beacon' | 'img'} - Set preferred transport; Default:fetch
Tip
After initializing new Analytics() — it's good to go, visitor navigation will be collected and reported in ostr.io analytics. For {auto: false}, additional settings, and custom events - see below.
List of all methods and its arguments available on OstrioWebAnalytics instance:
import Analytics from "ostrio-analytics/source";
const analyticsTracker = new Analytics('{{trackingId}}');
// CHANGE SETTINGS DURING RUNTIME
analyticsTracker.applySettings(settings: OstrioWebAnalyticsDynamicConfig);
interface OstrioWebAnalyticsDynamicConfig {
trackHash?: boolean;
trackQuery?: boolean;
transport?: Transport;
serviceUrl?: string;
}
// CHANGE TRANSPORT DURING RUNTIME
analyticsTracker.setTransport(Transport); // [Transport.Fetch, Transport.Beacon, Transport.Img]
// ADD IGNORED PATH DURING RUNTIME
analyticsTracker.ignorePath(path: string | RegExp);
// ADD MULTIPLE IGNORED PATHS DURING RUNTIME
analyticsTracker.ignorePaths(paths: Array<string | RegExp>);
// ADD IGNORED GET-QUERY DURING RUNTIME
analyticsTracker.ignoreQuery(queryKey: string);
// ADD MULTIPLE IGNORED GET-QUERIES DURING RUNTIME
analyticsTracker.ignoreQueries(queryKeys: Array<string>);
// ADD HOOK FOR .pushEvent() CALLS
analyticsTracker.onPushEvent(callback: Function);
// ADD HOOK FOR .track() CALLS
analyticsTracker.onTrack(callback: Function);
// TRACK CUSTOM EVENT
analyticsTracker.pushEvent(key: string, value: number | string);
// TRACK PAGEVIEW; USE WITH {auto: false} SETTING
analyticsTracker.track();
// STOP AUTO-TRACKING
analyticsTracker.destroy();Use analyticsTracker.pushEvent(key, value) method to collect and track custom user's events. Custom events are useful for tracking certain activity on your website, like clicks, form submits and others user's behaviors.
key{string} - [Required] The length of the event key must be between 1 and 24 symbols;value{string} - [Required] The length of the event value must be between 1 and 64 symbols.
If the length of key or value is longer than limits, it will be truncated without throwing an exception.
Examples:
// Various examples on tracking custom user's actions
analyticsTracker.pushEvent('userAction', 'login');
analyticsTracker.pushEvent('userAction', 'logout');
analyticsTracker.pushEvent('userAction', 'signup');
analyticsTracker.pushEvent('click', 'purchase');
analyticsTracker.pushEvent('click', 'purchase-left');
analyticsTracker.pushEvent('click', 'pricing - more info');<script type="text/javascript">
// make analyticsTracker global variable
window.analyticsTracker = analyticsTracker;
</script>
<form>
<h2>Buy Now</h2>
<select>
<option disabled>Select product</option>
<option>Blue</option>
<option>Red</option>
<option>Green</option>
</select>
<input name="qty" />
<!-- Example on tracking form submit -->
<button type="submit" onClick="analyticsTracker.pushEvent('checkout', 'buy-now-form')">Checkout</button>
</form>In a similar way using .pushEvent you can detect and track AdBlock usage and Accelerated Mobile Pages (AMP).
Manually dispatch a pageview.
Tip
Use .track() method with {auto: false} to manually and precisely control navigation's events and send tracking info. This method has no arguments.
Examples:
/* jQuery or any other similar case: */
$(document).ready(() => {
analyticsTracker.track();
});
/* JS-router definition (pseudo-code!) */
router({
'/'() {
analyticsTracker.track();
},
'/two'() {
analyticsTracker.track();
},
'/three'() {
analyticsTracker.track();
}
});
/* Although "History.js" and "History API" supported out-of-box,
you may want to optimize tracking behavior to meet your needs. */
History.Adapter.bind(window, 'statechange', () => {
analyticsTracker.track();
});Use .onPushEvent() to hook into .pushEvent() method. Read how to use this method for deep Google Analytics integration.
Examples:
analyticsTracker.onPushEvent((key, value) => {
console.log({ key, value }); // { key: 'testKey', value: 'testValue' }
});
analyticsTracker.pushEvent('testKey', 'testValue');Use .onTrack() to hook into .track() method and browser navigation in {auto: true} mode. Read how to use this method for deep Google Analytics integration.
Examples:
// Callback will be executed on every browser navigation and upon calling `.track()` method
analyticsTracker.onTrack(() => {
console.log('Tracking a session'); // Tracking a session
});Call .destroy() to unbind listeners and timers (useful on SPA teardown/HMR).
analyticsTracker.destroy();Explore advanced settings and its usage
{ transport: 'beacon' }– usesnavigator.sendBeaconwhen available (best for unload/background sends, but commonly blocked by browsers){ transport: 'fetch' }(default) – usesfetchwith{ mode: 'no-cors', cache: 'no-store' }{ transport: 'img' }– legacy image-pixel transport for top compatibility with various browsers
const analyticsTracker = new Analytics('{{trackingId}}', { transport: 'img' });
// OR DURING RUNTIME:
analyticsTracker.setTransport('beacon');Exclude paths from tracking with exact match, prefix, or RegExp. Use .ignorePath() or .ignorePaths() to add ignored paths during runtime:
analyticsTracker.ignorePath('/admin/*');
analyticsTracker.ignorePath('/payment/status/complete');
analyticsTracker.ignorePath(/^\/_next\//i);
// OR ADD ALL AS ARRAY IN ONE CALL
analyticsTracker.ignorePaths(['/admin/*', '/payment/status/complete']);Use ignoredPaths as part of the Constructor config object:
const analyticsTracker = new Analytics('{{trackingId}}', {
ignoredPaths: [
'/admin/', // exact match
'/api/*', // prefix match
/^\/_next\// // RegExp
]
});Note
Note: Referral source is tracked via HTTP headers
Remove noisy query keys (case-insensitive) from URL change detection and payload. Use .ignoreQuery() or .ignoreQueries() to add ignored paths during runtime:
analyticsTracker.ignoreQuery('utm');
analyticsTracker.ignoreQuery('ref');
// OR ADD ALL AS ARRAY IN ONE CALL
analyticsTracker.ignoreQueries(['gclid', 'fbclid', 'sessionid']);Use ignoredQueries as part of the Constructor config object:
const analyticsTracker = new Analytics('{{trackingId}}', {
ignoredQueries: ['utm_source', 'utm_medium', 'gclid', 'fbclid', 'sessionid']
});Control what constitutes a “new page” for SPAs:
const analyticsTracker = new Analytics('{{trackingId}}', {
trackHash: false, // don't treat #hash changes as navigation (default: true)
trackQuery: false // don't treat ?query changes as navigation (default: true)
});
// OR UPDATE SETTING DURING RUNTIME:
analyticsTracker.applySettings({
trackHash: false,
trackQuery: false
});Explore various custom usage examples
Using .onTrack() method and .onPushEvent() method we can send tracking-data to Google Analytics upon navigation or event.
In your <head> add Google Analytics as instructed:
<script async src="https://www.google-analytics.com/analytics.js"></script>
<script type='text/javascript'>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXXXXXX-X', 'auto');
</script>import Analytics from 'ostrio-analytics';
const analyticsTracker = new Analytics('{{trackingId}}');
analyticsTracker.onTrack(() => {
// Track navigation with Google Analytics
ga('send', {
hitType: 'pageview',
page: document.location.pathname,
location: document.location.href,
title: document.title
});
});
analyticsTracker.onPushEvent((name, value) => {
// Send events to Google Analytics
ga('send', {
hitType: 'event',
eventCategory: name,
eventAction: value
});
});Using .onTrack() method and .onPushEvent() method we can send tracking-data to Google Tag Manager upon navigation or event.
In page's <head> add Google Tag Manager as instructed:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script type='text/javascript'>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
</script>import Analytics from 'ostrio-analytics';
const analyticsTracker = new Analytics('{{trackingId}}');
analyticsTracker.onTrack(() => {
// Track navigation with Google Analytics
gtag('config', 'UA-XXXXXXXXX-X', {
page_title: document.title,
page_path: document.location.pathname,
page_location: document.location.href
});
});
analyticsTracker.onPushEvent((name, value) => {
// Send events to Google Analytics
gtag('event', name, { value });
});Tip
Provide a one-click opt-out link in project's legal/settings pages to follow the best privacy experience practices
https://analytics.ostr.io/settings/manage/opt-out/
- Add one-click opt-out link to legal documents and "settings" page
- Click here to check your browser current settings