Skip to main content
This guide is for Next.js projects with a /pages directory. If you have an /app directory, use the App Router guide

Step 1 — Install the SDK

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.
components/analytics.tsx
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 }
Add your API key to .env.local:
NEXT_PUBLIC_ANALYTIQ_KEY=pk_live_your_actual_key_here
The prefix must be NEXT_PUBLIC_. Without it, the key will be undefined on the client side.

Step 3 — Wrap your app in pages/_app

_app is a special Next.js file that wraps every page. Add your AnalyticsProvider there.
pages/_app.tsx
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>
  )
}
Setup is complete! You never need to touch _app again for analytics purposes.

What the setup handles automatically

ActionWhat 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 outuser becomes nullreset() 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.
pages/dashboard.jsx
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>
}

Step 5 — Verify it’s working

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

Common Mistakes

MistakeSymptomFix
Using ANALYTIQ_KEY without NEXT_PUBLIC_undefined key warningRename to NEXT_PUBLIC_ANALYTIQ_KEY
AnalyticsProvider outside AuthProvideruseAuth() context errorAuth must always wrap Analytics
Importing track from analytiq directlyEvents may fire before SDK initializesAlways import from your local analytics.jsx hub