From 54f7abc21fdb337d3e395e55e8026fa1b520e042 Mon Sep 17 00:00:00 2001 From: Tom Redman Date: Thu, 18 Sep 2025 10:09:53 -0400 Subject: [PATCH] Fixed instructions for NextJS App Router integration The current docs say to use `useEffect()` in the root layout, but that can't be done as the root layout is a special case, and is always server component, regardless of the "use client" directive. You cannot use `useEffect()` in a server component. --- .../tracking-methods/integrations/nextjs.mdx | 46 +++++++++++++------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/pages/docs/tracking-methods/integrations/nextjs.mdx b/pages/docs/tracking-methods/integrations/nextjs.mdx index 891f884843..e9a76e7cf4 100644 --- a/pages/docs/tracking-methods/integrations/nextjs.mdx +++ b/pages/docs/tracking-methods/integrations/nextjs.mdx @@ -73,24 +73,42 @@ import { dataItems } from "/utils/constants"; export default MyApp; ``` - b. **If using app router**, open or create the file `layout.js` or `layout.tsx` in your app/ directory + b. **If using app router**, create a file `MixpanelProvider.js` or `MixpanelProvider.tsx` in your root directory ```javascript - 'use client'; - - import { useEffect } from 'react'; - import { usePathname } from 'next/navigation'; - import { initMixpanel } from '../lib/mixpanelClient'; - - export default function RootLayout({ children }) { - + 'use client; + + import { initMixpanel } from './lib/mixpanel; + import { ReactNode, useEffect } from 'react'; + + export function MixpanelProvider({ children }: { children: ReactNode }) { useEffect(() => { - initMixpanel(); // Initialize Mixpanel + initMixpanel(); }, []); - + return children; + } + + export default MixpanelProvider; + ``` + + Then wrap your app with the provider in your root `layout.js` or `layout.tsx` file: + ```javascript + import './globals.css'; + import React from 'react'; + import MixpanelProvider from '../MixpanelProvider'; + + export default function RootLayout({ + children, + }: { + children: React.ReactNode; + }) { return ( - - {children} - + + + + {children} + + + ); } ```