Let’s be real, If your app has even slightly more going on than a basic CRUD, you’ll 100% want some kind of analytics. Whether it’s to track what features users actually use, or where they drop off, or even just how many people clicked that shiny new button you spent 3 hours designing, analytics help you understand what is going on with your website.
Today, we’re gonna look at how to integrate Mixpanel, one of the most powerful analytics platforms out there, with Next.js, which is kind of the go-to full stack framework these days.
I’m assuming you already have a nextjs project setup and a mixpanel account, you can signup on https://mixpanel.com/register/ its free .
🧩 Installing Dependencies
First things first, we need to get Mixpanel into our project. Fortunately, there’s an official SDK for the web which works great with Next.js.
Here’s the command you’ll need:
npm install mixpanel-browser
Initializing Mixpanel
Great, now lets initialize mixpanel in our app.
Lets start simple, we’ll just create a function called initMixpanel.
import mixpanel from 'mixpanel-browser';
const MIXPANEL_TOKEN = process.env.NEXT_PUBLIC_MIXPANEL_TOKEN;
export const initMixpanel = () => {
if (!MIXPANEL_TOKEN) {
console.warn('Mixpanel token is missing!');
return;
}
mixpanel.init(MIXPANEL_TOKEN, { debug: true });
}
Just make sure you add NEXT_PUBLIC in front of the env var name like we have in the snipped above, so that it is accessible on the client.
Now lets, add this to our root layout, but most probably you'll have a metadata object in your root layout and if you try to initialize it there with a useEffect you'll get a error.
You can create a providers.tsx and add the following code there
"use client"
import { useEffect, useState } from "react";
import { initMixpanel } from "@/lib/mixpanel";
import mixpanel from "mixpanel-browser";
export default function Providers({ children }: { children: React.ReactNode }) {
useEffect(() => {
initMixpanel();
}, [])
return (
{children}
)
}
Now we can wrap our root layout with this providers component like this.
import "./globals.css";
import Providers from "@/providers";
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Mixpanel Example",
description: "Mixpanel Nextjs example application",
};
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode; }>) {
return (
<html lang="en">
<body>
<Providers>
{children}
</Providers>
</body>
</html>
);
}
If you are worried about wrapping your server components, then let me tell you one thing, you can wrap server components under a client component, nextjs will handle that for you.
🔑 Getting Your Mixpanel Token
If you haven't already set up a Mixpanel project, go do that now, it's free to start.
Once thats done, head over to your mixpanel dashboard:
- Click on the gear icon on bottom right
- Go to settings -> Project Settings
- Scroll down a bit you'll see a section for Access Keys you can copy the project token and add it to your .env file with the variable name NEXT_PUBLIC_MIXPANEL_TOKEN
📈 Tracking Events
Keep in mind: Mixpanel uses a lot of event-based analytics, so it helps to come up with a consistent naming system for your events. Don't be random like "CLICKED THINGY" in one place and "User Clicked Important Button" somewhere else. Future you will thank you.
Here's a example enum for how you can keep your event names consistent:
export enum TRACK_EVENT {
PAGE_VIEW = "page_view",
SIGN_IN = "sign_in",
SIGN_UP = "sign_up",
SIGN_OUT = "sign_out",
USER_PROFILE_UPDATE = "user_profile_update",
}
You can obviously add more according to your requirements.
Alright, now the fun part begins, tracking some stuff.
Let's say you wanna track whenever someone clicks a button, submits a form, views a page, whatever.
Here's what that might look like for a page view event:
import mixpanel from "mixpanel-browser";
import { TRACK_EVENT } from "@/types/enums";
const HomePage = () => {
useEffect(() => {
mixpanel.track(TRACK_EVENT.PAGE_VIEW)
}, [])
return (
{/* Your jsx here */}
)
}
export default HomePage;
Here's how you can use it in a function:
const handleUserLogin = async (values) => {
mixpanel.track(TRACK_EVENT.SIGN_IN, {
email: values.email,
})
// Your login logic goes here…
}
🙋 Identifying Users
Tracking anonymous users is fine at first, but to get real insights, you'll wanna associate events with actual users once they log in or sign up.
Lets say you call a login function and that will make a backend call, log the user in and then return the logged in user back to you, now with that user object you have to do something like this.
const user = axios.post("/api/account/login", values)
mixpanel.identify(user?.id);
mixpanel.people.set({
"$email": user?.email,
"$name": user?.name
})
Important: Make sure you always call identify() before calling people.set(). Because let's say someone visits your site while logged out, they browse around, trigger some events, maybe even click a CTA or two. Mixpanel is already tracking those events and tying them to an anonymous device ID behind the scenes.
Now, if that person logs in and you call mixpanel.identify(userId), Mixpanel will go:
Ohhh, this device is now associated with user_123.
It stitches together all the events that happened before login and connects them to the actual user profile. Super helpful for seeing the full journey, not just post-login stuff.
So yeah, call identify() first, then people.set() to attach user properties like email, name, plan, whatever.
This lets you see how specific users behave over time, group them into cohorts, and get waaaay more out of Mixpanel.
🎉 Wrapping Up
That's pretty much it for getting started with Mixpanel in Next.js.
Just to recap:
- Install mixpanel-browser
- Initialize it (ideally with a singleton pattern)
- Use your project token
- Track some events
- Identify your users
Once you get these basics in place, you can go wild with funnels, retention, A/B tests, whatever you need to make smarter product decisions.
Happy tracking!
Connect with Me
If you enjoyed this post and want to stay in the loop with similar content, feel free to follow and connect with me across the web:
- Twitter: Follow me on Twitter for bite-sized tips, updates, and thoughts on tech.
- Medium: Check out my articles on Medium where I share tutorials, insights, and deep dives.
- Email: Got questions, ideas, or just want to say hi? Drop me a line at codezera3@gmail.com.
Your support means a lot, and I'd love to connect, collaborate, or just geek out over cool projects. Looking forward to hearing from you!
Top comments (0)