SDK Reference

Next.js Integration

Track user behavior in your Next.js application with automatic page view tracking and custom events.

Quick Start

Add the Phi Analytics tracker to your _app.tsx or _app.js file using Next.js's Script component:

TypeScript
import type { AppProps } from 'next/app';
import Script from 'next/script';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      {/* Phi Analytics Tracker */}
      <Script
        src="https://phi.llc/tracker.js"
        data-id="your-site-id"
        strategy="afterInteractive"
      />
      <Component {...pageProps} />
    </>
  );
}

Local Development

By default, the tracker ignores localhost traffic. To enable tracking during development, add the data-allow-localhost attribute:

TypeScript
<Script
  src="/tracker.js"
  data-id="phi_6adc65a9d96"
  strategy="afterInteractive"
  data-allow-localhost="true"
/>

Development Setup

For local development, use /tracker.js to load the script from your public directory instead of the production CDN.

Automatic SPA Tracking

Phi Analytics automatically tracks Next.js client-side navigation (App Router and Pages Router) without additional configuration. Every route change triggers a new pageview event.

TypeScript
// No additional code needed!
// The tracker automatically listens to:
// - history.pushState()
// - history.replaceState()
// - popstate events

// All Next.js Link clicks and router.push() calls
// are automatically tracked

Track Custom Events

Track button clicks, form submissions, or any user interaction:

TypeScript
'use client'; // For App Router components

import { useEffect } from 'react';

export default function SignupButton() {
  const handleClick = () => {
    // Track the event
    if (typeof window !== 'undefined' && window.phi) {
      window.phi('ButtonClicked', {
        button: 'signup',
        location: 'hero-section'
      });
    }
  };

  return (
    <button onClick={handleClick}>
      Sign Up
    </button>
  );
}

TypeScript Support

Add type definitions for the Phi Analytics global function:

TypeScript
// types/phi.d.ts
declare global {
  interface Window {
    phi?: (eventName: string, customData?: Record<string, any>) => void;
  }
}

export {};

App Router & Server Components

The tracker script should be added to your root layout. For tracking custom events in Server Components, extract the logic into a Client Component:

TypeScript
// app/layout.tsx (Server Component)
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Script
          src="https://phi.llc/tracker.js"
          data-id="your-site-id"
          strategy="afterInteractive"
        />
        {children}
      </body>
    </html>
  );
}

// components/TrackingButton.tsx (Client Component)
'use client';

export function TrackingButton() {
  const track = () => {
    window.phi?.('CustomEvent', { action: 'click' });
  };
  
  return <button onClick={track}>Track Me</button>;
}

Environment Variables

Store your site ID in environment variables for better security and flexibility:

Bash
# .env.local
NEXT_PUBLIC_PHI_SITE_ID=phi_6adc65a9d96
TypeScript
// _app.tsx or app/layout.tsx
<Script
  src="https://phi.llc/tracker.js"
  data-id={process.env.NEXT_PUBLIC_PHI_SITE_ID}
  strategy="afterInteractive"
/>

Best Practices

  • Use strategy="afterInteractive" for optimal performance.
  • Add the Script component in _app.tsx (Pages Router) or root layout.tsx (App Router).
  • Always check for typeof window !== 'undefined' before calling window.phi.
  • Use environment variables for your site ID to easily switch between development and production.
  • For App Router, mark components that use window.phi with 'use client'.

Troubleshooting

  • Not seeing data? Check your browser console for errors and ensure your site ID is correct.
  • 404 errors? Make sure you've registered your domain in Phi OS and the RLS policies allow public site lookups.
  • Localhost not tracking? Add data-allow-localhost="true" to the Script component.