Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/vemetric/vemetric/llms.txt

Use this file to discover all available pages before exploring further.

The Vemetric React SDK (@vemetric/react) provides a seamless integration for React applications with automatic pageview tracking, TypeScript support, and React hooks.

Installation

Install the package using your preferred package manager:
npm install @vemetric/react

Setup

Basic Setup

Add the VemetricScript component to your application root:
import { VemetricScript } from '@vemetric/react';
import { createRoot } from 'react-dom/client';

createRoot(document.getElementById('root')!).render(
  <>
    <VemetricScript
      host="https://hub.yourdomain.com"
      token="your-project-token"
    />
    <App />
  </>
);

With React Router

For single-page applications using React Router:
import { VemetricScript } from '@vemetric/react';
import { BrowserRouter } from 'react-router-dom';

function Root() {
  return (
    <BrowserRouter>
      <VemetricScript
        host="https://hub.yourdomain.com"
        token="your-project-token"
      />
      <App />
    </BrowserRouter>
  );
}

With Next.js

For Next.js applications, add the script in your root layout or _app.tsx:
import { VemetricScript } from '@vemetric/react';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <VemetricScript
          host={process.env.NEXT_PUBLIC_VEMETRIC_HOST}
          token={process.env.NEXT_PUBLIC_VEMETRIC_TOKEN}
        />
        {children}
      </body>
    </html>
  );
}

VemetricScript Props

host
string
required
The URL of your Vemetric hub instanceExample: https://hub.yourdomain.com
token
string
required
Your project token from the Vemetric dashboard
maskPaths
string[]
Array of URL patterns to mask in analytics (supports wildcards)
<VemetricScript
  host="https://hub.yourdomain.com"
  token="your-token"
  maskPaths={[
    '/p/*',
    '/settings',
    '/admin/*'
  ]}
/>
allowCookies
boolean
default:"true"
Whether to allow cookies for user tracking

Usage

Track Events

Import the vemetric singleton to track events anywhere in your application:
import { vemetric } from '@vemetric/react';

function Button() {
  const handleClick = () => {
    vemetric.trackEvent('ButtonClicked');
  };
  
  return <button onClick={handleClick}>Click Me</button>;
}

Track Events with Data

import { vemetric } from '@vemetric/react';

function ProductCard({ product }) {
  const handleAddToCart = () => {
    vemetric.trackEvent('AddedToCart', {
      eventData: {
        productId: product.id,
        productName: product.name,
        price: product.price,
        category: product.category
      }
    });
  };
  
  return (
    <div>
      <h3>{product.name}</h3>
      <button onClick={handleAddToCart}>Add to Cart</button>
    </div>
  );
}

User Identification

Identify Authenticated Users

Identify users when they log in to track them across sessions:
import { vemetric } from '@vemetric/react';
import { useEffect } from 'react';

function App() {
  const { user } = useAuth();
  
  useEffect(() => {
    if (user) {
      vemetric.identify({
        identifier: user.id,
        displayName: user.name,
        avatarUrl: user.avatar
      });
    } else {
      vemetric.resetUser();
    }
  }, [user]);
  
  return <div>...</div>;
}

Complete Authentication Example

Here’s a complete example from the Vemetric app source code:
import { vemetric } from '@vemetric/react';
import { useEffect, useRef } from 'react';

function RootLayout() {
  const { data: session, isPending } = useSession();
  const identifiedUserIdRef = useRef<string | null>(null);
  
  useEffect(() => {
    if (isPending) {
      return;
    }
    
    if (session !== null && session.user.id !== identifiedUserIdRef.current) {
      identifiedUserIdRef.current = session.user.id;
      vemetric.identify({
        identifier: session.user.id,
        displayName: session.user.name,
        avatarUrl: session.user.image ?? undefined,
      });
    } else if (session === null && identifiedUserIdRef.current !== null) {
      identifiedUserIdRef.current = null;
      vemetric.resetUser();
    }
  }, [isPending, session]);
  
  return <Outlet />;
}

Advanced Usage

Track with User Property Updates

Combine event tracking with user property updates:
import { vemetric } from '@vemetric/react';

function SettingsPage() {
  const handleThemeChange = (theme: string) => {
    vemetric.trackEvent('ChangeColorMode', {
      eventData: { colorMode: theme },
      userData: {
        set: { colorMode: theme }
      }
    });
  };
  
  return (
    <select onChange={(e) => handleThemeChange(e.target.value)}>
      <option value="light">Light</option>
      <option value="dark">Dark</option>
    </select>
  );
}

User Data Operations

Set or update user properties:
vemetric.identify({
  identifier: user.id,
  data: {
    set: {
      plan: 'premium',
      lastActive: new Date().toISOString()
    }
  }
});

API Reference

vemetric.trackEvent(name, options?)

Track a custom event.
name
string
required
Name of the event to track
options
object
Optional configuration object

vemetric.identify(options)

Identify a user and optionally update their properties.
options
object
required

vemetric.resetUser()

Reset the current user identity. Call this when users log out.

TypeScript Support

The React SDK is written in TypeScript and provides full type definitions:
import { vemetric } from '@vemetric/react';

// Type-safe event tracking
vemetric.trackEvent('Purchase', {
  eventData: {
    orderId: string,
    total: number,
    items: Array<{
      id: string;
      quantity: number;
    }>
  }
});

Privacy Features

Path Masking

Mask sensitive URLs from analytics:
<VemetricScript
  host="https://hub.yourdomain.com"
  token="your-token"
  maskPaths={[
    '/p/*',              // All project pages
    '/p/*/settings',     // Settings pages
    '/admin/*',          // Admin section
    '/invite/*'          // Invite links
  ]}
/>

Cookieless Tracking

Disable cookies for privacy compliance:
<VemetricScript
  host="https://hub.yourdomain.com"
  token="your-token"
  allowCookies={false}
/>

Real-World Examples

SaaS Dashboard

import { vemetric } from '@vemetric/react';

function Dashboard() {
  const handleCreateProject = async (name: string) => {
    const project = await createProject(name);
    
    vemetric.trackEvent('ProjectCreated', {
      eventData: {
        projectId: project.id,
        name: project.name
      },
      userData: {
        set: {
          totalProjects: user.projects.length + 1,
          lastProjectCreated: new Date().toISOString()
        }
      }
    });
  };
  
  return <CreateProjectForm onSubmit={handleCreateProject} />;
}

E-commerce Store

import { vemetric } from '@vemetric/react';

function CheckoutPage() {
  const handlePurchase = async (order) => {
    await processPayment(order);
    
    vemetric.trackEvent('Purchase', {
      eventData: {
        orderId: order.id,
        total: order.total,
        itemCount: order.items.length,
        currency: 'USD'
      },
      userData: {
        set: {
          lastPurchase: new Date().toISOString(),
          totalSpent: user.totalSpent + order.total,
          orderCount: user.orderCount + 1
        }
      }
    });
  };
  
  return <CheckoutForm onComplete={handlePurchase} />;
}

Documentation Site

import { vemetric } from '@vemetric/react';

function DocsPage() {
  const handleLinkClick = (href: string) => {
    vemetric.trackEvent('DocsLinkClicked', {
      eventData: {
        href,
        section: getCurrentSection()
      }
    });
  };
  
  return (
    <a href="/docs/api" onClick={() => handleLinkClick('/docs/api')}>
      API Documentation
    </a>
  );
}

Best Practices

Store your Vemetric host and token in environment variables:
<VemetricScript
  host={import.meta.env.VITE_VEMETRIC_HOST}
  token={import.meta.env.VITE_VEMETRIC_TOKEN}
/>
Use useRef to prevent redundant identification calls:
const identifiedRef = useRef(false);

useEffect(() => {
  if (user && !identifiedRef.current) {
    identifiedRef.current = true;
    vemetric.identify({ identifier: user.id });
  }
}, [user]);
Focus on events that matter for your business:
  • User signups and authentication
  • Feature usage and engagement
  • Conversions and purchases
  • Important user actions
Use clear, descriptive names in PascalCase:
  • ProjectCreated, UserSignup, PaymentCompleted
  • click, action, event1

Next Steps

Tracking Events

Learn event tracking best practices

Node.js SDK

Server-side tracking with Node.js

Configuration

Advanced configuration options

JavaScript SDK

Vanilla JavaScript integration