# Next.js analytics: install the tracking script

Add the script with next/script in the App or Pages Router, type window.supr, identify signed-in users, test on localhost and attribute Stripe or Polar revenue.

Your snippet is in Settings → General of the website (the gear next to its name on the dashboard), with its id and domain filled in. The examples below use `YOUR_WEBSITE_ID` and `yourdomain.com`: replace them with yours.

Load the script with `next/script` in the root layout, so it's on every page. Client-side navigation is tracked automatically.

App Router:

```
// app/layout.tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          defer
          supr-website-id="YOUR_WEBSITE_ID"
          supr-domain="yourdomain.com"
          src="https://supranalytics.app/js/script.js"
        />
      </body>
    </html>
  );
}
```

Pages Router:

```
// pages/_app.tsx
import type { AppProps } from "next/app";
import Script from "next/script";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Script
        defer
        supr-website-id="YOUR_WEBSITE_ID"
        supr-domain="yourdomain.com"
        src="https://supranalytics.app/js/script.js"
      />
      <Component {...pageProps} />
    </>
  );
}
```

## Check it works

Open your website in a normal browser window, then the dashboard: the visit shows up within seconds, and the install card on a new website turns into the dashboard by itself. Nothing after a minute? See [Not seeing any data](https://supranalytics.app/docs/no-data.md).

## Track goals, with TypeScript

Call `window.supr()` from client components, or add a `supr-goal` attribute to a button or link (see [Track custom goals](https://supranalytics.app/docs/custom-goals.md)). Use `?.`: the script loads after the page becomes interactive, and ad blockers can block it.

```
<button onClick={() => window.supr?.("start_trial", { plan: "pro" })}>
  Start free trial
</button>
<a href="/signup" supr-goal="signup">Sign up</a>
```

For TypeScript, declare `window.supr` once, in any file your `tsconfig.json` includes:

`supr.d.ts`:

```ts
export {};

declare global {
  interface Window {
    supr?: {
      (event: "identify", user: { user_id?: string; email?: string; name?: string }): void;
      (goal: string, props?: Record<string, string | number | boolean>): void;
      visitorId?: () => string;
      sessionId?: () => string;
    };
  }
}
```

`visitorId` and `sessionId` are optional because they only exist once the script has loaded: call them as `window.supr?.visitorId?.()`.

## Identify signed-in users

Put a name and email on a visitor with `supr("identify")`, so the live view, journeys and goal alerts show who they are. A component that runs it is often rendered before the script has loaded, so first add this stub to the root layout: it queues calls until the script is ready.

`app/layout.tsx`:

```tsx
<Script id="supr-queue" strategy="beforeInteractive">
  {`window.supr=window.supr||function(){(supr.q=supr.q||[]).push(arguments)}`}
</Script>
```

Then render a small client component wherever you know the signed-in user, such as the layout of your signed-in pages:

app/identify.tsx:

```
"use client";
import { useEffect } from "react";

type User = { id: string; email: string; name?: string };

export function Identify({ id, email, name }: User) {
  useEffect(() => {
    window.supr?.("identify", { user_id: id, email, name });
  }, [id, email, name]);
  return null;
}
```

app/(app)/layout.tsx:

```
import { Identify } from "../identify";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const user = await getCurrentUser(); // from your auth library
  return (
    <>
      {user && <Identify id={user.id} email={user.email} name={user.name} />}
      {children}
    </>
  );
}
```

Calling it again replaces the values, and the visitor's earlier visits stay attached. Names and emails never appear on a public dashboard. More in [User identification](https://supranalytics.app/docs/user-identification.md).

## Test on localhost

Visits from `localhost`, `127.0.0.1` and `.local` addresses are ignored, so `next dev` records nothing. Turn on **Track localhost** in Settings → General to count them (no change to the snippet; turn it off again whenever you like), or add `supr-allow-localhost="true"` to one tag, for example in development only:

`app/layout.tsx`:

```tsx
<Script
  defer
  supr-website-id="YOUR_WEBSITE_ID"
  supr-domain="yourdomain.com"
  src="https://supranalytics.app/js/script.js"
  supr-allow-localhost={process.env.NODE_ENV === "development" ? "true" : undefined}
/>
```

Local addresses are always accepted, so there's no domain to add. Local visits land in the same website as your real ones, though: turn the setting off or remove the attribute when you're done, or point development at a second website (websites are unlimited on every plan).

## Vercel preview deployments

Visits to preview deployments on `*.vercel.app` aren't recorded until you allow them, which keeps test traffic out of your stats.

SuprAnalytics only records visits from your website's domain (Settings → General → Domains), its subdomains and the domains listed under Settings → General → Domains → Additional domains. A page anywhere else gets `403 Hostname not allowed for this website` from `/api/event` (you'll see it in the browser's **Network** tab) and nothing is recorded. That's what stops another website from sending data to yours.

To record visits on `my-app-git-feature-team.vercel.app`, add that full address under Settings → General → Domains → Additional domains (up to 20); the snippet doesn't need to change. Add the whole address, not `vercel.app`, which would accept visits from every website on vercel.app. Or test on your own domain instead, once it's connected and published.

Visits on that address count as different visitors from your own domain, since cookies can't be shared between domains. When you're done testing, remove it, or keep it out of your stats with [Exclude visits](https://supranalytics.app/docs/exclude-visits.md).

If your app only lives on a `vercel.app` address, make that address the website's domain.

## Attribute Stripe or Polar revenue

Your route handlers or server actions read the `supr_visitor_id` cookie with `cookies()` from `next/headers` and pass it to the checkout they create. Each provider's webhook then brings it back with the payment.

- Stripe: [Connect Stripe](https://supranalytics.app/docs/stripe.md) (the webhook), then [Attribute Stripe Checkout Sessions](https://supranalytics.app/docs/stripe-checkout-api.md) or [Attribute Stripe Payment Links](https://supranalytics.app/docs/stripe-payment-links.md).
- Polar: [Connect Polar](https://supranalytics.app/docs/polar.md) (the webhook), then [Attribute Polar checkouts created on your server](https://supranalytics.app/docs/polar-checkout-api.md), which has a Next.js example. Polar Checkout Links need [no code](https://supranalytics.app/docs/polar-checkout-links.md).

How payments are tied to visits, first touch or last: [How revenue attribution works](https://supranalytics.app/docs/revenue-attribution.md).

> To get past ad blockers on Next.js, the [managed proxy](https://supranalytics.app/docs/managed-proxy.md) needs no code; [rewrites](https://supranalytics.app/docs/own-proxy.md) work too, with caveats.

---

This page on the web: https://supranalytics.app/docs/nextjs
Every documentation page: https://supranalytics.app/docs.md
