Next.js

npm install @x3growth/sdk
// app/layout.tsx
import { X3Analytics } from "@x3growth/sdk/next";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <X3Analytics publishableKey={process.env.NEXT_PUBLIC_X3_KEY!} host="/n3" />
      </body>
    </html>
  );
}

<X3Analytics> starts the SDK script from the server-rendered HTML, before hydration, so a visitor who leaves within the first seconds is still counted; next/script (afterInteractive) loads the same script as a fallback. It does not use useSearchParams, so static pages stay static. App Router and Pages Router navigations are captured through the History API.

Props

PropMeaning
publishableKeypk_3x_…
hostAPI origin or proxy path. Use /n3 with the proxy route; without a proxy the API origin, e.g. https://api.3x.example
configClient config fetched on the server with fetchClientConfig() – the tracker starts without a round trip
nonceCSP nonce for the inline loader and the scripts; on dynamically rendered pages Next.js applies the request nonce to the next/script fallback automatically
build"full" (default, x3.full.js with every plugin) or "core" (x3.js, plugins load lazily)
consentInitial consent (pending, granted, denied) – rendered as data-consent
debugExpose window.__x3 and log diagnostics
hashRoutingTreat #/route changes as pageviews
strategy"early" (default: inline loader before hydration, next/script as fallback) or "afterInteractive" (only next/script)

The component renders an inline <script id="x3-early"> with the queue stub (exported as QUEUE_STUB), the server-fetched config (serialized with inlineJson(), which escapes < so the payload cannot close the tag) and a loader that appends the async SDK script (earlyLoader()), plus the same stub and the SDK script as two next/script tags (afterInteractive) – the SDK ignores the second load. Use a nonce rather than a hash for the inline part – its content changes with the config. With a Content Security Policy that blocks inline scripts, pass the nonce (the loader hands it on to the SDK script) or set strategy="afterInteractive".

// app/layout.tsx – config fetched on the server (cached by Next for 60 s)
import { X3Analytics, fetchClientConfig } from "@x3growth/sdk/next";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const config = await fetchClientConfig({ publishableKey: process.env.NEXT_PUBLIC_X3_KEY!, apiOrigin: process.env.X3_API_ORIGIN! });
  return (
    <html lang="en">
      <body>
        {children}
        <X3Analytics publishableKey={process.env.NEXT_PUBLIC_X3_KEY!} host="/n3" config={config ?? undefined} />
      </body>
    </html>
  );
}

Pages Router

// pages/_app.tsx
import type { AppProps } from "next/app";
import { X3Analytics } from "@x3growth/sdk/next";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <X3Analytics publishableKey={process.env.NEXT_PUBLIC_X3_KEY!} host="/n3" />
    </>
  );
}

Events from components

<X3Analytics> loads the script-tag build, so components talk to window.x3. A tiny helper queues calls until the script has loaded:

// lib/x3.ts
type X3Command = (...args: unknown[]) => void;

export function x3(...args: unknown[]): void {
  if (typeof window === "undefined") return;
  const w = window as unknown as { x3?: X3Command; x3q?: unknown[][] };
  w.x3 ??= (...queued: unknown[]) => void (w.x3q ??= []).push(queued);
  w.x3(...args);
}
"use client";
import { x3 } from "@/lib/x3";

export function SignupButton() {
  return <button onClick={() => x3("track", "signup_click", { plan: "pro" })}>Start trial</button>;
}

Methods that return something (getIds(), identify(), conversion()) are available as window.x3.getIds() etc. once the script has loaded. Prefer the npm package everywhere instead? Use <X3Provider> from @x3growth/sdk/react (React) – then import { track } from "@x3growth/sdk" talks to the same tracker. Do not combine both on one page.

Server actions and route handlers

Leads, conversions and server-side events need a secret key and therefore run on the server: Server helper. Pass getIds().sessionId from the browser so 3x can attach them to the visit.

Visitor id behind the proxy

createX3ProxyHandler (route app/n3/[...path]/route.ts) keeps the consented visitor id x3_vid as an HttpOnly first-party cookie: it answers POST /n3/v1/id after consent and injects the id into batches that carry consent. Without the handler (other proxies, direct API host) the SDK stores x3_vid as a JavaScript cookie instead. Before consent nothing is stored either way – Consent and CMPs.

Middleware / proxy.ts

If your app has middleware.ts (or proxy.ts), exclude the proxy path from its matcher so tracking requests are not rewritten or localized:

export const config = { matcher: ["/((?!n3|_next|api|.*\\..*).*)"] };

Full recipes: Next.js App Router, Next.js Pages Router.