> ## 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 — App Router

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

<Warning>
  This guide is for Next.js projects that use the **`/app` directory** (Next.js 13+). If your project has a `/pages` folder instead, [use this guide](/frameworks/nextjs-pages-router)
</Warning>

<Note>
  **Before starting:** Get your API key from [Settings](/api-key)
</Note>

***

## Step 1 — Install the SDK

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

***

## Step 2 — Create `components/analytics.tsx` (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}
    'use client'
    // ↑ Required — tells Next.js this runs in the browser, not the server

    import { Analytiq, identify, reset, track } from 'analytiq/react'
    import { useEffect } from 'react'

    // Import YOUR app's authentication hook here
    import { useAuth } from '@/context/AuthContext'

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

      // Bridges your Auth system to the Analytics SDK
      useEffect(() => {
        if (user) {
          identify(user)
        } else {
          reset()
        }
      }, [user])

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

    // Re-export track so other files import from here, not the package directly
    export { track }
    ```
  </Tab>

  <Tab title="JavaScript (analytics.js)">
    ```jsx components/analytics.js theme={null}
    'use client'
    // ↑ Required — tells Next.js this runs in the browser, not the server

    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_`. Any other prefix (like `VITE_` or just `ANALYTIQ_KEY`) will make the key `undefined` on the client.
</Warning>

***

## Step 3 — Wrap your app in `app/layout.tsx`

Open your existing `app/layout.tsx` and wrap the children with the provider. Make sure it goes **inside** your Auth provider.

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

    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode
    }) {
      return (
        <html lang="en">
          <body>
            <AuthProvider>
              <AnalyticsProvider>
                {children}
              </AnalyticsProvider>
            </AuthProvider>
          </body>
        </html>
      )
    }
    ```
  </Tab>

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

    export default function RootLayout({ children }) {
      return (
        <html lang="en">
          <body>
            <AuthProvider>
              <AnalyticsProvider>
                {children}
              </AnalyticsProvider>
            </AuthProvider>
          </body>
        </html>
      )
    }
    ```
  </Tab>
</Tabs>

<Check>
  Setup is complete! You never need to touch these two files 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 instantly     |
| User logs in (your auth changes)   | `useEffect` detects new user → `identify(user)` called automatically |
| User logs out (your auth clears)   | `user` becomes `null` → `reset()` called automatically               |

***

## Step 4 — Track Custom Events

For specific actions (page views, button clicks, purchases), import `track()` **from your `analytics.tsx` file** and call it where the action happens. Always add `'use client'` at the top since `track()` is browser-only.

<Tabs>
  <Tab title="Track a page view">
    ```tsx app/page.tsx theme={null}
    'use client'
    import { useEffect } from 'react'
    import { track } from '@/components/analytics'   // Import from your hub!

    export default function HomePage() {
      useEffect(() => {
        track('Home_page_view')
      }, [])

      return <main><h1>Home</h1></main>
    }
    ```
  </Tab>

  <Tab title="Button click">
    ```tsx app/pricing/page.tsx theme={null}
    'use client'
    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 API call">
    ```tsx app/checkout/page.tsx theme={null}
    'use client'
    import { track } from '@/components/analytics'

    async function handlePayment(data: any) {
      const result = await processPayment(data)

      if (result.success) {
        track('order_completed', { order_id: result.id, total: result.total })
      } else {
        track('payment_failed', { reason: result.error })
      }
    }
    ```
  </Tab>
</Tabs>

***

## Step 5 — Verify it's working

1. Run: `npm run dev`
2. Log into your app (so your `useAuth` returns a user)
3. Open `http://localhost:3000`, press **F12** → **Network** tab, filter by `track`
4. You should see a `POST /api/events/track` request for any event you fire manually

***

## Common Mistakes

| Mistake                                            | Symptom                                | Fix                                               |
| -------------------------------------------------- | -------------------------------------- | ------------------------------------------------- |
| Missing `'use client'` on any file using `track()` | Build error about server components    | Add `'use client'` as the very first line         |
| Using `ANALYTIQ_KEY` without `NEXT_PUBLIC_`        | `undefined` key warning in console     | Rename to `NEXT_PUBLIC_ANALYTIQ_KEY`              |
| `AnalyticsProvider` outside `AuthProvider`         | `useAuth()` context error              | Auth must wrap Analytics in `layout.tsx`          |
| Importing `track` directly from `analytiq`         | Events may fire before SDK initializes | Always import from your local `analytics.tsx` hub |
