matomo-react-native
v1.0.5
Published
Enhanced Matomo tracking library for React Native and Expo projects with TypeScript support and automatic platform detection.
Maintainers
Readme
Matomo React Native
Enhanced TypeScript version of the Matomo tracker for React Native and Expo projects with automatic platform detection and comprehensive Matomo API support.
Credits
This package is based on the excellent work by donni106/matomo-tracker-react-native. The original JavaScript implementation has been converted to TypeScript and enhanced with additional features including:
- 🔥 Full TypeScript support with comprehensive type definitions
- 📱 Automatic platform detection (iOS/Android/web) using
Platform.OS - 🌐 Enhanced Matomo API compliance with referrer tracking, user agents, and timestamps
- 🎯 Simplified API with all parameters optional and intelligent defaults
- 📊 Production tested against live Matomo instances
Special thanks to the original contributors and the foundation packages:
- donni106/matomo-tracker-react-native - Original React Native implementation
- matomo-org/matomo-nodejs-tracker - Node.js foundation
- Amsterdam/matomo-tracker - React foundation
Why This Enhanced Version?
The original package provides excellent Matomo tracking for React Native. This enhanced version adds:
- Zero configuration required - works out of the box with automatic platform detection
- Full TypeScript integration - comprehensive interfaces and type safety
- Enhanced tracking parameters - automatic referrer detection, user agents, and platform-specific data
- Modern development experience - IntelliSense support and compile-time error checking
Installation
npm install matomo-react-nativeOr with yarn:
yarn add matomo-react-nativeQuick Start
import React, { useEffect } from 'react';
import { View } from 'react-native';
import MatomoTracker, { MatomoProvider, useMatomo } from 'matomo-react-native';
// Create tracker instance
const tracker = new MatomoTracker({
urlBase: 'https://your-matomo-domain.com',
siteId: 1, // Your Matomo site ID
});
// Your main app component
const MainApp = () => {
const { trackAppStart } = useMatomo();
useEffect(() => {
// Track app start - automatically detects platform (iOS/Android/web)
trackAppStart();
}, []);
return <View>Your App Content</View>;
};
// Wrap your app with the provider
export const App = () => (
<MatomoProvider instance={tracker}>
<MainApp />
</MatomoProvider>
);That's it! The tracker will automatically detect the platform and send appropriate tracking data to your Matomo instance.
Configuration Options
MatomoTracker Constructor
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| urlBase | string | ✅ | - | Your Matomo server domain (e.g., 'https://matomo.example.com') |
| siteId | number | ✅ | - | Your Matomo site ID |
| trackerUrl | string | ❌ | ${urlBase}matomo.php | Custom tracker endpoint if different from default |
| userId | string | ❌ | undefined | Unique user identifier for cross-session tracking |
| disabled | boolean | ❌ | false | Disable all tracking when true |
| log | boolean | ❌ | false | Enable debug logging |
const tracker = new MatomoTracker({
urlBase: 'https://your-matomo.com',
siteId: 1,
userId: 'user123', // Optional: for user-specific tracking
log: true, // Optional: enable debug logs
});Enhanced Features
Automatic Platform Detection
The tracker automatically detects the platform and sends appropriate data:
// Automatically detects iOS/Android/web and sends platform-specific data
await tracker.trackAppStart();
// Override platform detection if needed
await tracker.trackAppStart({
platform: 'custom-platform',
userAgent: 'CustomApp/1.0'
});Referrer Tracking
Enhanced support for referrer tracking:
await tracker.trackAppStart({
referrer: 'https://your-website.com'
});
await tracker.trackPageView({
name: 'Home Screen',
referrer: 'https://external-site.com'
});Type Safety with TypeScript
Full TypeScript support with comprehensive interfaces:
import { MatomoTrackEventOptions, MatomoUserInfo } from 'matomo-react-native';
const eventData: MatomoTrackEventOptions = {
category: 'User Interaction',
action: 'Button Press',
name: 'Sign Up Button',
value: 1
};
const userInfo: MatomoUserInfo = {
userId: 'user123',
customData: { plan: 'premium' }
};API Reference
useMatomo Hook
All tracking methods are available through the useMatomo hook:
const {
trackAppStart,
trackPageView,
trackEvent,
trackAction,
trackContent,
trackSiteSearch,
trackLink,
trackDownload,
updateUserInfo,
removeUserInfo
} = useMatomo();trackAppStart(options?)
Tracks app start with automatic platform detection. All parameters are optional.
// Simple usage - automatic platform detection
await trackAppStart();
// With custom options
await trackAppStart({
url: '/home',
referrer: 'https://mywebsite.com',
platform: 'ios', // Will auto-detect if not provided
userAgent: 'MyApp/1.0', // Will auto-generate if not provided
userInfo: { userId: 'user123' }
});| Parameter | Type | Description |
|-----------|------|-------------|
| url | string | Custom URL for the app start event |
| referrer | string | Referrer URL (urlref parameter) |
| platform | string | Platform override (auto-detected from Platform.OS) |
| userAgent | string | Custom user agent (auto-generated if not provided) |
| userInfo | MatomoUserInfo | Additional user information |
trackPageView(options)
Tracks page/screen views with enhanced parameters:
await trackPageView({
name: 'Home Screen', // Required
url: '/home',
referrer: 'https://external-site.com',
userInfo: { userId: 'user123' }
});| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| name | string | ✅ | Screen/page name |
| url | string | ❌ | Page URL |
| referrer | string | ❌ | Referrer URL |
| userInfo | MatomoUserInfo | ❌ | User information |
trackEvent(options)
Tracks custom events:
await trackEvent({
category: 'User Interaction', // Required
action: 'Button Press', // Required
name: 'Sign Up Button',
value: 1,
url: '/signup',
campaign: 'summer-promo',
userInfo: { userId: 'user123' }
});| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| category | string | ✅ | Event category |
| action | string | ✅ | Event action |
| name | string | ❌ | Event name |
| value | number | ❌ | Numeric event value |
| url | string | ❌ | Associated URL |
| campaign | string | ❌ | Campaign identifier |
| userInfo | MatomoUserInfo | ❌ | User information |
trackAction(options)
Tracks general actions:
await trackAction({
name: 'Help / Contact Form', // Required - supports categories with /
url: '/help/contact',
userInfo: { userId: 'user123' }
});trackContent(options)
Tracks content impressions and interactions:
await trackContent({
name: 'Banner Ad', // Required
piece: '/images/banner.jpg',
target: 'https://example.com',
interaction: 'click',
url: '/home',
userInfo: { userId: 'user123' }
});trackSiteSearch(options)
Tracks site search queries:
await trackSiteSearch({
keyword: 'react native', // Required
category: 'documentation',
count: 42,
url: '/search',
userInfo: { userId: 'user123' }
});trackLink(options) & trackDownload(options)
Track external links and downloads:
await trackLink({
link: 'https://external-site.com', // Required
url: '/current-page'
});
await trackDownload({
download: 'https://example.com/file.pdf', // Required
url: '/downloads'
});User Information Management
// Update user info
await updateUserInfo({
userInfo: { userId: 'user123', customData: { plan: 'premium' } }
});
// Remove user info
await removeUserInfo();trackReferralUrl(options) - NEW!
Tracks referral sources for attribution:
await trackReferralUrl({
referralUrl: 'https://facebook.com/post/123', // Required
source: 'facebook', // Optional - auto-extracted from URL
medium: 'social',
campaign: 'summer-2024',
url: '/landing-page',
userInfo: { userId: 'user123' }
});This method tracks where users came from by recording referral information as an event with proper campaign attribution. Perfect for measuring marketing campaign effectiveness!
trackAdClick(options) - NEW!
Tracks advertisement clicks using content tracking:
await trackAdClick({
adId: 'banner-001', // Required
adName: 'Summer Sale Banner', // Required
adSource: 'homepage',
adCampaign: 'summer-2024',
targetUrl: 'https://example.com/sale',
url: '/home',
userInfo: { userId: 'user123' }
});Records when users click on advertisements, providing insights into ad performance and engagement.
trackAdImpression(options) - NEW!
Tracks advertisement impressions (views):
await trackAdImpression({
adId: 'banner-001', // Required
adName: 'Summer Sale Banner', // Required
adSource: 'homepage',
adCampaign: 'summer-2024',
url: '/home',
userInfo: { userId: 'user123' }
});Records when advertisements are displayed to users, helping measure ad visibility and reach. Perfect for tracking ad performance and calculating CTR (Click-Through Rate)!
TypeScript Support
This package is written in TypeScript and provides comprehensive type definitions:
import {
MatomoTracker,
MatomoProvider,
useMatomo,
MatomoUserInfo,
MatomoTrackEventOptions,
MatomoTrackPageViewOptions,
MatomoTrackAppStartOptions,
MatomoInitOptions
} from 'matomo-react-native';Type Definitions
interface MatomoUserInfo {
userId?: string;
visitorId?: string;
customData?: Record<string, any>;
// ... additional user info fields
}
interface MatomoTrackEventOptions {
category: string;
action: string;
name?: string;
value?: number;
url?: string;
campaign?: string;
userInfo?: MatomoUserInfo;
}
// All tracking options have comprehensive type definitionsPlatform Detection
The package automatically detects the platform using React Native's Platform.OS:
- iOS: Sends appropriate iOS user agents and platform identifiers
- Android: Sends Android-specific tracking data
- Web: Detects web platform when running in browser environments
- Custom: Allows manual override for custom platforms
import { Platform } from 'react-native';
// Automatic detection
console.log(Platform.OS); // 'ios', 'android', 'web', etc.
// The tracker uses this automatically, but you can override:
await trackAppStart({
platform: 'custom-platform',
userAgent: 'MyCustomApp/1.0'
});Migration from Original Package
If you're migrating from matomo-tracker-react-native, the API is fully backward compatible:
- Update your package.json:
- "matomo-tracker-react-native": "^0.3.3"
+ "matomo-react-native": "^1.0.0"- Update imports:
- import MatomoTracker, { MatomoProvider, useMatomo } from 'matomo-tracker-react-native';
+ import MatomoTracker, { MatomoProvider, useMatomo } from 'matomo-react-native';- Your existing tracking calls work unchanged:
// This still works exactly the same
const { trackAppStart, trackEvent } = useMatomo();
await trackAppStart();
await trackEvent({ category: 'test', action: 'click' });- Optionally, take advantage of new features:
// New enhanced features
await trackAppStart({
referrer: 'https://mysite.com',
platform: 'ios' // or let it auto-detect
});Examples
Basic Setup
import React from 'react';
import { App } from './App';
import MatomoTracker, { MatomoProvider } from 'matomo-react-native';
const tracker = new MatomoTracker({
urlBase: 'https://your-matomo.com',
siteId: 1
});
export default function AppWrapper() {
return (
<MatomoProvider instance={tracker}>
<App />
</MatomoProvider>
);
}Navigation Tracking
import { useMatomo } from 'matomo-react-native';
import { useEffect } from 'react';
function HomeScreen({ route }) {
const { trackPageView } = useMatomo();
useEffect(() => {
trackPageView({
name: 'Home Screen',
url: route.name
});
}, []);
return <YourHomeComponent />;
}Event Tracking
function SignUpButton() {
const { trackEvent } = useMatomo();
const handlePress = async () => {
await trackEvent({
category: 'User Interaction',
action: 'Button Press',
name: 'Sign Up',
value: 1
});
// Continue with your sign up logic
};
return <Button onPress={handlePress} title="Sign Up" />;
}Ad Tracking Example
function AdBanner({ adId, adName, targetUrl }) {
const { trackAdImpression, trackAdClick } = useMatomo();
useEffect(() => {
// Track ad impression when component mounts
trackAdImpression({
adId,
adName,
adSource: 'app-banner',
adCampaign: 'summer-2024'
});
}, [adId]);
const handleAdClick = async () => {
// Track ad click
await trackAdClick({
adId,
adName,
adSource: 'app-banner',
adCampaign: 'summer-2024',
targetUrl
});
// Navigate to ad target
Linking.openURL(targetUrl);
};
return (
<TouchableOpacity onPress={handleAdClick}>
<Image source={{ uri: adImage }} />
</TouchableOpacity>
);
}Referral Tracking Example
function App() {
const { trackReferralUrl } = useMatomo();
useEffect(() => {
// Track referral from deep link
const handleDeepLink = async (url) => {
const referrer = getReferrerFromUrl(url);
if (referrer) {
await trackReferralUrl({
referralUrl: referrer,
source: 'deep-link',
medium: 'app',
campaign: getCampaignFromUrl(url)
});
}
};
// Setup deep link listener
Linking.getInitialURL().then(handleDeepLink);
const subscription = Linking.addEventListener('url', ({ url }) => {
handleDeepLink(url);
});
return () => subscription.remove();
}, []);
return <YourApp />;
}Contributing
Contributions are welcome! This package builds upon the excellent foundation of the original matomo-tracker-react-native.
Please see the original repository for contribution guidelines: donni106/matomo-tracker-react-native
License
This package maintains the same license as the original project. See LICENSE for details.
Changelog
See CHANGELOG.md for version history and updates.
Enhanced TypeScript version | Based on donni106/matomo-tracker-react-native | Version 1.0.0
