How to Use Mixpanel with Next. Js in Server-Side Rendering?

I am trying to use Mixpanel in a Next.js application with server-side rendering, but I am having trouble getting it to work. I have tried importing the Mixpanel library and initializing it in the getServerSideProps() method, but it doesn't seem to be working.

Here is the code I am using:

import { GetSessionParams, getSession } from "next-auth/client";
import mixpanel from "mixpanel-browser";

export async function getServerSideProps(context: GetSessionParams | undefined) {
  const session = await getSession(context);

  mixpanel.init("MY_MIXPANEL_TOKEN");

  mixpanel.track("Page view", {
    "page": "/auth/login",
    "user": session?.user?.email
  });

  if (session) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      }
    };
  }

  return {
    props: {
      session: await getSession(context)
    }
  };
}

I have also tried importing and initializing Mixpanel in the pages/_app.tsx file, but it still doesn't seem to be working.

Is there something I am missing or doing wrong? How can I use Mixpanel in a Next.js application with server-side rendering?

1
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article