React / Next.js Integration
Integrate seamlessly into your React or Next.js App Router applications using the standard script tag — no npm package required.
Next.js (App Router)
Add the script to your root layout. All three attributes — data-website-id, data-domain, and data-api-key — are required.
// app/layout.tsx
import Script from "next/script";
export default function RootLayout({ children }) {
return (
<html lang="en">
<head>
<Script
defer
data-website-id="YOUR_WEBSITE_ID"
data-domain="yourdomain.com"
data-api-key="YOUR_API_KEY"
src="https://your-analytics-domain.com/js/script.js"
/>
</head>
<body>{children}</body>
</html>
);
}🚀 Automatic Routing
Our script automatically hooks into the browser's History API. When a user navigates between pages using Next.js <Link> components, pageviews are logged automatically — no extra configuration required!
Tracking Custom Events (Click)
Add a data-ezlytics-goal attribute to any element to track clicks — works in both Server and Client Components since it's a plain HTML attribute.
// Works in Server Components too — no "use client" needed
export default function PricingPage() {
return (
<div>
<button
data-ezlytics-goal="upgrade-clicked"
data-ezlytics-goal-plan="pro"
>
Upgrade to Pro
</button>
</div>
);
}Tracking Custom Events (JavaScript)
If you need to fire an event programmatically (e.g., after an async form submission), use the window.ezlytics function. Make sure to guard against SSR with a typeof window check.
💡 Prefer HTML attributes
For click tracking, data-ezlytics-goal is simpler and works without a Client Component. Use the JS API only when you need to trigger an event from code (e.g., after a fetch completes).
"use client";
export default function CheckoutForm() {
const handleSuccess = async () => {
const res = await submitOrder();
// Fire event after async action completes
if (typeof window !== "undefined" && window.ezlytics) {
window.ezlytics("identify", {
user_id: res.userId,
name: res.name,
plan: "pro",
});
}
};
return <button onClick={handleSuccess}>Complete Order</button>;
}Identifying Users
Associate analytics events with a specific logged-in user using window.ezlytics("identify", ...). Call this after login or on any page where you have the user's session available.
"use client";
import { useEffect } from "react";
import { useSession } from "next-auth/react"; // or your auth library
export function AnalyticsIdentify() {
const { data: session } = useSession();
useEffect(() => {
if (!session?.user || typeof window === "undefined") return;
if (!window.ezlytics) return;
window.ezlytics("identify", {
user_id: session.user.id,
name: session.user.name,
plan: session.user.plan, // any extra keys become metadata
});
}, [session]);
return null;
}Add <AnalyticsIdentify /> to your root layout so it runs on every page after the user logs in.