How to Add Observability to a Turborepo or Nx Monorepo With One Shared Config
Stop copy-pasting SDK init code across eight apps. Here's how to wire analytics, errors, and APM into a Turborepo or Nx monorepo from a single shared package.
Picture a Turborepo with eleven apps. Marketing site, main web app, admin dashboard, a mobile web wrapper, seven internal tools. Each has its own analytics setup — a special kind of chaos that only accumulates when nobody owns the problem. Different SDK versions in five of them. Two apps pointed at the wrong project ID. One with error tracking switched off by someone who "was debugging something" and never switched it back on.
If you've ever inherited a repo like that, you know the fix isn't more dashboards. It's one shared package. One config file. Every app instrumented identically.
This is that setup. Fair warning: it's opinionated in places. You might disagree. That's fine.
What the monorepo observability setup gives you
A single internal package (@acme/observability or whatever you call your workspace scope) that every app in your monorepo imports. Change the SDK version once, bump it everywhere. Toggle a feature flag in one place, enable it across all apps. Deploy with confidence that your error tracking and analytics are consistent whether a user hits your marketing site or your main dashboard.
The config covers analytics pageviews, error tracking, and basic APM traces. Works with JustAnalytics, though the same pattern applies to Sentry, Datadog, or whatever you're using — the shared-package architecture is tool-agnostic. Honestly, most teams overthink tool selection and underthink setup consistency. If you're weighing options, our comparison of JustAnalytics vs Plausible vs Fathom breaks down the tradeoffs. Pick your poison.
Prerequisites
- Turborepo or Nx monorepo — the pattern works with either. I'll show Turborepo syntax but Nx equivalents are nearly identical.
- pnpm, yarn, or npm workspaces — any of them work. Examples use pnpm.
- Node.js 18+ — for the server-side pieces.
- At least two apps in your monorepo — otherwise why are you here?
- A JustAnalytics account — the free tier (100K events/month) covers the analytics pieces; error tracking, session replay and distributed tracing are on the Pro plan.
Step 1: Create the shared observability package
Inside your packages/ directory, create a new package. Most teams name it something like @acme/analytics, @acme/observability, or @acme/monitoring. I'll use @acme/observability since we're covering more than just analytics.
mkdir -p packages/observability
cd packages/observability
pnpm init
Your package.json should look like this:
{
"name": "@acme/observability",
"version": "0.0.1",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./client": {
"import": "./dist/client.mjs",
"require": "./dist/client.js",
"types": "./dist/client.d.ts"
},
"./server": {
"import": "./dist/server.mjs",
"require": "./dist/server.js",
"types": "./dist/server.d.ts"
}
},
"scripts": {
"build": "tsup",
"dev": "tsup --watch"
},
"devDependencies": {
"tsup": "^8.0.0",
"typescript": "^5.4.0"
},
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0"
}
}
The three exports matter. Client code imports from @acme/observability/client. Server code imports from @acme/observability/server. And anything shared (types, constants) comes from the root.
The manifest above only lists build tools. The source files import next and five OpenTelemetry packages (@opentelemetry/api, sdk-node, exporter-trace-otlp-http, resources, semantic-conventions), and tsup leaves them external, so add them as dependencies or peer dependencies too or the apps will fail to resolve them.
Step 2: Write the client-side initialization
Create src/client.tsx. This loads the analytics tracker and wraps the browser calls your apps will use.
// packages/observability/src/client.tsx
"use client";
import { useEffect } from "react";
import { usePathname, useSearchParams } from "next/navigation";
export interface ObservabilityConfig {
siteId: string;
enableReplay?: boolean;
enableErrorTracking?: boolean;
environment?: "development" | "staging" | "production";
}
const DEFAULT_CONFIG: Partial<ObservabilityConfig> = {
enableReplay: true,
enableErrorTracking: true,
environment: "production",
};
export function initClientObservability(config: ObservabilityConfig) {
const merged = { ...DEFAULT_CONFIG, ...config };
if (typeof window === "undefined") return;
if (merged.environment === "development") {
console.log("[observability] skipping init in development");
return;
}
// Inject the script if not already present. Copy the exact snippet
// (script URL and attribute names) from your JustAnalytics dashboard
// and mirror it here; the values below are placeholders for that snippet.
if (!document.querySelector('script[data-ja-loaded]')) {
const script = document.createElement("script");
script.src = "https://justanalytics.app/tracker.js";
script.async = true;
script.dataset.site = merged.siteId;
script.dataset.jaLoaded = "true";
document.head.appendChild(script);
}
}
// React hook for pageview tracking on client-side route changes
export function usePageviewTracking() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (typeof window === "undefined") return;
window.JustAnalytics?.trackPageview();
}, [pathname, searchParams]);
}
// Manual event tracking
export function trackEvent(
name: string,
properties?: Record<string, string | number | boolean>
) {
if (typeof window === "undefined") return;
window.JustAnalytics?.track(name, properties);
}
// Error boundary helper (monitor.js exposes window.JA)
export function captureError(error: Error) {
if (typeof window === "undefined") return;
window.JA?.captureException(error);
}
A word of caution on pageviews: the tracker already hooks pushState, replaceState and popstate, so SPA navigations are counted without help. Leave usePageviewTracking out unless you've confirmed an app's route changes aren't being counted. Run both against the same route changes and you get double-counted views and a bounce rate that looks suspiciously good. Check one app's live count before copying the hook into the other ten. If you're on Next.js 15, our Next.js 15 analytics tutorial covers the App Router specifics.
You'll also need ambient types so window.JustAnalytics and window.JA compile. Put a declare global { interface Window { JustAnalytics?: any; JA?: any } } block in the package and tighten it later.
captureError needs a second script. window.JA comes from monitor.js, the error-tracking script, not from tracker.js, so until you load it (the same way, from the snippet in your dashboard) the call does nothing. The unused enableErrorTracking flag is the natural switch for that injection.
Step 3: Write the server-side initialization
Create src/server.ts. This covers Node.js processes — API routes, background jobs, SSR rendering.
// packages/observability/src/server.ts
import { trace, context, SpanStatusCode } from "@opentelemetry/api";
export interface ServerObservabilityConfig {
serviceName: string;
apiKey: string;
environment?: string;
}
let initialized = false;
export async function initServerObservability(config: ServerObservabilityConfig) {
if (initialized) return;
const { NodeSDK } = await import("@opentelemetry/sdk-node");
const { OTLPTraceExporter } = await import(
"@opentelemetry/exporter-trace-otlp-http"
);
const { Resource } = await import("@opentelemetry/resources");
const { ATTR_SERVICE_NAME } = await import(
"@opentelemetry/semantic-conventions"
);
const exporter = new OTLPTraceExporter({
// Use the OTLP endpoint and auth header shown in your JustAnalytics dashboard
url: process.env.JA_OTLP_TRACES_URL!,
headers: { Authorization: `Bearer ${config.apiKey}` },
});
const sdk = new NodeSDK({
resource: new Resource({
[ATTR_SERVICE_NAME]: config.serviceName,
"deployment.environment": config.environment ?? "production",
}),
traceExporter: exporter,
});
sdk.start();
initialized = true;
process.on("SIGTERM", () => sdk.shutdown());
}
// Helper for wrapping async operations
export async function withSpan<T>(
name: string,
fn: () => Promise<T>
): Promise<T> {
const tracer = trace.getTracer("@acme/observability");
return tracer.startActiveSpan(name, async (span) => {
try {
const result = await fn();
span.setStatus({ code: SpanStatusCode.OK });
return result;
} catch (error) {
span.setStatus({ code: SpanStatusCode.ERROR });
span.recordException(error as Error);
throw error;
} finally {
span.end();
}
});
}
The withSpan helper is optional but saves you from writing the same try/catch/finally pattern everywhere. Wrap database calls, external API requests, and anywhere else you want latency visibility. Some people inline the pattern. Those people have more patience than most.
(Side note: teams skip tracing because "it's too complicated." It's not. This is about forty lines of code. The hard part is getting everyone to agree on span naming conventions, and no package fixes that for you. If you're running a multi-product portfolio, consistent naming matters even more.)
Step 4: Export everything from the package root
Create src/index.ts to re-export types and any shared utilities:
// packages/observability/src/index.ts
export type { ObservabilityConfig } from "./client";
export type { ServerObservabilityConfig } from "./server";
export const OBSERVABILITY_VERSION = "0.0.1";
And your tsup.config.ts:
// packages/observability/tsup.config.ts
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "src/client.tsx", "src/server.ts"],
format: ["cjs", "esm"],
dts: true,
clean: true,
external: ["react", "next/navigation", "@opentelemetry/*"],
});
Run pnpm build in the package directory. You should see dist/ populated with the compiled output.
Step 5: Wire it into your apps
In each app's package.json, add the workspace dependency:
{
"dependencies": {
"@acme/observability": "workspace:*"
}
}
Run pnpm install from the repo root to link everything.
Now in your app's root layout (Next.js example):
// apps/web/app/layout.tsx
import { Suspense } from "react";
import { ObservabilityProvider } from "./observability-provider";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Suspense fallback={null}>
<ObservabilityProvider />
</Suspense>
</body>
</html>
);
}
// apps/web/app/observability-provider.tsx
"use client";
import { useEffect } from "react";
import { initClientObservability } from "@acme/observability/client";
export function ObservabilityProvider() {
useEffect(() => {
initClientObservability({
siteId: process.env.NEXT_PUBLIC_JA_SITE_ID!,
environment: process.env.NODE_ENV === "production" ? "production" : "development",
});
}, []);
return null;
}
Copy this into your admin dashboard, marketing site, and internal tools. Each app passes its own siteId — one dashboard per app, unified SDK code.
Step 6: Configure Turborepo caching
Add the observability package to your build pipeline. In turbo.json:
{
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".next/**"]
}
}
}
Turborepo will cache the observability package build and skip it on subsequent runs unless the source changes. Small thing, but it adds up across a dozen apps.
Common errors and fixes
"Cannot find module '@acme/observability/client'"
Your package.json exports aren't set up correctly, or you haven't run pnpm build in the observability package. Check that dist/client.mjs exists and that your exports map points to it.
"window is not defined" on server render
You're importing client code into a Server Component. Use dynamic imports with { ssr: false } or make sure you only call initClientObservability inside a useEffect.
OpenTelemetry spans aren't appearing
Check your API key and the endpoint URL. Then check them again — a single mistyped character is easy to miss. The OTLP exporter tends to fail quietly when auth fails, which is infuriating. No error, no warning, just... nothing. Silent failure as a default is a bad call. Add a console.log after sdk.start() to confirm initialization runs, and set OTEL_LOG_LEVEL=debug to surface export errors.
Bundle size increased unexpectedly
You're probably importing server code into a client bundle. Keep the imports separate: @acme/observability/client for browsers, @acme/observability/server for Node. Tree-shaking can't save you if you import the root and it re-exports both.
Spans from the first requests are missing
Until the SDK starts, the OpenTelemetry API hands out a no-op tracer, so anything withSpan wraps before then is dropped without an error. Make sure initServerObservability completes before any traced code runs. In Next.js, put it in instrumentation.ts.
Next steps
Now that you've got unified observability, a few things worth exploring:
- Source map uploads — upload source maps from CI with
@justanalyticsapp/cliso stack traces show actual line numbers. - Error grouping — eleven apps means a lot of errors. Use issue grouping to keep them manageable, then correlate errors with user behavior, as we explain in our guide to correlating errors with analytics funnel drop-off.
- Cross-app correlation — if users flow between apps (marketing → signup → dashboard), decide up front how you'll tie those visits together. Separate site IDs per app mean separate dashboards, so plan for it.
If your marketing site buys paid traffic, ClickzProtect can flag the bot clicks in it. If you're migrating from GA4, our GA4 migration guide walks through the full process.
That's the full setup. One package, every app, observability that works the same way everywhere. Is it perfect? No. Monorepos always find new ways to surprise you, usually in the build graph. But fixing a production error with the same workflow in the admin dashboard and the marketing site is worth the afternoon.
Frequently Asked Questions
Can I use different site IDs for different apps in the same monorepo?
Yes. The shared package exports configuration that each app can override with its own site ID. Pass the app-specific ID when calling initClientObservability() and you'll see separate dashboards per app while sharing all the SDK initialization code.
Does this work with pnpm, yarn, or npm workspaces?
All three. pnpm and Yarn 2+ understand the workspace:* protocol used in this guide; npm workspaces don't, so with npm set the dependency version to "*" instead. Turborepo and Nx are build orchestrators that sit on top of your package manager — they don't care which one you use. The shared package approach works identically.
How do I handle server-side vs client-side initialization in the same shared package?
Export separate functions: initClientObservability() for browser-side code and initServerObservability() for Node.js processes. The server version uses the Node SDK and sends traces via OpenTelemetry, while the client version loads the browser script. Your apps import whichever they need based on their runtime.
Will this increase my bundle size since every app imports the shared package?
No. Each app only bundles the code paths it actually uses. Tree-shaking removes unused exports. The JustAnalytics browser script itself is under 5KB, and the shared wrapper is a small amount of configuration code. You're not duplicating anything — you're sharing it.
Try JustAnalytics
All-in-one observability in one under-5KB script: cookieless analytics + error tracking + APM + session replay + uptime + structured logs. Replaces GA4 + Sentry + Datadog + Pingdom + LogRocket. Learn more about how JustAnalytics replaces your entire observability stack. Free tier (100K events/mo), Pro $49/month ($39/month billed annually).
Author at JustAnalytics.