Documentation
Complete guide to integrating and using the Metricly tracking system
Getting Started
Get up and running with Metricly in just a few minutes. The SDK is lightweight, privacy-focused, and easy to integrate.
Step 1: Get Your API Key
After creating a project in your dashboard, you'll receive an API key. This key uniquely identifies your project and should be kept secure.
Step 2: Install the SDK
Add the Metricly script tag to your website. Place it in the <head> or just before the closing </body> tag.
<script
src="https://YOUR_DOMAIN/sdk"
data-key="YOUR_PROJECT_API_KEY"
data-autotrack="true"
defer
></script>Step 3: Verify Installation
Once installed, the SDK will automatically start tracking page views. You can verify it's working by:
- Checking your browser's developer console for any errors
- Visiting your dashboard to see if page views are being recorded
- Using the browser console to check if
window.analyticsSaasis available
Configuration Options
Customize the SDK behavior using data attributes on the script tag. All options are optional and have sensible defaults.
data-key / data-project
Required. Your project's API key. You can use either data-key or data-project.
data-key="your-api-key-here"data-api
Optional. Custom endpoint URL for sending analytics data. Defaults to /api/analytics/collect.
data-api="https://your-domain.com/api/analytics/collect"data-autotrack
Optional. Enable or disable automatic page view tracking. When enabled, the SDK automatically tracks page views and handles SPA route changes. Defaults to true.
data-autotrack="true" or data-autotrack="false"When set to false, you'll need to manually call analyticsSaas.page() for each page view.
data-consent-required
Optional. Require explicit user consent before tracking. When enabled, tracking is paused until analyticsSaas.consent(true) is called. Defaults to false.
data-consent-required="true"Useful for GDPR compliance. Events are queued when consent is not granted and sent once consent is provided.
data-heartbeat-ms
Optional. Interval in milliseconds for heartbeat events that track user engagement. Defaults to 15000 (15 seconds).
data-heartbeat-ms="30000"Heartbeat events help measure engagement time. Lower values provide more granular data but increase network requests.
Complete Example
<script
src="https://analytics.example.com/sdk"
data-key="your-api-key-here"
data-api="https://analytics.example.com/api/analytics/collect"
data-autotrack="true"
data-consent-required="false"
data-heartbeat-ms="15000"
defer
></script>API Reference
The SDK exposes a global window.analyticsSaas object with methods for tracking events and managing the SDK.
analyticsSaas.page()
Manually track a page view. Useful when data-autotrack="false" or for tracking virtual page views in single-page applications.
analyticsSaas.page()// Track a page view
analyticsSaas.page();
// In a React Router app
useEffect(() => {
analyticsSaas.page();
}, [location]);analyticsSaas.track(eventName, eventProps)
Track a custom event with an optional properties object. This is the primary method for tracking user interactions, conversions, and business events.
analyticsSaas.track(eventName: string, eventProps?: object)Parameters:
eventName(required) - Name of the event (e.g., "signup", "purchase", "button_click")eventProps(optional) - Object containing additional event properties
// Simple event
analyticsSaas.track('button_click');
// Event with properties
analyticsSaas.track('signup', {
plan: 'Pro',
source: 'landing_page'
});
// E-commerce purchase
analyticsSaas.track('purchase', {
order_id: '12345',
value: 99.99,
currency: 'USD',
items: [
{ name: 'Product A', quantity: 2, price: 49.99 }
]
});analyticsSaas.consent(allowed)
Grant or revoke user consent for tracking. When data-consent-required="true", tracking is paused until consent is granted.
analyticsSaas.consent(allowed: boolean)// Grant consent
analyticsSaas.consent(true);
// Revoke consent (stops tracking)
analyticsSaas.consent(false);
// Example: GDPR consent banner
function handleConsentAccept() {
analyticsSaas.consent(true);
// Hide consent banner
}
function handleConsentReject() {
analyticsSaas.consent(false);
// Hide consent banner
}analyticsSaas.identify()
Currently a no-op function provided for API compatibility with other analytics libraries. User identification is not currently persisted on the server.
analyticsSaas.identify()This method exists for compatibility but does not perform any action. Future versions may implement user identification.
Examples
Common use cases and code examples for integrating Metricly into your application.
Basic HTML Website
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<script
src="https://analytics.example.com/sdk"
data-key="your-api-key"
defer
></script>
</head>
<body>
<h1>Welcome</h1>
<button onclick="analyticsSaas.track('button_click', { button: 'welcome' })">
Click Me
</button>
</body>
</html>React Application
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function App() {
const location = useLocation();
useEffect(() => {
// Track page views on route change
if (window.analyticsSaas) {
window.analyticsSaas.page();
}
}, [location]);
const handleSignup = () => {
// Track signup event
if (window.analyticsSaas) {
window.analyticsSaas.track('signup', {
plan: 'Pro',
source: 'homepage'
});
}
};
return (
<div>
<button onClick={handleSignup}>Sign Up</button>
</div>
);
}E-commerce Purchase Tracking
function completePurchase(order) {
if (window.analyticsSaas) {
window.analyticsSaas.track('purchase', {
order_id: order.id,
value: order.total,
currency: order.currency,
items: order.items.map(item => ({
name: item.name,
quantity: item.quantity,
price: item.price
}))
});
}
}GDPR Consent Management
<!-- HTML with consent required -->
<script
src="https://analytics.example.com/sdk"
data-key="your-api-key"
data-consent-required="true"
defer
></script>
<!-- Consent banner -->
<div id="consent-banner">
<p>We use cookies to analyze traffic. Do you consent?</p>
<button onclick="acceptConsent()">Accept</button>
<button onclick="rejectConsent()">Reject</button>
</div>
<script>
function acceptConsent() {
if (window.analyticsSaas) {
window.analyticsSaas.consent(true);
}
document.getElementById('consent-banner').style.display = 'none';
localStorage.setItem('analytics-consent', 'true');
}
function rejectConsent() {
if (window.analyticsSaas) {
window.analyticsSaas.consent(false);
}
document.getElementById('consent-banner').style.display = 'none';
localStorage.setItem('analytics-consent', 'false');
}
// Check for existing consent on page load
if (localStorage.getItem('analytics-consent') === 'true') {
if (window.analyticsSaas) {
window.analyticsSaas.consent(true);
}
document.getElementById('consent-banner').style.display = 'none';
}
</script>Privacy & Compliance
Metricly is built with privacy as a core principle. Learn about our privacy features and compliance options.
Do Not Track (DNT) Support
The SDK automatically respects the browser's Do Not Track setting. When DNT is enabled, no tracking events are sent to the server.
Note: The SDK checks both navigator.doNotTrack and window.doNotTrack properties.
Consent Management
For GDPR and other privacy regulations, use the consent management features:
- Set
data-consent-required="true"to pause tracking until consent is granted - Use
analyticsSaas.consent(true)to grant consent - Events are queued when consent is not granted and sent once consent is provided
- Use
analyticsSaas.consent(false)to revoke consent and stop tracking
Data Collection
Metricly collects minimal data:
- Page path - The URL path of the page
- Page title - The document title
- Referrer - The referring URL (if available)
- UTM parameters - Campaign tracking parameters from the URL
- Screen resolution - Coarse screen size bucket (e.g., "1920x1080")
- Country - ISO-2 country code (derived from IP, not stored)
- User agent - Browser and device information
Privacy First: IP addresses are never stored. Only truncated IP prefixes are used for country detection and visitor hashing. No cookies or persistent identifiers are used.
Session Tracking
Sessions are tracked using a session ID stored in localStorage. This allows for visitor approximation across page views while maintaining privacy.
The session ID is generated randomly and stored locally. It's not tied to any personally identifiable information.
Dashboard Features
Learn about powerful features available in your analytics dashboard for managing projects, teams, and analyzing data.
Team Invitations and Permissions
Invite team members to your organization and manage their access levels. The platform supports three role types:
- Owner - Full access to all features, can manage team members and organization settings
- Admin - Can create and manage projects, goals, funnels, and alerts. Cannot manage organization settings
- Viewer - Read-only access to view analytics data and reports
How to invite team members:
- Go to your project settings and click on "Organization Members"
- Click "Invite Member" and enter the email address
- Select the role (Admin or Viewer)
- The invitee will receive an email invitation
- They can accept the invitation by clicking the link in the email
Invitations expire after a set period. Only owners and admins can invite new members. Viewers have read-only access and cannot modify any settings.
Multi-Site Aggregated Analytics
View combined analytics across multiple projects in a single dashboard. This is useful when you manage multiple websites or applications and want to see overall performance.
How to use aggregated analytics:
- Navigate to your dashboard without selecting a specific project
- Click the "Aggregated View" button
- Select the projects you want to aggregate using the multi-select dropdown
- View combined metrics including total visitors, top pages, countries, and referrers
Note: Visitor counts are approximate when aggregating, as the same visitor may be counted across multiple projects. The system uses privacy-preserving hashing that may result in slight over-counting.
Error Tracking
The SDK automatically tracks JavaScript errors, 404 page errors, and API failures without any additional configuration. Error tracking helps you identify and fix issues affecting your users.
Automatic Error Types:
- JavaScript Errors - Uncaught exceptions and unhandled promise rejections
- 404 Errors - Failed fetch requests returning 404 status codes
- API Failures - Network errors and failed API requests
Privacy Note: Error messages and stack traces are automatically sanitized to remove potential personally identifiable information (PII) before being stored. The system limits error tracking to 10 errors per minute per visitor to prevent abuse.
View error analytics in your dashboard:
- Error summary by type (JS errors, 404s, API failures)
- Top error messages and their frequency
- Errors by page path to identify problematic routes
- Error timeline to track trends over time
Funnels
Track user journeys through your application with lightweight, cookie-free funnels. Define a series of steps and see how many users progress through each step and where they drop off.
Creating a funnel:
- Go to your project settings and scroll to the "Funnels" section
- Click "Create Funnel"
- Enter a name for your funnel (e.g., "Signup Funnel")
- Add at least 2 steps, each with:
- A step name (e.g., "Landing Page", "Signup Form", "Checkout")
- A step type:
Path(regex pattern) orEvent(event name) - A pattern to match (regex for paths, event name for events)
- Save the funnel
// Example funnel steps:
Step 1: Landing Page
Type: Path
Pattern: ^/$
Step 2: Signup Clicked
Type: Event
Pattern: signup_clicked
Step 3: Signup Completed
Type: Path
Pattern: ^/signup/complete$Funnel features:
- View visitor counts at each step
- See dropoff percentages between steps
- Track funnel performance over time
- Cookie-free tracking using privacy-preserving visitor hashing
Note: Funnels track unique visitors who reach each step. Since tracking is cookie-free, the same user may be counted multiple times if they visit on different days or from different devices.
Goals and Conversions
Set up goals to track important user actions and measure conversion rates. Goals can be based on page paths (using regex patterns) or custom events.
Creating a goal:
- Go to your project settings and find the "Goals" section
- Click "Create Goal"
- Enter a goal name (e.g., "Purchase Completed")
- Choose the goal type:
- Path-based: Match page views using a regex pattern (e.g.,
^/checkout/success$) - Event-based: Match custom events by name (e.g.,
purchase_completed)
- Path-based: Match page views using a regex pattern (e.g.,
- Enter the pattern and save
View goal performance in your dashboard:
- Total goal completions
- Unique visitors who completed the goal
- Conversion rate (percentage of visitors who completed the goal)
- Goal completion trends over time
Alerts and Notifications
Set up alerts to be notified when important metrics change. Currently supports traffic spike and drop alerts.
Creating an alert:
- Go to your project settings and find the "Alerts" section
- Click "Create Alert"
- Enter an alert name and select the alert type
- Set the threshold percentage (e.g., 20% increase or decrease)
- Enable or disable the alert
Notifications appear in the notification bell icon in the top navigation. You'll be notified when traffic spikes or drops by the specified percentage compared to the previous period.
Data Retention Controls
Configure how long analytics data is retained for each project. This helps you manage storage costs and comply with data retention policies.
Setting data retention:
- Go to your project settings
- Find the "Data Retention" section
- Select a retention period:
- Forever (default) - Keep all data indefinitely
- 30 days - Delete data older than 30 days
- 90 days - Delete data older than 90 days
- 365 days (1 year) - Delete data older than 1 year
- 730 days (2 years) - Delete data older than 2 years
- Click "Save Retention Setting"
Warning: Data deletion is permanent and cannot be undone. Once data is deleted, it cannot be recovered. Choose your retention period carefully.
Advanced Usage
Learn about advanced features and integration patterns for complex applications.
Single Page Application (SPA) Routing
When data-autotrack="true", the SDK automatically tracks route changes in SPAs by intercepting history.pushState and history.replaceState.
// The SDK automatically handles these:
history.pushState({}, '', '/new-page');
history.replaceState({}, '', '/updated-page');
window.addEventListener('popstate', () => {
// Also tracked automatically
});
// For manual tracking in frameworks:
// React Router
useEffect(() => {
if (window.analyticsSaas) {
window.analyticsSaas.page();
}
}, [location]);
// Vue Router
router.afterEach(() => {
if (window.analyticsSaas) {
window.analyticsSaas.page();
}
});Engagement Tracking
The SDK automatically tracks user engagement through:
- Heartbeat events - Sent at regular intervals (default: 15 seconds) while the page is active
- Visibility change events - Tracked when the user switches tabs or minimizes the browser
- Time on page - Calculated from heartbeat and visibility events
Adjust the heartbeat interval with data-heartbeat-ms to balance granularity and network usage.
UTM Parameter Tracking
UTM parameters are automatically captured from the URL and included in page view events:
utm_sourceutm_mediumutm_campaignutm_termutm_content
Example URL: https://example.com/page?utm_source=google&utm_campaign=summer_sale
These parameters are automatically extracted and sent with the page view event.
Custom Event Properties
Event properties can include any JSON-serializable data. Use descriptive property names and consistent value types:
// Good: Descriptive properties
analyticsSaas.track('video_play', {
video_id: 'abc123',
video_title: 'Introduction Video',
video_duration: 120,
video_position: 45
});
// Good: Nested objects for complex data
analyticsSaas.track('form_submit', {
form_name: 'contact',
fields: {
name: 'John Doe',
email: 'john@example.com'
},
submission_time: 2.5
});
// Avoid: Inconsistent types or unclear names
analyticsSaas.track('event', {
data: 'value', // Too generic
num: '123' // String instead of number
});Integration with Other Tools
Metricly can be used alongside other analytics tools. The SDK is lightweight and won't interfere with other tracking scripts.
// Track to multiple analytics tools
function trackEvent(name, props) {
// Metricly
if (window.analyticsSaas) {
window.analyticsSaas.track(name, props);
}
// Google Analytics (if using)
if (window.gtag) {
window.gtag('event', name, props);
}
// Other tools...
}
// Use in your application
trackEvent('button_click', { button: 'signup' });Error Tracking (Automatic)
The SDK automatically tracks JavaScript errors, 404s, and API failures. No additional code is required. Errors are tracked with rate limiting (max 10 errors per minute) to prevent abuse.
Error tracking is enabled by default. You can view error analytics in your dashboard under the "Errors" section. Error messages are automatically sanitized to remove potential PII before storage.
Tracked automatically:
- Uncaught JavaScript exceptions
- Unhandled promise rejections
- 404 errors from failed fetch requests
- Network errors and API failures
Troubleshooting
Common issues and solutions when integrating Metricly.
Events Not Appearing in Dashboard
If events aren't showing up in your dashboard, check the following:
- Verify your API key is correct in the script tag
- Check the browser console for JavaScript errors
- Ensure the SDK script is loading (check Network tab in DevTools)
- Verify
window.analyticsSaasexists in the console - Check if Do Not Track is enabled in the browser
- Verify consent is granted if
data-consent-required="true" - Check the Network tab to see if requests are being sent to the collect endpoint
SDK Not Loading
If the SDK isn't loading:
- Verify the script src URL is correct and accessible
- Check for Content Security Policy (CSP) restrictions
- Ensure the script tag is placed before any code that uses
window.analyticsSaas - Remove
deferattribute if you need immediate access (not recommended) - Check browser console for loading errors
SPA Routes Not Tracking
If route changes in your SPA aren't being tracked:
- Ensure
data-autotrack="true"is set - For some frameworks, you may need to manually call
analyticsSaas.page()on route changes - Check if your router uses standard
history.pushStateor a custom implementation - Verify the SDK loaded before your router initializes
CORS Errors
If you see CORS errors in the console:
- Verify the
data-apiURL is correct - Ensure the API endpoint allows requests from your domain
- Check server CORS configuration
- The SDK uses
credentials: 'omit'to avoid CORS issues
Debugging Tips
Enable debugging to see what's happening:
// Check if SDK is loaded
console.log('Metricly:', window.analyticsSaas);
// Check configuration
console.log('Config:', window.analyticsSaas._config);
// Manually trigger a page view
window.analyticsSaas.page();
// Manually trigger an event
window.analyticsSaas.track('test_event', { debug: true });
// Check consent status
console.log('Consent:', window.analyticsSaas._config.consentRequired);Open the browser's Network tab and filter for requests to your analytics endpoint to see if events are being sent.