> ## Documentation Index
> Fetch the complete documentation index at: https://bhavishaya.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js — Pages Router

> Add Analytiq to your Next.js app (Pages Router) in two files. Uses the Analytiq component for initialization.

<Note>
  This guide is for Next.js projects with a **`/pages` directory**. If you have an `/app` directory, [use the App Router guide](/frameworks/nextjs-app-router)
</Note>

***

## Step 1 — Install the SDK

```bash theme={null}
npm install analytiq
```

***

## Step 2 — Create `components/analytics.jsx` (One-time setup)

Create this file anywhere in your project. This is the **only place** Analytiq is configured.

<Tabs>
  <Tab title="TypeScript (analytics.tsx)">
    ```tsx components/analytics.tsx theme={null}
    import { Analytiq, identify, reset, track } from 'analytiq/react'
    import { useEffect } from 'react'
    import { useAuth } from '../context/AuthContext'   // your existing auth

    export function AnalyticsProvider({ children }: { children: React.ReactNode }) {
      const { user } = useAuth()

      useEffect(() => {
        if (user) {
          identify(user)
        } else {
          reset()
        }
      }, [user])

      return (
        <>
          <Analytiq apiKey={process.env.NEXT_PUBLIC_ANALYTIQ_KEY!} />
          {children}
        </>
      )
    }

    export { track }
    ```
  </Tab>

  <Tab title="JavaScript (analytics.js)">
    ```jsx components/analytics.js theme={null}
    import { Analytiq, identify, reset, track } from 'analytiq/react'
    import { useEffect } from 'react'
    import { useAuth } from '../context/AuthContext'

    export function AnalyticsProvider({ children }) {
      const { user } = useAuth()

      useEffect(() => {
        if (user) {
          identify(user)
        } else {
          reset()
        }
      }, [user])

      return (
        <>
          <Analytiq apiKey={process.env.NEXT_PUBLIC_ANALYTIQ_KEY} />
          {children}
        </>
      )
    }

    export { track }
    ```
  </Tab>
</Tabs>

**Add your API key to `.env.local`:**

```bash theme={null}
NEXT_PUBLIC_ANALYTIQ_KEY=pk_live_your_actual_key_here
```

<Warning>
  The prefix **must** be `NEXT_PUBLIC_`. Without it, the key will be `undefined` on the client side.
</Warning>

***

## Step 3 — Wrap your app in `pages/_app`

`_app` is a special Next.js file that wraps every page. Add your `AnalyticsProvider` there.

<Tabs>
  <Tab title="TypeScript (pages/_app.tsx)">
    ```tsx pages/_app.tsx theme={null}
    import type { AppProps } from 'next/app'
    import { AuthProvider } from '../context/AuthContext'
    import { AnalyticsProvider } from '../components/analytics'

    export default function MyApp({ Component, pageProps }: AppProps) {
      return (
        <AuthProvider>
          <AnalyticsProvider>
            <Component {...pageProps} />
          </AnalyticsProvider>
        </AuthProvider>
      )
    }
    ```
  </Tab>

  <Tab title="JavaScript (pages/_app.js)">
    ```jsx pages/_app.js theme={null}
    import { AuthProvider } from '../context/AuthContext'
    import { AnalyticsProvider } from '../components/analytics'

    export default function MyApp({ Component, pageProps }) {
      return (
        <AuthProvider>
          <AnalyticsProvider>
            <Component {...pageProps} />
          </AnalyticsProvider>
        </AuthProvider>
      )
    }
    ```
  </Tab>
</Tabs>

<Check>
  Setup is complete! You never need to touch `_app` again for analytics purposes.
</Check>

***

## What the setup handles automatically

| Action                             | What happens                                                         |
| ---------------------------------- | -------------------------------------------------------------------- |
| App loads (user logged out)        | `init()` runs once, anonymous tracking begins                        |
| App loads (user already logged in) | `userId` restored from `localStorage`, user identified immediately   |
| User logs in (your auth changes)   | `useEffect` detects new user → `identify(user)` called automatically |
| User logs out                      | `user` becomes `null` → `reset()` called automatically               |

***

## Step 4 — Track Custom Events

For any specific action, import `track()` **from your `analytics.jsx` file** and call it where the action happens.

<Tabs>
  <Tab title="Track a page view">
    ```jsx pages/dashboard.jsx theme={null}
    import { useEffect } from 'react'
    import { track } from '../components/analytics'   // Import from your hub!

    export default function DashboardPage() {
      useEffect(() => {
        track('Dashboard_page_view')
      }, [])

      return <h1>Dashboard</h1>
    }
    ```
  </Tab>

  <Tab title="Button click">
    ```jsx pages/pricing.jsx theme={null}
    import { track } from '../components/analytics'

    export default function PricingPage() {
      return (
        <button onClick={() => track('upgrade_clicked', { plan: 'Pro' })}>
          Upgrade to Pro
        </button>
      )
    }
    ```
  </Tab>

  <Tab title="After a login / API call">
    ```jsx pages/login.jsx theme={null}
    import { useRouter } from 'next/router'
    import { track } from '../components/analytics'

    export default function LoginPage() {
      const router = useRouter()

      async function handleLogin(email, password) {
        const res = await api.post('/auth/login', { email, password })

        track('login_completed', { method: 'email' })
        router.push('/dashboard')
      }
    }
    ```
  </Tab>
</Tabs>

***

## Step 5 — Verify it's working

1. Run: `npm run dev`
2. Log into your app
3. Open `http://localhost:3000`, press **F12** → **Network** tab
4. You should see `POST /api/events/track` requests for every `track()` call you make

***

## Common Mistakes

| Mistake                                     | Symptom                                | Fix                                               |
| ------------------------------------------- | -------------------------------------- | ------------------------------------------------- |
| Using `ANALYTIQ_KEY` without `NEXT_PUBLIC_` | `undefined` key warning                | Rename to `NEXT_PUBLIC_ANALYTIQ_KEY`              |
| `AnalyticsProvider` outside `AuthProvider`  | `useAuth()` context error              | Auth must always wrap Analytics                   |
| Importing `track` from `analytiq` directly  | Events may fire before SDK initializes | Always import from your local `analytics.jsx` hub |
