Skip to main content
RapidDev - Software Development Agency
v0-integrationsNext.js API Route

How to Integrate Mixpanel with V0

To integrate Mixpanel with V0 by Vercel, add the Mixpanel browser SDK to your V0-generated Next.js app for client-side event tracking, and create a Next.js API route using your Mixpanel service account credentials to query analytics data server-side. Store the secret credentials in Vercel environment variables and deploy — your app can track user behavior and display funnel and retention analytics.

What you'll learn

  • How to initialize the Mixpanel JavaScript SDK in a Next.js App Router application
  • How to track custom events from V0-generated React components using Mixpanel
  • How to create a Next.js API route that queries Mixpanel analytics data using service account credentials
  • How to build a Mixpanel analytics dashboard component with V0 showing funnel and event data
  • How to identify users and set profile properties in Mixpanel from your Next.js app
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate15 min read35 minutesAnalyticsApril 2026RapidDev Engineering Team
TL;DR

To integrate Mixpanel with V0 by Vercel, add the Mixpanel browser SDK to your V0-generated Next.js app for client-side event tracking, and create a Next.js API route using your Mixpanel service account credentials to query analytics data server-side. Store the secret credentials in Vercel environment variables and deploy — your app can track user behavior and display funnel and retention analytics.

Add Mixpanel Event Analytics and Build Reporting Dashboards with V0

Mixpanel's event-driven model is a natural fit for Next.js applications: every user action — button clicks, page views, form submissions, feature usage — can be tracked as a named event with custom properties. Unlike Google Analytics' pageview-centric model, Mixpanel lets you analyze exactly what users do inside your app, build conversion funnels between key actions, and see retention cohorts based on specific behaviors. Adding Mixpanel to a V0-generated app takes two forms: client-side tracking with the JavaScript SDK, and server-side analytics queries.

The client-side SDK initializes with your project token (a public value, safe to expose) and tracks events by calling mixpanel.track('Event Name', { property: value }) from any React component. In Next.js App Router with Server Components, event tracking belongs in client components marked with 'use client' — the Mixpanel SDK requires browser APIs. Create a shared useMixpanel hook or a tracking utility file that components import, keeping tracking code centralized and testable.

For reading analytics data — funnel results, event counts, top properties — Mixpanel provides a Query API authenticated with service account credentials. These are server-only secrets that power dashboard API routes. The Query API supports event segmentation, funnel analysis, retention cohorts, and JQL (Mixpanel's query language) for custom reports. V0 can generate the dashboard UI — charts, tables, KPI cards — while your API routes supply the data from Mixpanel's Query API.

Integration method

Next.js API Route

Mixpanel integrates with V0-generated Next.js apps through two layers: the Mixpanel JavaScript SDK running client-side for real-time event tracking, and a Next.js API route using Mixpanel's Query API for server-side analytics queries. The public project token is safe to use client-side with NEXT_PUBLIC_ prefix. Service account credentials for reading analytics data are stored as server-only environment variables and accessed through your API routes.

Prerequisites

  • A Mixpanel account and project — create a free account at mixpanel.com, the free plan supports up to 20M events per month
  • Your Mixpanel Project Token — found in Mixpanel → Project Settings → Access Keys, this is a public value safe to use client-side
  • A Mixpanel Service Account for API access — create one in Mixpanel → Project Settings → Access Keys → Service Accounts, you'll get a username and secret
  • Your Mixpanel Project ID — visible in the URL when viewing your project (mixpanel.com/project/{projectId}) and in Project Settings
  • A V0 account at v0.dev and a Vercel account for deployment

Step-by-step guide

1

Generate the Tracking UI and Analytics Dashboard with V0

Open V0 at v0.dev and describe two separate interfaces: first, the user-facing app pages where you want to track events (any interactive feature — a pricing page, dashboard, onboarding flow), and second, a separate internal analytics dashboard for viewing the Mixpanel data. For the tracking pages, tell V0 specifically what interactions to track — button clicks, form submissions, tab switches — and V0 will generate components with onClick handlers that you'll wire to Mixpanel. For the analytics dashboard, describe the chart types and metrics you need: funnel visualizations, event count tables, time series charts, user lists. V0 uses Recharts by default for data visualization, which works well for Mixpanel analytics dashboards. Be specific about your data model — if you're tracking a signup funnel with 4 steps, tell V0 the step names and it will generate an appropriate funnel component. After generating both interfaces, push the code to GitHub using V0's Git panel. In subsequent steps you'll wire the tracking hooks into the user-facing components and build the API routes that power the dashboard with real Mixpanel data.

V0 Prompt

Create a product analytics dashboard with a left sidebar showing navigation items: Overview, Funnels, Retention, Events, and Users. The Overview page should show 4 KPI cards at the top (Monthly Active Users, New Signups, Event Count, Avg Events per User), a line chart showing daily active users over 30 days, a bar chart showing top 10 events by count this week, and a small table of the 5 most recent user signups. Include a date range picker in the top right. Show loading skeletons for all data components. Data comes from GET /api/mixpanel/overview. Use a dark gray background with white cards and violet accent colors.

Paste this in V0 chat

Pro tip: Ask V0 to generate a reusable MetricCard component with props for label, value, trend (positive/negative percentage), and icon — you'll use this card pattern throughout the analytics dashboard for different Mixpanel metrics.

Expected result: V0 generates a polished analytics dashboard UI with KPI cards, charts, and tables in preview. The components reference /api/mixpanel/* endpoints that you'll implement in the next steps.

2

Initialize the Mixpanel SDK and Add Event Tracking

Install the Mixpanel JavaScript SDK with npm install mixpanel-browser and create a tracking utility module. In Next.js App Router, the Mixpanel SDK must only run in the browser — initialize it inside a useEffect or in a module that checks typeof window !== 'undefined'. Create a client-side tracking utility at lib/mixpanel.ts that exports an initialized Mixpanel instance and helper functions. The NEXT_PUBLIC_MIXPANEL_TOKEN environment variable is safe to expose client-side because it's a public identifier, not a secret — Mixpanel's security model relies on server-side secrets for reading data and a project token for writing events. Add event tracking to your V0-generated components by importing the tracking utility and calling track() in click handlers, form submission callbacks, and useEffect hooks for page views. For user identification (connecting events to specific users after login), call mixpanel.identify(userId) with your app's user ID, then mixpanel.people.set({ email, name, plan }) to create or update the user's Mixpanel profile. This links all events from that session to the user's profile for cohort analysis.

V0 Prompt

Update the dashboard components to track Mixpanel events on all user interactions. When a user clicks on a KPI card, track 'Metric Drilldown Clicked' with the metric name as a property. When the date range picker changes, track 'Date Range Changed' with from and to dates. When navigating between sidebar sections, track 'Page Viewed' with the page name. Add the tracking calls to each interactive element using the mixpanel.track() function from lib/mixpanel.ts. Show a subtle 'Analytics active' indicator in the footer.

Paste this in V0 chat

lib/mixpanel.ts
1// lib/mixpanel.ts (client-only tracking utility)
2import mixpanel from 'mixpanel-browser';
3
4const MIXPANEL_TOKEN = process.env.NEXT_PUBLIC_MIXPANEL_TOKEN;
5
6let initialized = false;
7
8export function initMixpanel() {
9 if (initialized || typeof window === 'undefined' || !MIXPANEL_TOKEN) return;
10
11 mixpanel.init(MIXPANEL_TOKEN, {
12 debug: process.env.NODE_ENV === 'development',
13 track_pageview: true,
14 persistence: 'localStorage',
15 });
16
17 initialized = true;
18}
19
20export function track(event: string, properties?: Record<string, unknown>) {
21 if (typeof window === 'undefined') return;
22 initMixpanel();
23 mixpanel.track(event, properties);
24}
25
26export function identify(userId: string) {
27 if (typeof window === 'undefined') return;
28 initMixpanel();
29 mixpanel.identify(userId);
30}
31
32export function setUserProfile(properties: Record<string, unknown>) {
33 if (typeof window === 'undefined') return;
34 mixpanel.people.set(properties);
35}
36
37export function reset() {
38 if (typeof window === 'undefined') return;
39 mixpanel.reset(); // Call on logout
40}

Pro tip: Call mixpanel.reset() when users log out to clear the current distinct ID. Without this, the next user who logs in on the same browser will have their events merged with the previous user's profile.

Expected result: Events from your V0-generated components appear in the Mixpanel Live View (mixpanel.com/project/{id}/live) within 1-2 seconds of being triggered. Check Live View during local development to confirm tracking is working.

3

Build the Mixpanel Query API Route for Analytics Dashboards

Create a Next.js API route that queries Mixpanel's Data Export and Query APIs using your service account credentials. Mixpanel's Query API base URL is https://mixpanel.com/api/2.0/ and authentication uses Basic auth with your service account username and secret as the credentials. The most useful endpoints for dashboards are: /events (aggregate event counts by name and time), /segmentation (break down events by property), /funnels (conversion rates through a defined funnel), and /retention (cohort retention analysis). Service account credentials are secret and must never reach the browser — they give read access to all your Mixpanel data. The Mixpanel API requires project_id as a query parameter on all requests and returns data in a format specific to each endpoint. The /events endpoint returns counts by event name and date. The /segmentation endpoint returns event counts broken down by any event or profile property. For the overview dashboard, query total event counts for your key metrics and user counts from the /engage endpoint. Build helper functions for each query type and compose them in your route handler based on query parameters from the frontend.

app/api/mixpanel/overview/route.ts
1// app/api/mixpanel/overview/route.ts
2import { NextRequest, NextResponse } from 'next/server';
3
4const MIXPANEL_PROJECT_ID = process.env.MIXPANEL_PROJECT_ID;
5const MIXPANEL_SERVICE_ACCOUNT = process.env.MIXPANEL_SERVICE_ACCOUNT_USERNAME;
6const MIXPANEL_SERVICE_SECRET = process.env.MIXPANEL_SERVICE_ACCOUNT_SECRET;
7
8const MIXPANEL_API_BASE = 'https://mixpanel.com/api/2.0';
9
10function getAuthHeader(): string {
11 const credentials = `${MIXPANEL_SERVICE_ACCOUNT}:${MIXPANEL_SERVICE_SECRET}`;
12 return `Basic ${Buffer.from(credentials).toString('base64')}`;
13}
14
15async function queryMixpanel(endpoint: string, params: Record<string, string>) {
16 const queryString = new URLSearchParams({
17 project_id: MIXPANEL_PROJECT_ID!,
18 ...params,
19 }).toString();
20
21 const response = await fetch(`${MIXPANEL_API_BASE}/${endpoint}?${queryString}`, {
22 headers: {
23 Authorization: getAuthHeader(),
24 Accept: 'application/json',
25 },
26 });
27
28 if (!response.ok) {
29 throw new Error(`Mixpanel API error: ${response.status}`);
30 }
31
32 return response.json();
33}
34
35export async function GET(request: NextRequest) {
36 if (!MIXPANEL_PROJECT_ID || !MIXPANEL_SERVICE_ACCOUNT || !MIXPANEL_SERVICE_SECRET) {
37 return NextResponse.json({ error: 'Mixpanel not configured' }, { status: 500 });
38 }
39
40 const today = new Date();
41 const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
42 const fromDate = thirtyDaysAgo.toISOString().split('T')[0];
43 const toDate = today.toISOString().split('T')[0];
44
45 try {
46 // Fetch top events by count
47 const eventsData = await queryMixpanel('events/top', {
48 from_date: fromDate,
49 to_date: toDate,
50 limit: '10',
51 });
52
53 return NextResponse.json({
54 topEvents: eventsData.events || [],
55 dateRange: { from: fromDate, to: toDate },
56 });
57 } catch (error) {
58 const message = error instanceof Error ? error.message : 'Unknown error';
59 console.error('Mixpanel overview fetch failed:', message);
60 return NextResponse.json({ error: message }, { status: 500 });
61 }
62}

Pro tip: Mixpanel's Query API uses date strings in YYYY-MM-DD format for from_date and to_date parameters. Always compute these server-side in your API route rather than accepting raw date strings from the frontend to prevent injection of unexpected date ranges.

Expected result: GET /api/mixpanel/overview returns top events data from Mixpanel for the last 30 days. The analytics dashboard components display real data from your Mixpanel project.

4

Set Environment Variables in Vercel and Deploy

Push your project to GitHub and add Mixpanel credentials to Vercel. Open the Vercel Dashboard → select your project → Settings → Environment Variables. Add four variables: NEXT_PUBLIC_MIXPANEL_TOKEN with your project token (this is the only Mixpanel variable that gets the NEXT_PUBLIC_ prefix — it needs to be accessible in the browser for the client SDK), MIXPANEL_PROJECT_ID with your numeric project ID, MIXPANEL_SERVICE_ACCOUNT_USERNAME with the service account username (format: username.123456.mp-service-account), and MIXPANEL_SERVICE_ACCOUNT_SECRET with the service account secret. The service account credentials are server-only secrets — never add NEXT_PUBLIC_ to them. Set all variables for Production, Preview, and Development environments. After saving and deploying, open your live Vercel URL and interact with the app — then check Mixpanel's Live View to confirm events are arriving. Open the analytics dashboard route and verify it returns real data from your Mixpanel project. If events appear in Live View but the dashboard shows errors, check the Vercel function logs (Vercel Dashboard → your deployment → Functions) for the specific Mixpanel API error.

Pro tip: Test the Mixpanel service account credentials locally before deploying by adding them to .env.local and running npm run dev. Make a test API call to /api/mixpanel/overview in your browser or with curl to verify the credentials work before spending time debugging in Vercel.

Expected result: The deployed Vercel app tracks user events to Mixpanel in real time, and the analytics dashboard displays live data from your Mixpanel project through the API routes.

Common use cases

User Behavior Event Tracking in a SaaS App

Track every meaningful user action in your V0-generated SaaS app — feature activations, upgrade button clicks, settings changes, invite sends — to understand which features drive retention and which users are most engaged. Mixpanel's funnel analysis then shows where users drop off in your conversion flow.

V0 Prompt

Build a SaaS dashboard with three main sections: Projects list, Team Members, and Settings. Add tracking to all interactive elements — clicking 'Create Project' should track a Project Created event, clicking 'Invite Member' tracks Member Invited, and switching tabs tracks Tab Viewed with the tab name as a property. Each track call posts to the Mixpanel SDK. Include a toast notification system that briefly shows 'Action logged' when events fire in development mode. The dashboard should use a clean product UI with a dark sidebar and a white content area.

Copy this prompt to try it in V0

Conversion Funnel Analytics Dashboard

An internal marketing analytics page showing Mixpanel funnel data for your key conversion flow — from landing page visit through signup to first purchase. The dashboard displays funnel steps with conversion rates between each step, trend lines for conversion over time, and breakdown by acquisition source.

V0 Prompt

Create a funnel analytics dashboard with a title 'Signup Conversion Funnel' and a horizontal funnel visualization showing 5 steps: Landing Page View → Signup Started → Email Verified → Profile Completed → First Purchase. Each step shows the count and percentage from step 1. Below the funnel, add a line chart showing the step 1-to-last-step conversion rate over the past 30 days. Add a breakdown table showing conversion by top 5 traffic sources. All data from GET /api/mixpanel/funnel. Use an indigo and violet color scheme for the funnel steps.

Copy this prompt to try it in V0

Feature Usage Heatmap for Product Teams

A product team dashboard showing which features are used most frequently, by how many unique users, and trending up or down compared to last month. Product managers use this to prioritize roadmap items and identify underused features worth improving or removing.

V0 Prompt

Design a feature usage analytics page with a grid of feature cards. Each card shows the feature name, a 30-day usage sparkline, total event count this month, unique users count, and a trend badge (Up X% or Down X% vs last month). Sort cards by usage with a toggle for alphabetical order. Add a search filter at the top. Include a 'Top Users' section on the right showing the 10 most active users with their event counts. Fetch data from GET /api/mixpanel/events. Use a clean product analytics style with data visualizations in purple and teal.

Copy this prompt to try it in V0

Troubleshooting

Mixpanel SDK is not initialized and events are not being tracked

Cause: The Mixpanel SDK is imported in a Server Component or the initialization check for typeof window is missing, causing the SDK to attempt initialization during server-side rendering where browser APIs don't exist.

Solution: Add 'use client' directive to any component that calls Mixpanel tracking functions. Ensure the tracking utility checks typeof window !== 'undefined' before calling mixpanel.init(). For the root layout, initialize Mixpanel inside a useEffect hook which only runs in the browser.

typescript
1'use client';
2import { useEffect } from 'react';
3import { initMixpanel } from '@/lib/mixpanel';
4
5export function MixpanelProvider({ children }: { children: React.ReactNode }) {
6 useEffect(() => {
7 initMixpanel();
8 }, []);
9 return <>{children}</>;
10}

Query API returns 401 Unauthorized for service account requests

Cause: The service account credentials are wrong, the service account does not have the Project Analyst role, or the Basic auth header is being constructed incorrectly.

Solution: In Mixpanel, go to Project Settings → Access Keys → Service Accounts and verify the service account exists and has the Project Analyst role (minimum for API read access). Regenerate the secret if unsure. Verify the auth header format: 'username:secret' Base64-encoded as Basic auth, not as a token.

Events appear in Mixpanel Live View locally but not in production Vercel deployment

Cause: NEXT_PUBLIC_MIXPANEL_TOKEN is not set in Vercel environment variables, so the client-side SDK does not initialize in production.

Solution: Go to Vercel Dashboard → Settings → Environment Variables and verify NEXT_PUBLIC_MIXPANEL_TOKEN is set with the correct project token for Production scope. After adding the variable, redeploy the project — NEXT_PUBLIC_ variables are baked into the build at build time and require a new deployment to take effect.

Analytics dashboard shows data but all event counts are zero

Cause: The date range passed to Mixpanel's Query API is outside the range where events exist, or the project ID in the request does not match the project where events are being sent.

Solution: Verify MIXPANEL_PROJECT_ID matches the project ID visible in your Mixpanel URL. Check the date range in your API route — events must exist within the queried from_date to to_date range. Open Mixpanel's native reports interface to verify events are present for the time period your API is querying.

Best practices

  • Keep NEXT_PUBLIC_MIXPANEL_TOKEN (for tracking) and MIXPANEL_SERVICE_ACCOUNT_SECRET (for reading) separate — the token is public, the secret is server-only; never confuse them
  • Create a centralized tracking utility (lib/mixpanel.ts) rather than calling mixpanel.track() directly in components — this makes it easy to add event naming conventions, disable tracking in test environments, and mock tracking in tests
  • Use Mixpanel's super properties (mixpanel.register()) to attach persistent properties to every event — user plan, app version, locale — so you can filter any report by these dimensions without adding them to every individual track() call
  • Call mixpanel.identify(userId) immediately after a user logs in so all subsequent events are tied to their profile — without identify(), events from logged-in users appear as anonymous
  • Call mixpanel.reset() on logout to prevent the next user's events from being attributed to the previous user's profile on shared devices
  • Implement event naming conventions before you scale — use verb-noun patterns like 'Project Created', 'Report Downloaded', 'Plan Upgraded' so Mixpanel reports are readable without knowing internal code terminology
  • For high-traffic apps, consider batching events using Mixpanel's track_forms() and track_links() helpers rather than individual track() calls to reduce API call volume

Alternatives

Frequently asked questions

Is the Mixpanel project token safe to expose in client-side code?

Yes — the Mixpanel project token (NEXT_PUBLIC_MIXPANEL_TOKEN) is designed to be public. It identifies which Mixpanel project receives events but cannot be used to read your analytics data. Your service account credentials (username and secret) are what protect read access and must be kept server-side in Vercel environment variables without the NEXT_PUBLIC_ prefix.

How do I track events in Next.js Server Components?

The Mixpanel JavaScript SDK requires browser APIs and cannot run in Server Components. For server-side event tracking (capturing events that happen in API routes or server actions — like a successful payment or data export), use Mixpanel's HTTP API directly. POST to https://api.mixpanel.com/track with your project token and event data as a base64-encoded JSON array. This enables server-side tracking without the browser SDK.

What is the difference between Mixpanel's project token and service account credentials?

The project token is a write-only identifier — it allows sending events to your project but cannot be used to read any data. Service account credentials (username + secret) are read credentials for Mixpanel's Query API, allowing you to export event data, run funnel queries, and access user profiles. Service accounts are created per-project and assigned a role (Viewer, Analyst, or Admin) that controls which data they can access.

How long does it take for events to appear in Mixpanel reports after tracking?

Events appear in Mixpanel's Live View within 1-2 seconds of being sent. For the standard reports (Insights, Funnels, Flows), there is typically a 2-5 minute ingestion delay before events appear. Ingestion delays can extend to 24 hours in rare cases of high-volume data pipelines. If events appear in Live View but not in Funnels after 30 minutes, check that your funnel's event name matches the tracked event name exactly (case-sensitive).

Can I use Mixpanel on Vercel's free Hobby plan?

Yes — the Mixpanel browser SDK makes outbound HTTP calls from the user's browser to Mixpanel's servers directly, not through Vercel's serverless functions. This doesn't consume any Vercel function execution quota. The Query API routes you build for the analytics dashboard do run as serverless functions, but Mixpanel queries are fast (under 2 seconds) and stay within Hobby plan limits for typical usage.

How do I track page views automatically in Next.js App Router?

Use Mixpanel's track_pageview option set to true in mixpanel.init() — this automatically tracks page views for multi-page navigation. In Next.js App Router, where navigation happens without full page reloads, also add a usePathname hook in your analytics provider component and call mixpanel.track('Page Viewed', { path: pathname }) in a useEffect that runs when pathname changes.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.