How to Set Up Mixpanel in React and Next.js

React and Next.js apps are single-page applications (SPAs): after the first load, navigation happens in the browser without full page reloads. That changes how analytics works. Page views must follow route changes, initialization must happen only in the browser, and server-rendered code can’t call the browser SDK.

This guide covers setting up Mixpanel in a plain React app and in Next.js with both the Pages Router and the App Router, plus page views, identity, typed event helpers and testing.

How Mixpanel works in an SPA

  • The mixpanel-browser package needs browser APIs (window, storage), so it must run only on the client.
  • It should be initialized once per page load.
  • Page views must fire on route changes, not just the first load.
  • Identity calls (identify, reset) belong where your app learns a user logged in or out.

Step 1: Install the SDK

npm install --save mixpanel-browser
# TypeScript types, if not bundled with your version
npm install --save-dev @types/mixpanel-browser

Step 2: Store the token in an environment variable

In Next.js, create .env.local (and set the same variable in your hosting provider for production):

NEXT_PUBLIC_MIXPANEL_TOKEN=your_project_token

The NEXT_PUBLIC_ prefix is required. Without it, Next.js won’t expose the variable to browser code and Mixpanel won’t initialize. In Create React App the prefix is REACT_APP_; in Vite it’s VITE_.

Use a different token for development and production so test data stays out of your production project (post 34).

Step 3: Create one Mixpanel module

Mixpanel’s Next.js guide recommends a dedicated file, for example lib/mixpanelClient.js. Keeping all Mixpanel logic in one place makes changes easier.

// lib/mixpanelClient.js
import mixpanel from 'mixpanel-browser';

const TOKEN = process.env.NEXT_PUBLIC_MIXPANEL_TOKEN;
let initialized = false;

export const initMixpanel = () => {
  if (initialized || !TOKEN || typeof window === 'undefined') return;
  mixpanel.init(TOKEN, {
    debug: process.env.NODE_ENV !== 'production',
    track_pageview: 'url-with-path',
    persistence: 'localStorage'
  });
  initialized = true;
};

export const track = (event, props = {}) => {
  if (!initialized) return;
  mixpanel.track(event, props);
};

export const identifyUser = (userId, profile = {}) => {
  if (!initialized) return;
  mixpanel.identify(userId);
  if (Object.keys(profile).length) mixpanel.people.set(profile);
};

export const resetUser = () => {
  if (initialized) mixpanel.reset();
};

The initialized guard prevents double initialization, which can happen with React Strict Mode in development (effects run twice) or hot reloads.

Add api_host for EU or India data residency (post 33), and stop_utm_persistence: true if you use Mixpanel’s attribution models.

Step 4: Choose how page views are tracked

You have two choices. Use one, not both.

Automatic SPA page views

The JavaScript SDK’s track_pageview option accepts string values for SPAs, according to Mixpanel’s SDK release notes and community answers:

ValueFires a page view when
trueThe page first loads only
"url-with-path"The path changes (ignores query string and hash)
"url-with-path-and-query-string"The path or query string changes
"full-url"Anything in the URL changes

For most apps, "url-with-path" is the cleanest. Use "url-with-path-and-query-string" if query parameters mark genuinely different pages (such as search results).

Mixpanel’s default page view event includes properties like page title, domain, path and query string, plus UTMs and click IDs.

One known issue: in Next.js, an automatic page view can fire before the new page’s <title> updates, so the page title property shows the previous page. If titles matter, track page views manually.

Manual page views

Turn off automatic tracking (track_pageview: false) and call mixpanel.track_pageview() yourself after each route change, optionally with extra properties such as a page name or template.

Step 5a: Next.js Pages Router

In pages/_app.js, initialize once and listen to route changes, following Mixpanel’s Next.js guide:

// pages/_app.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import mixpanel from 'mixpanel-browser';
import { initMixpanel } from '../lib/mixpanelClient';

export default function MyApp({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    initMixpanel();
    const handleRouteChange = () => mixpanel.track_pageview();
    router.events.on('routeChangeComplete', handleRouteChange);
    return () => router.events.off('routeChangeComplete', handleRouteChange);
  }, [router.events]);

  return <Component {...pageProps} />;
}

If you use this manual approach, set track_pageview to true (first load only) or false and fire the first page view yourself, so the first page isn’t counted twice.

Step 5b: Next.js App Router

In the App Router, components are server components by default. Mixpanel’s guide uses a client component provider marked with 'use client', then wraps the app in layout.js.

// components/MixpanelProvider.js
'use client';

import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import mixpanel from 'mixpanel-browser';
import { initMixpanel } from '@/lib/mixpanelClient';

export default function MixpanelProvider({ children }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    initMixpanel();
  }, []);

  // Manual page views on route change (use with track_pageview: false)
  useEffect(() => {
    if (pathname) mixpanel.track_pageview();
  }, [pathname, searchParams]);

  return children;
}
// app/layout.js
import MixpanelProvider from '@/components/MixpanelProvider';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <MixpanelProvider>{children}</MixpanelProvider>
      </body>
    </html>
  );
}

Notes:

  • Next.js expects components using useSearchParams to be wrapped in a <Suspense> boundary in some cases; check the Next.js docs for your version.
  • If you prefer automatic page views, keep only the init effect and set track_pageview: 'url-with-path'.

Step 5c: Plain React (Vite or CRA)

Call initMixpanel() once near your app’s entry (for example in main.jsx before rendering). With React Router, fire mixpanel.track_pageview() in an effect that depends on useLocation().pathname, or rely on track_pageview: 'url-with-path'.

Step 6: Track custom events from components

Only call Mixpanel from client components or event handlers:

'use client';
import { track } from '@/lib/mixpanelClient';

export function UpgradeButton() {
  return (
    <button onClick={() => track('upgrade_clicked', { location: 'pricing_table' })}>
      Upgrade
    </button>
  );
}

For TypeScript projects, add typed helpers so event names and properties match your tracking plan (post 4):

type Events = {
  sign_up_completed: { signup_method: 'email' | 'google' };
  upgrade_clicked: { location: string };
};

export function trackEvent<K extends keyof Events>(name: K, props: Events[K]) {
  track(name, props);
}

This catches typos and missing properties at build time.

Step 7: Identify and reset users

Call identifyUser() when your auth provider confirms the user (after login, signup, or when the app loads with an existing session), and resetUser() on logout. Use a stable user ID from your database, not an email (post 2).

useEffect(() => {
  if (session?.user?.id) {
    identifyUser(session.user.id, { $email: session.user.email, plan: session.user.plan });
  }
}, [session?.user?.id]);

Step 8: Server-side events

Server components, route handlers and server actions can’t use mixpanel-browser. For events that happen on the server, such as a completed payment in an API route, use Mixpanel’s Node.js server SDK (post 44) and pass the same user ID.

Step 9: Test

  1. Run the app in development with debug on and watch the console.
  2. Navigate between several routes and confirm one page view per route change.
  3. In the console run mixpanel.get_distinct_id(), then search that ID in Mixpanel’s Events view.
  4. Log in and out, then confirm the profile merges and resets correctly.
  5. Build for production and confirm the token variable is set in your hosting environment.

Common issues

ProblemCause and fix
window is not definedSDK imported or called in server code. Only call it in client components or effects.
No events in productionToken variable missing the NEXT_PUBLIC_ prefix, or not set in the host.
Double page viewsBoth automatic and manual page view tracking enabled.
Double events in developmentReact Strict Mode running effects twice; use an init guard.
Wrong page title on page viewsAuto page view fired before the title updated; track manually.

Summary

Install mixpanel-browser, keep the token in a public environment variable, create one Mixpanel module with an init guard, choose automatic SPA page views or manual ones (not both), initialize in a client-side provider or _app, and call identify and reset from your auth flow. Use the Node.js SDK for server-side events.

Sources