Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No proper documentation on how to integrate this in Next.js 13 app router #962

Open
kriptonian1 opened this issue Mar 28, 2024 · 1 comment

Comments

@kriptonian1
Copy link

I have been trying to implement it to my nextjs 13 app but the support is so bad that I decided to skip using this

@mingeee
Copy link

mingeee commented Apr 10, 2024

Yeah! I poke around for ages on this. If you are mainly using server-side rendering. The easier way is to get the NextJS middleware to hit another API endpoint. Then, in the API endpoint, you can pass all the details to Mixpanel using:

In your middleware.ts

export async function middleware(request: NextRequest) {
	const requestHeaders = new Headers(request.headers);

	const { device, isBot, ua } = userAgent(request);
	const viewport = device.type === "mobile" ? "mobile" : "desktop";
	const url = new URL(request.url);
	const path = url.pathname;

	if (ua.includes("vercel")) {
		return NextResponse.next();
	}

	const page = path === "/" ? "home" : path.split("/")[1];

	await fetch("http://localhost:3000/api/blar", {
	        method: "POST",
	        headers: {
		        "Content-Type": "application/json",
	        },
	        body: JSON.stringify({
		        page,
		        data: {
			        ip,
			        referer,
			        ua,
			        isBot,
			        viewport,
		        },
	        }),
        });

        return NextResponse.next();
}

In your api/blar/route.ts

import Mixpanel from "mixpanel";

export const mixpanel = Mixpanel.init(process.env.MIXPANEL_TOKEN as string, { geolocate: true });

export async function POST(request: Request) {
	const body = await request.json();

	const { page, data } = body;
	const { ip, referer, ua, isBot, viewport } = data;
         
         mixpanel.track(`${page} view`, {
		ip,
		d_ip: ip,
		referer,
		ua,
		isBot,
		viewport,
	});
}

NOTE: NextJS middleware can only do edge runtime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants