# Next.js analytics

> Live analytics for Next.js: one component, one middleware, and you see page views, crawler visits, 404s, errors and your own events as they happen.

Source: https://mettr.app/integrations/nextjs

## Three steps to install

```bash
npm install @mettr/next
```

```tsx
// app/layout.tsx
import { Mettr } from '@mettr/next';

<head>
    <Mettr />
</head>
```

```ts
// proxy.ts (Next 16), or middleware.ts (Next 15)
import { withMettr } from '@mettr/next/middleware';

export const proxy = withMettr();
```

Set `METTR_SECRET_KEY` and `METTR_PUBLIC_KEY`, and it sends from production only. Next.js 15.1 or later, App Router.

## What you get without writing code

- **Page views, navigation and who is online**, from the [browser script](/docs/browser-script), loaded and sent through `/_live` on your own domain, so ad blockers mostly let it through.
- **Crawler visits**: Googlebot, Bingbot, GPTBot, ClaudeBot and the rest seldom run scripts. The middleware sees them, and mettr names each and keeps them apart from your visitors.
- **404s and errors**: `reportNotFound()` in your not-found page and `onRequestError` in `instrumentation.ts`. Errors go by their class, never their message.

## Your own events, server or client

```ts
import { track } from '@mettr/next/server';

await track('signup', { plan: 'pro' }, { userId: user.id });
```

From a server action or a route handler, sent after the response. In a client component, `track` from `@mettr/next/client` does the same in the browser.

## Revenue from your own billing

[Stripe](/integrations/stripe), [Paddle](/integrations/paddle) and [Polar](/integrations/polar) are read by mettr itself. Billing of your own? `getMettr()` gives the Node client, and `subscription()` sends each subscription as it changes: MRR, churn and revenue by source follow.

## Open source

`@mettr/next` is MIT licensed, on [GitHub](https://github.com/mettrhq/mettr-js) and [npm](https://www.npmjs.com/package/@mettr/next). [The full guide](/docs/nextjs).
