← Back to SSMetrics

Next.js: page views on every navigation

With <Link>, the page doesn’t reload, so the SSMetrics script only fires once. Add the steps below in your Next.js app so every route change sends a page_view.

Step 1: Create the component

In your app, create components/TrackPageView.tsx:

"use client";

import { usePathname } from "next/navigation";
import { useEffect } from "react";

export function TrackPageView() {
  const pathname = usePathname();

  useEffect(() => {
    if (!pathname || typeof window === "undefined") return;
    const script = document.querySelector('script[data-id][src*="t.js"]');
    const trackingId = process.env.NEXT_PUBLIC_ANALYTICS_ID || script?.getAttribute("data-id") || "";
    if (!trackingId) return;
    if (typeof (window as unknown as { track?: (e: string, p?: string, id?: string) => void }).track === "function") {
      (window as unknown as { track: (e: string, p?: string, id?: string) => void }).track("page_view", pathname, trackingId);
    }
  }, [pathname]);

  return null;
}

Step 2: Mount in template (not layout)

Create or edit app/template.tsx. Use template, not layout — template re-mounts on every navigation so the effect runs when you click a <Link>.

import { TrackPageView } from "@/components/TrackPageView";

export default function Template({ children }: { children: React.ReactNode }) {
  return (
    <>
      <TrackPageView />
      {children}
    </>
  );
}

Step 3: Check window.track

Open your app in the browser. In the console, run: typeof window.track. If it says "undefined", the script from sandrobuilds.com doesn’t have window.track yet — ensure the latest t.js is deployed, then hard-refresh.

Step 4: Test

Add console.log("Analytics page_view", pathname); inside the effect. Click a <Link> to another page. If you see the log → it’s working. If not → the component is in layout instead of template. In DevTools → Network, filter by “track”; you should see a POST to sandrobuilds.com/api/track on each navigation.

Don’t build your own track() or /api/track route. Use only window.track from the script — that’s what sends events to SSMetrics.

powered by sandrobuilds.com