Add analytics to Next.js with Tracwell

Track page views and custom events in Next.js. Learn where to initialize Tracwell, avoid duplicate tracking, and verify your installation.

Guide reviewed

Initialize Tracwell

Keep initialization in a small Client Component and render it from the root layout. The rest of the layout can remain a Server Component.

pnpm add tracwell
components/tracwell-analytics.tsx
"use client";

import { useEffect } from "react";
import { createTracwell, type TracwellClient } from "tracwell";

let client: TracwellClient | undefined;

/** Undefined during server rendering and before the first effect runs. */
export function getAnalytics() {
  return client;
}

export function TracwellAnalytics() {
  useEffect(() => {
    client ??= createTracwell({
      collectionMode: "private",
      projectKey: "tw_live_...",
    });
  }, []);

  return null;
}

// Render <TracwellAnalytics /> once inside app/layout.tsx.
// Pages Router apps can render it from pages/_app.tsx instead.

Replace tw_live_... with your project key from Settings → Website → Tracking setup.

Do not call page() from usePathname. Next.js link and router navigation update browser history, which the SDK already observes.

Track an event

Call track() after a product action succeeds, from wherever that action completes:

Any Client Component
"use client";

import { getAnalytics } from "@/components/tracwell-analytics";

getAnalytics()?.track("signup_completed", { plan: "starter" });

The optional call (?.) skips tracking whenever the client is not available yet, such as during server rendering. Continue with the custom events guide for naming, property limits, and verification.

Track navigation without duplicate page views

Tracwell records the initial page view and observes standard History API navigation, including pushState, replaceState, and back or forward navigation. Do not add another page-view call for the same route change. Hash-only changes are ignored; call page() only for meaningful page changes that do not update browser history.

Verify the installation

  1. Copy the project key from Settings → Website → Tracking setup. To test locally, add a separate website whose URL is your local address, such as http://localhost:3000; the port must match.
  2. Open the website with the SDK installed. If consent is required, grant it through your site’s consent flow before expecting collection.
  3. Confirm the initial page view in Tracwell’s Realtime report, then use a normal internal link and check that the destination is recorded once.
  4. Complete the custom action and check its name and properties in Events → live stream. If nothing arrives, follow the troubleshooting checklist.
Troubleshoot missing events

Turn events into conversion reports

Use successful product actions as goal matches or steps in an ordered funnel. Verified purchases and refunds must come from your backend; a browser checkout click is not payment confirmation.