Skip to main content
Add PostMetric to your React application in minutes.

Installation

Step 1: Add the tracking script

Add the tracking script to your public/index.html:
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://your-domain.com/api/track.js?site=YOUR_TRACKING_CODE"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
Or add it dynamically in your React app:
import { useEffect } from "react";

function App() {
  useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://your-domain.com/api/track.js?site=YOUR_TRACKING_CODE";
    script.async = true;
    document.head.appendChild(script);

    return () => {
      document.head.removeChild(script);
    };
  }, []);

  return <div>Your app</div>;
}
Replace YOUR_TRACKING_CODE with your tracking code from the dashboard.

Step 2: Verify installation

  1. Start your development server
  2. Visit your website
  3. Check your PostMetric dashboard - you should see your visit

Track custom goals

Track custom goals in your React components:
function Button() {
  const handleClick = () => {
    if (window.postMetric) {
      window.postMetric("track", "goal", {
        event: "button_click",
        value: 0,
      });
    }
  };

  return <button onClick={handleClick}>Click me</button>;
}

User identification

Identify users when they log in:
function LoginButton() {
  const handleLogin = async () => {
    const user = await login();

    if (window.postMetric) {
      window.postMetric("identify", {
        userId: user.id,
        email: user.email,
        name: user.name,
      });
    }
  };

  return <button onClick={handleLogin}>Login</button>;
}

React Router integration

The tracking script automatically tracks React Router navigation. No additional setup needed!

TypeScript types

Add TypeScript types for better type safety:
// types/PostMetric.d.ts
declare global {
  interface Window {
    PostMetric: (
      method: "track" | "identify",
      type: "pageview" | "goal",
      data?: {
        event?: string;
        value?: number;
        userId?: string;
        email?: string;
        name?: string;
      }
    ) => void;
  }
}

export {};

Next steps

Track custom goals

Learn how to track custom user actions