Disable PostHog in development
When developing your website, you don’t want to mess up your analytics with events from the development environment. So we’re going to disable PostHog in our Next.js app when in dev mode.
Setting up PostHog
If you’ve followed along with the Next.js app router tutorial for PostHog you’ve got something like the following:
"use client";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { useEffect } from "react";
export function PHProvider({ children }) {
useEffect(() => {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
person_profiles: "identified_only",
});
}, []);
return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}
How I initially setup PostHog was to simply remove the useEffect
since
there is no need to initialize posthost inside a useEffect
hook because
it is a one-time operation and doesn’t effect the rendering process. By
removing the useEffect
we avoid unnecessary re-initializations.
"use client";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
if (typeof window !== "undefined") {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST!,
person_profiles: "identified_only",
});
}
export function PHProvider({ children }: React.PropsWithChildren) {
return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}
Disabling PostHog in development
To disable PostHog in development we’re going to use process.env.NODE_ENV
to
check if we’re not in production mode, and thus in either development
or testing . If we are we’re going to return the children, otherwise we’re
going to simply return the children
. Note that we also moved the
posthog.init
inside of the PHProvider
since we only need to initialize it
when we’re actually using it.
"use client";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
export function PHProvider({ children }: React.PropsWithChildren) {
if (process.env.NODE_ENV !== "production") return children;
if (typeof window !== "undefined") {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST!,
person_profiles: "identified_only",
});
}
return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}
That’s it! Now when you run npm run dev
, PostHog will be disabled in the
development environment. Happy tracking!