Documentation
Complete guide to integrating, configuring, and getting the most out of MetricTrail.
Overview
MetricTrail is a developer-first product intelligence platform built for real-time performance. It connects real visitor journeys, automatic React Error Boundary diagnostics, Core Web Vitals, and AI-driven insights into a single ultra-fast dashboard.
Quick Start (5 minutes)
The fastest way to start tracking is the zero-code HTML script tag. It auto-captures pageviews, Web Vitals, clicks, OS, browser, device type, and referrer without any additional configuration.
Step 1 – Create a Project
After signing up, navigate to Settings → Projects → New Project. Copy your Project ID and Write Key.
Step 2 – Add the Script
<!-- MetricTrail Zero-Code Auto-Capture -->
<script
defer
src="https://api.metrictrail.io/v1/metrictrail.min.js"
data-project="<YOUR_PROJECT_ID>"
data-write-key="<YOUR_WRITE_KEY>"
data-auto-vitals="true"
data-auto-clicks="true"
data-auto-context="true"
></script>Step 3 – Verify
Open the Integrations tab in your dashboard, click "Test & Verify in Realtime", and browse your site. Within seconds you'll see live events appear in the stream.
Architecture & Security
MetricTrail uses a write-key / read-key separation model. Write keys are safe to embed in client-side code — they can only insert events. Read keys are secret and must never be exposed publicly.
Client-safe. Can only POST events. Embed in SDKs & script tags.
Server-side only. Grants access to query APIs. Never expose publicly.
Choosing the Right SDKOverview
MetricTrail provides specialized SDKs for different environments. Pick the option that matches your tech stack:
Best for static websites, Webflow, WordPress, and marketing landing pages. Drop one script tag in <head>.
Best for Next.js App Router and React SPAs. Includes hooks, MetricTrailProvider, and Error Boundaries.
Best for custom JavaScript apps, Vue, Angular, or Node.js. Pure typed client with offline retry storage.
HTML Script TagZero-code
Drop a single <script> tag into your HTML <head> — no build step, no npm install. Automatically captures pageviews (including SPA route changes), clicks, Core Web Vitals, and acquisition context.
<script
defer
src="https://metrictrail.io/tag.js"
data-project="<PROJECT_ID>"
data-write-key="<WRITE_KEY>"
data-user-id="user@example.com"
></script>Attributes
| Attribute | Required | Description |
|---|---|---|
| data-project | Yes | Project ID |
| data-write-key | Yes | Project write key for ingestion auth |
| data-user-id | No | Pre-identify the user (email or user_id) directly on tag load |
| data-auto-vitals | No (default true) | Set to "false" to disable automatic Core Web Vitals capture |
| data-auto-clicks | No (default true) | Set to "false" to disable automatic click tracking on links, buttons, and [role="button"] elements |
| data-auto-context | No (default true) | Set to "false" to disable automatic browser/OS/device/UTM/referrer enrichment |
React / Next.jsBrowser SDK
Type-safe browser tracker for React and Next.js applications. Automatically enriches OS, browser, device type, UTMs, and Web Vitals with offline durable storage.
npm install @metrictrail/trackerimport { MetricTrail } from '@metrictrail/tracker';
export const tracker = new MetricTrail({
projectId: '<PROJECT_ID>',
writeKey: '<WRITE_KEY>',
storage: 'local', // Preserves session & queued events across page reloads
autoContext: true // Auto-detects browser, OS, device type & referrer
});
// Identify logged-in users
tracker.identify('usr_9842', { plan: 'pro', team_size: 12 });
// Track page navigation & core web vitals
tracker.page(window.location.pathname);
tracker.webVital('LCP', 1850, 'good');
// Track business events
await tracker.track('checkout_completed', {
order_id: 'ord_541',
amount: 249.00,
currency: 'USD'
});Node.jsServer SDK
High-throughput Node.js SDK (v20+) with crash-safe FIFO queue, non-blocking batch flushing, and structured retries.
npm install @metrictrail/nodeimport { MetricTrail, FileStore } from '@metrictrail/node';
const client = await MetricTrail.create({
projectId: '<PROJECT_ID>',
writeKey: '<WRITE_KEY>',
store: new FileStore('./.metrictrail-queue.json'), // Crash-safe persistence
maxRetries: 3
});
// Track backend domain events
await client.track('subscription_upgraded', {
user_id: 'usr_9842',
previous_plan: 'starter',
new_plan: 'enterprise',
mrr_delta: 450
});
// Flush before process exit or serverless shutdown
await client.shutdown();PythonServer SDK
Thread-safe Python 3.9+ client with optional durable FIFO FileStore and zero external heavyweight dependencies.
pip install metrictrailfrom metrictrail import Client, FileStore
client = Client(
project_id="<PROJECT_ID>",
write_key="<WRITE_KEY>",
store=FileStore("./metrictrail_queue.json"), # Optional FIFO queue
max_retries=3,
)
# Queue custom telemetry events
client.track(
"invoice_generated",
{
"user_id": "usr_9842",
"amount": 1250.00,
"currency": "BRL",
"auto_debit": True,
}
)
# Flush pending events to collector
client.flush()GoServer SDK
High-performance Go SDK (Go 1.23+) with context cancellation, atomic durable file store, and zero memory leaks.
go get github.com/barba-software/metrictrail-gopackage main
import (
"context"
"time"
"github.com/barba-software/metrictrail-go"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := metrictrail.New(ctx, metrictrail.Options{
ProjectID: "<PROJECT_ID>",
WriteKey: "<WRITE_KEY>",
})
if err != nil {
panic(err)
}
client.Track(ctx, "api_request_processed", map[string]any{
"route": "/v1/payments",
"duration_ms": 42,
"status_code": 200,
})
_ = client.Shutdown(ctx)
}Android (Kotlin)Coming soon
The Android SDK is implemented and tested but not yet published to Maven Central. Email contact@metrictrail.io for early access.
iOS (Swift)Coming soon
The iOS SDK is implemented and tested but not yet available as a standalone Swift package. Email contact@metrictrail.io for early access.
React NativeCross-platform
React Native client for iOS & Android with AsyncStorage queue retention and lifecycle background handlers.
npm install @metrictrail/react-native @react-native-async-storage/async-storageimport { MetricTrail } from '@metrictrail/react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Platform } from 'react-native';
export const tracker = await MetricTrail.create({
projectId: '<PROJECT_ID>',
writeKey: '<WRITE_KEY>',
platform: Platform.OS === 'ios' ? 'ios' : 'android',
storage: AsyncStorage
});
await tracker.track('screen_viewed', { screen: 'CheckoutModal' });Custom Events
Track any business action with a name and a free-form properties object. All events are automatically enriched with timestamp, session ID, project ID, and client context.
// Browser SDK
await tracker.track('purchase_completed', {
plan: 'enterprise',
mrr: 499,
currency: 'USD',
seats: 10
});
// Node.js SDK
await client.track('invoice_paid', {
invoice_id: 'inv_1234',
amount: 1999.00,
customer_id: 'cus_abc123'
});User Identification
Attach a persistent identity to a session so you can track the full journey of a logged-in user across pages and devices.
// Call identify() after user logs in
tracker.identify('usr_9842', {
email: 'alex@example.com',
plan: 'pro',
team_size: 12,
company: 'Acme Corp'
});
// All subsequent track() calls will include user_id: 'usr_9842'
await tracker.track('dashboard_viewed', { section: 'traffic' });Core Web VitalsAuto
With data-auto-vitals="true" or autoContext: true, MetricTrail automatically captures and classifies all Core Web Vitals: LCP, INP, CLS, FCP, and TTFB, along with their Google-defined rating (good / needs-improvement / poor).
// Manual override (e.g. from your own PerformanceObserver)
tracker.webVital('LCP', 1850, 'good');
tracker.webVital('INP', 95, 'good');
tracker.webVital('CLS', 0.02, 'good');Error MonitoringAuto
MetricTrail automatically captures unhandled errors and React Error Boundary exceptions, including stack traces, component trees, and session context. No additional setup is required when using the browser SDK.
// Manual error capture
tracker.error(new Error('Payment gateway timeout'), {
gateway: 'stripe',
order_id: 'ord_541',
retry_count: 3
});Session Explorer
The Session Explorer lets you inspect individual user sessions end-to-end: every page visited, events fired, errors triggered, Web Vitals captured, and device/location context. Filter by OS, browser, acquisition source, session duration, and more.
Conversion Funnels
Define multi-step conversion funnels using any event names. MetricTrail calculates drop-off rates at each step and compares cohorts by time range, acquisition source, device type, and custom properties.
SEO Fix (JSON-LD)Opt-in
The SEO auditor checks your highest-traffic pages daily (title, meta description, structured data, H1, canonical, image alt coverage) and scores each one. For issues it can fix with AI, it writes a suggested title, meta description, and JSON-LD — visible in the dashboard's SEO tab.
// Call once the page has settled — e.g. after your first page() call,
// or on every route change in an SPA. Safe to call on every page: it's a
// no-op if there's no approved fix for the current path.
await tracker.page();
await tracker.applySEOFixes();applySEOFixes() only ever injects JSON-LD (a <script type="application/ld+json" data-metrictrail-jsonld="1"> tag appended to <head>) — it never rewrites your <title> or meta description, since a client-side rewrite of those isn't reliably seen by crawlers that don't execute JavaScript. Approved title/meta suggestions stay text-only in the dashboard; apply those to your page source by hand.
To verify it worked: open DevTools → Elements (not "View Page Source", which shows the static HTML before this script runs) and look for the data-metrictrail-jsonld attribute inside <head>. The next audit cycle will also pick it up and flip that page's "structured data" check to passing.
What is MCP?Beta
MetricTrail ships a Model Context Protocol (MCP) server that exposes your analytics data to AI agents and coding assistants. With MCP, tools like Cursor, Claude Desktop, and Antigravity can query your sessions, traffic, and events in natural language.
Setup & Config
Cursor / VS Code
Add the following to your Cursor settings or .cursor/mcp.json:
{
"mcpServers": {
"metrictrail": {
"command": "npx",
"args": ["-y", "@metrictrail/mcp-server"],
"env": {
"METRICTRAIL_API_URL": "https://api.metrictrail.io",
"METRICTRAIL_READ_KEY": "<YOUR_READ_KEY>",
"METRICTRAIL_PROJECT_ID": "<YOUR_PROJECT_ID>"
}
}
}
}Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json on macOS:
{
"mcpServers": {
"metrictrail": {
"command": "npx",
"args": ["-y", "@metrictrail/mcp-server"],
"env": {
"METRICTRAIL_API_URL": "https://api.metrictrail.io",
"METRICTRAIL_READ_KEY": "<YOUR_READ_KEY>",
"METRICTRAIL_PROJECT_ID": "<YOUR_PROJECT_ID>"
}
}
}
}Antigravity (AGY)
{
"mcpServers": {
"metrictrail": {
"command": "npx",
"args": ["-y", "@metrictrail/mcp-server"],
"env": {
"METRICTRAIL_API_URL": "https://api.metrictrail.io",
"METRICTRAIL_READ_KEY": "<YOUR_READ_KEY>",
"METRICTRAIL_PROJECT_ID": "<YOUR_PROJECT_ID>"
}
}
}
}Available Tools
The MCP server exposes the following tools to AI agents:
get_traffic_overviewReturns pageviews, sessions, visitors, and bounce rate for a date range.
get_top_pagesLists the most visited pages ranked by session count or pageviews.
get_session_listReturns filtered sessions with full event trails.
get_error_eventsRetrieves JS errors, uncaught exceptions, and Error Boundary hits.
get_web_vitalsAggregates LCP, INP, CLS, FCP, TTFB across your session window.
get_custom_eventsQueries custom track() events with optional property filters.
get_audience_breakdownReturns OS, browser, device, country, and referrer distribution.
run_ai_analysisTriggers AI root-cause analysis on a specific metric or error spike.
Query Examples
Once configured, ask your AI assistant natural language questions about your analytics: