metrictrail./ docs
Open Console
metrictrail.ioDocumentation

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.

< 4 KB SDKZero bundle bloat
Real-Time EngineMillisecond queries
CookielessNo consent banners
AI InsightsRoot cause analysis

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

html
<!-- 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>
Tip Place the script tag inside <head> for earliest possible execution. The defer attribute ensures it does not block page rendering.

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.

Write Key

Client-safe. Can only POST events. Embed in SDKs & script tags.

Read Key

Server-side only. Grants access to query APIs. Never expose publicly.

Important All event ingestion endpoints support HTTPS only. Data is stored with row-level tenant isolation. No cross-tenant data access is possible.

Choosing the Right SDKOverview

MetricTrail provides specialized SDKs for different environments. Pick the option that matches your tech stack:

Tag HTML (Zero-Code)

Best for static websites, Webflow, WordPress, and marketing landing pages. Drop one script tag in <head>.

React / Next.js (@metrictrail/react)

Best for Next.js App Router and React SPAs. Includes hooks, MetricTrailProvider, and Error Boundaries.

JS / TypeScript (@metrictrail/tracker)

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.

html
<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

AttributeRequiredDescription
data-projectYesProject ID
data-write-keyYesProject write key for ingestion auth
data-user-idNoPre-identify the user (email or user_id) directly on tag load
data-auto-vitalsNo (default true)Set to "false" to disable automatic Core Web Vitals capture
data-auto-clicksNo (default true)Set to "false" to disable automatic click tracking on links, buttons, and [role="button"] elements
data-auto-contextNo (default true)Set to "false" to disable automatic browser/OS/device/UTM/referrer enrichment
Tip The tracker instance is exposed as window.metrictrail — call window.metrictrail.identify(userId) or window.metrictrail.track(name, properties) for custom events alongside the automatic capture. Add data-mt-track="label" to any clickable element to give its auto-captured click event a custom label.

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.

bash
npm install @metrictrail/tracker
typescript
import { 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'
});
Tip For Next.js App Router, initialize the tracker in a Client Component and call tracker.page() inside useEffect on route changes. See the full Next.js App Router guide for the @metrictrail/react Provider, hook, and error boundary API.

Node.jsServer SDK

High-throughput Node.js SDK (v20+) with crash-safe FIFO queue, non-blocking batch flushing, and structured retries.

bash
npm install @metrictrail/node
javascript
import { 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.

bash
pip install metrictrail
python
from 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.

bash
go get github.com/barba-software/metrictrail-go
go
package 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.

bash
npm install @metrictrail/react-native @react-native-async-storage/async-storage
typescript
import { 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.

typescript
// 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'
});
Note Event names must be snake_case strings up to 128 characters. Property values can be strings, numbers, booleans, or ISO 8601 date strings. Nested objects are flattened automatically.

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.

typescript
// 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).

typescript
// Manual override (e.g. from your own PerformanceObserver)
tracker.webVital('LCP', 1850, 'good');
tracker.webVital('INP', 95, 'good');
tracker.webVital('CLS', 0.02, 'good');
LCP
Good: ≤ 2.5s
Poor: > 4.0s
INP
Good: ≤ 200ms
Poor: > 500ms
CLS
Good: ≤ 0.1
Poor: > 0.25

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.

typescript
// 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.

⚠ Clicking "Approve fix" in the dashboard only marks the fix as ready — it does not change your live site by itself. Your site's own code has to call applySEOFixes() (below) for the JSON-LD to actually get injected. Nothing happens automatically until you add this call.
typescript
// 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.

Important The MCP server requires a Read Key with analytics:read scope. It runs as a local stdio process that communicates with the MetricTrail API. Your analytics data never leaves your environment unsolicited.

Setup & Config

Cursor / VS Code

Add the following to your Cursor settings or .cursor/mcp.json:

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:

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>"
      }
    }
  }
}

Antigravity (AGY)

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>"
      }
    }
  }
}

Available Tools

The MCP server exposes the following tools to AI agents:

get_traffic_overview

Returns pageviews, sessions, visitors, and bounce rate for a date range.

get_top_pages

Lists the most visited pages ranked by session count or pageviews.

get_session_list

Returns filtered sessions with full event trails.

get_error_events

Retrieves JS errors, uncaught exceptions, and Error Boundary hits.

get_web_vitals

Aggregates LCP, INP, CLS, FCP, TTFB across your session window.

get_custom_events

Queries custom track() events with optional property filters.

get_audience_breakdown

Returns OS, browser, device, country, and referrer distribution.

run_ai_analysis

Triggers 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:

"What were my top 5 pages last week and their bounce rates?"
"Show me all sessions where users hit a JS error on the checkout page."
"What's my LCP score for mobile visitors from Brazil this month?"
"Find the root cause of the conversion rate drop on September 8th."
Tip Combine tools in one prompt: "Get my traffic overview for last 7 days, then find the sessions with highest error rates, and run AI analysis on the spike."