# Product analytics for Next.js

Add open-source product analytics to Next.js with the Pug Web SDK: one client component in your root layout gives autocapture, identity, and funnels.

Source: https://pug.sh/integrations/nextjs

Pug’s Web SDK is framework-agnostic JavaScript, so there’s no separate Next.js package to learn. Mount it once in a client component from your App Router root layout, then add one effect so client-side navigations keep counting.

- Pug Web SDK: one SDK for the browser
- @pug-sh/browser
- Open source: MIT SDK, AGPL-3.0 server

## Add Pug to Next.js

Four steps, start to first insight. Everything below uses the Web SDK exactly as it ships. There is no Next.js wrapper in between.

### 1. Install the Web SDK

One package covers every browser framework. It ships compiled JavaScript plus type definitions for bundlers, so Next.js needs no extra config.

```bash
npm install @pug-sh/browser
# or: pnpm add @pug-sh/browser · yarn add @pug-sh/browser · bun add @pug-sh/browser
```

### 2. Initialize from a client component

init() must run in the browser, not during SSR, so put it in a small "use client" component and render it once inside <body> in app/layout.tsx. Both values are public (the key is write-scoped and safe to ship in client code), so NEXT_PUBLIC_ env vars are the right home for them.

`app/pug-provider.tsx`

```tsx
'use client'

import { useEffect } from 'react'
import { init } from '@pug-sh/browser'

export function PugProvider() {
  useEffect(() => {
    init(process.env.NEXT_PUBLIC_PUG_PROJECT_ID!, {
      apiKey: process.env.NEXT_PUBLIC_PUG_PUBLIC_KEY!,
    })
  }, [])
  return null
}
```

### 3. Keep counting App Router navigations

Autocapture derives page views from the History API. The App Router navigates without a History push, so it fires page_view on the first load and then goes quiet. Send the rest yourself from a usePathname() effect. This is the one piece of Next.js-specific wiring Pug needs.

`app/pug-page-views.tsx`

```tsx
'use client'

import { useEffect } from 'react'
import { usePathname } from 'next/navigation'
import { track } from '@pug-sh/browser'

export function PugPageViews() {
  const pathname = usePathname()
  useEffect(() => {
    track('page_view')
  }, [pathname])
  return null
}
```

### 4. Identify people, and trust your revenue events

Call identify() once you know who someone is, and the anonymous session merges into their profile. Events that must be right regardless of the browser belong on the server: send those from a route handler with the Node SDK, naming the same user id.

`app/api/checkout/route.ts`

```ts
import { Pug } from '@pug-sh/node'

const pug = new Pug({ apiKey: process.env.PUG_PRIVATE_KEY! }) // prv_…, server only

export async function POST(req: Request) {
  const { userId, amount } = await req.json()
  pug.track(userId, 'order_completed', { amount, currency: 'USD' })
  return Response.json({ ok: true })
}
```

## What to watch for in Next.js

The specifics that decide whether the numbers you see are the numbers that happened.

### App Router page views need one effect

The History API is what autocapture listens to, and App Router navigation does not push through it. Without the usePathname() effect above you get a page_view on entry and nothing after, so any funnel past the landing page looks broken.

### Server Components never run the tracker

They render on the server, where there is no browser session to attribute to. Keep init() in a client component, and use the Node SDK for anything that happens in a route handler, server action, or webhook.

### Two keys, two homes

The public key (pub_…) is write-scoped and belongs in NEXT_PUBLIC_ vars. The private key (prv_…) also authorizes reads, so keep it server-side only. The Node SDK refuses to construct with anything but a prv_ key.

### Cookieless until someone answers

The Web SDK starts in cookieless consent by default: events are counted with a server-side hash whose salt is deleted daily, no identifier is stored on the device, and identify() does nothing until the visitor opts in. Pass trackingConsent to change that.

## Report AI crawlers from proxy.ts. Crawlers don’t run JavaScript, so the Web SDK never sees them.

Install @pug-sh/crawlers (it has no dependencies) and call it from your Next.js proxy with your private key. For a request from a known crawler, such as GPTBot, ClaudeBot, or ChatGPT-User, it sends one report to Pug; your visitors’ requests never leave your server. Pug checks the IP against the ranges the operator publishes, so a scraper borrowing GPTBot’s name reads as unverified. The proxy runs before the page, so these reports carry no status code, and each one counts toward your usage as a crawler_request event.

`proxy.ts`

```ts
import { crawlers } from '@pug-sh/crawlers'
import { type NextFetchEvent, type NextRequest, NextResponse } from 'next/server'

const pug = crawlers({ apiKey: process.env.PUG_PRIVATE_KEY! })

export function proxy(request: NextRequest, event: NextFetchEvent) {
  pug.track(request, undefined, event)
  return NextResponse.next()
}
```

[AI crawler setup in the docs](https://docs.pug.sh/crawlers/)

## Product analytics in your Next.js app

### Autocapture, six trackers

Page views, clicks, scrolls, form starts and submits, rage clicks, and dead clicks: all on after one init(), or narrowed with a per-listener allowlist.

### One profile per person

identify() merges the anonymous session into the signed-in profile and keeps it joined across devices and later visits.

### Your own events

track() takes a name and typed properties, with a generated list of well-known event kinds so your names match what the insights expect.

### Every insight type

Trends, funnels, retention cohorts, segmentation, user flows, top-K lists, and country maps all run over the same events, with no instrumentation per report.

## Read it in the docs

The Web SDK reference goes deeper than a setup page can: every option, every event, and the edge cases.

- [Next.js App Router setup](https://docs.pug.sh/sdks/web/#nextjs-app-router): The provider component and the page-view caveat, in the SDK reference.
- [init() options](https://docs.pug.sh/sdks/web/#initialize): Every option with its default: batching, sessions, consent, redaction.
- [Auto-tracking](https://docs.pug.sh/sdks/web/#auto-tracking): The six trackers, the properties each captures, and the allowlist form.
- [Tracking consent](https://docs.pug.sh/sdks/web/#tracking-consent): Wiring a banner to the granted, cookieless, and denied states.
- [Node SDK events](https://docs.pug.sh/sdks/node/#track-events): track(), flush(), and close() for the route-handler events in step 4.
- [AI crawler reports](https://docs.pug.sh/crawlers/): The Next.js proxy and every other adapter, the five crawler categories, and what each report sends.

* [Start from the beginning](https://docs.pug.sh/get-started/)
* [See all SDKs](https://pug.sh/sdks)

## Pug + Next.js: common questions

### Do I need a Next.js-specific package?

No, and none is needed. Pug ships a single Web SDK (TypeScript/JavaScript) that runs in any browser framework, Next.js included. You install the same @pug-sh/browser package and initialise it once from a client component.

### Does it work with the App Router and Server Components?

Yes. Autocapture is a browser concern, so initialise the SDK in a small "use client" component mounted in your root layout. Server Components render on the server and don’t run the tracker themselves; pair the Web SDK with the Node SDK if you also want authoritative server-side events.

### Why do page views stop after the first load?

Because the App Router navigates without a History push, and that is what autocapture listens to. Add the usePathname() effect above: it calls track('page_view') on every route change, which is the same event autocapture would have sent. The Pages Router and ordinary SPA routers push through History, so they need no equivalent.

### Where do I put the project ID and keys?

The project ID and public key go in NEXT_PUBLIC_ environment variables. The public key is write-scoped (events and identify only) and designed to ship in client code. The private key is a different key entirely: it also authorizes reads, so it stays in server-only env vars and is used by the Node SDK.

### Can I self-host the analytics backend?

Yes. Pug is open source under AGPL-3.0: one Go binary on PostgreSQL, ClickHouse, NATS, and Dragonfly. A self-hosted install points the SDK at your server with the endpoint option; on Pug Cloud, free up to 100k events a month, you leave it out.
