Implement Mixpanel analytics in a NextJS app
NextJS
React
May 01, 2023
1. Install Mixpanel:
npm install --save mixpanel-browser
2. Install Mixpanel types for Typescript
npm i --save-dev @types/mixpanel-browser
3. Create a mix panel Context/Provider file
In order to call mix panel via a hook, lets create a Mixpanel Context/Provider file
The following code creates a React Provider.
Here we init the mixpanel code and expose the mixpanel variable to interact with mixpanel on children components.
Here, we also add the code to track the page views.
import mixpanel, { OverridedMixpanel } from "mixpanel-browser";
import { useRouter } from "next/router";
import { createContext, ReactNode, useContext, useEffect } from "react";
//the current version of the mixpanel types does not include the track_pageview method. Let's add it
declare module "mixpanel-browser" {
interface Mixpanel {
track_pageview(properties?: Dict): void;
}
}
const mixPanelKey = process.env.NEXT_PUBLIC_MIXPANEL_KEY || "";
mixpanel.init(mixPanelKey, { debug: process.env.NODE_ENV === "development" });
const MixPanelContext = createContext<OverridedMixpanel | undefined>(undefined);
type Props = {
children: ReactNode;
};
const MixPanelProvider = ({ children }: Props) => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = () => {
mixpanel?.track_pageview();
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
return (
<MixPanelContext.Provider value={mixpanel}>
{children}
</MixPanelContext.Provider>
);
};
function useMixPanel() {
const context = useContext(MixPanelContext);
if (context === undefined) {
throw new Error("MixPanelContext must be used within a MixpanelProvider");
}
return context;
}
export { MixPanelProvider, useMixPanel };
4. Add the context to the _app file
<MixPanelProvider>
<Component {...pageProps} />
</MixPanelProvider>
5. Call the useMixpanel hook to track custom events from children components
const mixpanel = useMixPanel();
mixpanel.track("click-add-filter", { criteria: "date-filter" });
6. Add the mixpanel key to the env file
Create an .env file and add a new key value
NEXT_PUBLIC_MIXPANEL_KEY=your key
Check the source code