Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(analytics): initialize PostHog before the layout identifies the user
Raul9eb2ed029377
diff --git a/apps/erp/app/entry.client.tsx b/apps/erp/app/entry.client.tsxindex 23fa2b4cbb..0fb147a149 100644--- a/apps/erp/app/entry.client.tsx+++ b/apps/erp/app/entry.client.tsx@@ -1,5 +1,5 @@import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url";-import { Fragment, startTransition, useEffect } from "react";+import { startTransition } from "react";import { pdfjs } from "react-pdf";pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;@@ -12,26 +12,21 @@ import { HydratedRouter } from "react-router/dom";ensureLoggingConfigured();+// Initialized at module scope, before hydration, rather than from an effect:+// the authenticated layout calls identify()/register()/group() from its own+// effect, and posthog-js drops those when it isn't loaded yet — register()+// without even a warning. React flushes effects in tree order, so an effect+// here would run after the router's and lose them.+//// The project key is what enables analytics: it is unset in local development// and set by the deployment. A hostname check can't stand in for that, since// `crbn up` serves the app from *.dev rather than localhost.-function PosthogInit() {- useEffect(() => {- if (!POSTHOG_PROJECT_PUBLIC_KEY) return;-- posthog.init(POSTHOG_PROJECT_PUBLIC_KEY, {- api_host: POSTHOG_API_HOST- });- }, []);- return null;+if (POSTHOG_PROJECT_PUBLIC_KEY) {+ posthog.init(POSTHOG_PROJECT_PUBLIC_KEY, {+ api_host: POSTHOG_API_HOST+ });}startTransition(() => {- hydrateRoot(- document,- <Fragment>- <HydratedRouter />- <PosthogInit />- </Fragment>- );+ hydrateRoot(document, <HydratedRouter />);});diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 4d17814696..e727f7c6a5 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -24,13 +24,12 @@ import {ItarPopup,TooltipProvider,useKeyboardWedge,- useMount,useNProgress} from "@carbon/react";import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";import { Edition, isSearchParamOnlyNavigation } from "@carbon/utils";import posthog from "posthog-js";-import { Suspense } from "react";+import { Suspense, useEffect } from "react";import type {LoaderFunctionArgs,ShouldRevalidateFunction@@ -282,23 +281,32 @@ export default function AuthenticatedRoute() {}});- useMount(() => {- if (!user) return;+ const userId = user?.id;+ const userEmail = user?.email;+ const userFullName = user ? `${user.firstName} ${user.lastName}` : undefined;+ const companyId = company?.companyId;+ const companyName = company?.name;- posthog.identify(user.id, {- email: user.email,- name: `${user.firstName} ${user.lastName}`- });+ // Keyed on the identity rather than run once on mount: switching company+ // redirects back into x+/_layout without unmounting it, so a mount-only+ // effect would leave the previous company attached to every later event.+ // The deps are primitives because `user`/`company` get fresh object+ // identities on every revalidation, and group() re-sends $groupidentify+ // each time it is called.+ useEffect(() => {+ if (!userId) return;++ posthog.identify(userId, { email: userEmail, name: userFullName });- if (!company?.companyId) return;+ if (!companyId) return;// Adoption is measured per customer, and a user can belong to more than one// company — so the company rides on the events rather than on the person.// register() puts companyId on every event including autocapture; group()// is what lets PostHog aggregate by customer.- posthog.register({ companyId: company.companyId });- posthog.group("company", company.companyId, { name: company.name });- });+ posthog.register({ companyId });+ posthog.group("company", companyId, { name: companyName });+ }, [userId, userEmail, userFullName, companyId, companyName]);return (<div className="h-[100dvh] flex flex-col">diff --git a/apps/mes/app/entry.client.tsx b/apps/mes/app/entry.client.tsxindex 2dba05cf69..29bfabf065 100644--- a/apps/mes/app/entry.client.tsx+++ b/apps/mes/app/entry.client.tsx@@ -6,32 +6,27 @@ pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;import { POSTHOG_API_HOST, POSTHOG_PROJECT_PUBLIC_KEY } from "@carbon/auth";import { ensureLoggingConfigured } from "@carbon/logger/config.client";import posthog from "posthog-js";-import { Fragment, startTransition, useEffect } from "react";+import { startTransition } from "react";import { hydrateRoot } from "react-dom/client";import { HydratedRouter } from "react-router/dom";ensureLoggingConfigured();+// Initialized at module scope, before hydration, rather than from an effect:+// the authenticated layout calls identify()/register()/group() from its own+// effect, and posthog-js drops those when it isn't loaded yet — register()+// without even a warning. React flushes effects in tree order, so an effect+// here would run after the router's and lose them.+//// The project key is what enables analytics: it is unset in local development// and set by the deployment. A hostname check can't stand in for that, since// `crbn up` serves the app from *.dev rather than localhost.-function PosthogInit() {- useEffect(() => {- if (!POSTHOG_PROJECT_PUBLIC_KEY) return;-- posthog.init(POSTHOG_PROJECT_PUBLIC_KEY, {- api_host: POSTHOG_API_HOST- });- }, []);- return null;+if (POSTHOG_PROJECT_PUBLIC_KEY) {+ posthog.init(POSTHOG_PROJECT_PUBLIC_KEY, {+ api_host: POSTHOG_API_HOST+ });}startTransition(() => {- hydrateRoot(- document,- <Fragment>- <HydratedRouter />- <PosthogInit />- </Fragment>- );+ hydrateRoot(document, <HydratedRouter />);});diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex 0c4d693147..26df5d9c0c 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -19,13 +19,12 @@ import {SidebarProvider,TooltipProvider,useKeyboardWedge,- useMount,useNProgress} from "@carbon/react";import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";import { Edition, isSearchParamOnlyNavigation } from "@carbon/utils";import posthog from "posthog-js";-import { Suspense } from "react";+import { Suspense, useEffect } from "react";import type {LoaderFunctionArgs,MiddlewareFunction,@@ -252,23 +251,32 @@ export default function AuthenticatedRoute() {}});- useMount(() => {- if (!user) return;+ const userId = user?.id;+ const userEmail = user?.email;+ const userFullName = user ? `${user.firstName} ${user.lastName}` : undefined;+ const companyId = company?.companyId;+ const companyName = company?.name;- posthog.identify(user.id, {- email: user.email,- name: `${user.firstName} ${user.lastName}`- });+ // Keyed on the identity rather than run once on mount: switching company+ // redirects back into x+/_layout without unmounting it, so a mount-only+ // effect would leave the previous company attached to every later event.+ // The deps are primitives because `user`/`company` get fresh object+ // identities on every revalidation, and group() re-sends $groupidentify+ // each time it is called.+ useEffect(() => {+ if (!userId) return;- if (!company?.companyId) return;+ posthog.identify(userId, { email: userEmail, name: userFullName });++ if (!companyId) return;// Adoption is measured per customer, and a user can belong to more than one// company — so the company rides on the events rather than on the person.// register() puts companyId on every event including autocapture; group()// is what lets PostHog aggregate by customer.- posthog.register({ companyId: company.companyId });- posthog.group("company", company.companyId, { name: company.name });- });+ posthog.register({ companyId });+ posthog.group("company", companyId, { name: companyName });+ }, [userId, userEmail, userFullName, companyId, companyName]);// Scroll stays unlocked until lg, where the controls dock beside the content// instead of stacking below it.