@bbcd0/analytics
v1.7.1
Published
This package shared analytics utils to be used in all projects across bbcd0.
Downloads
1,022
Readme
@bbcd0/analytics
Shared analytics utilities for bbcd0 projects. Built on top of RudderStack Analytics.
Installation
npm install @bbcd0/analyticsRequirements
- React >= 19.2.0
- React DOM >= 19.2.0
- Next.js >= 16.0.0 when using
@bbcd0/analytics/next - Node.js >= 24.0.0 when using
@bbcd0/analytics/node(@bbcd0/analytics/cookieshas no runtime dependencies and no such requirement) - React Router >= 7.0.0 when using
@bbcd0/analytics/react-router - Vite >= 5.0.0 when using
@bbcd0/analytics/vite
Usage
1. Next.js Connection Script
If you are using Next.js, add AnalyticsScript from @bbcd0/analytics/next to your app's root layout:
import { AnalyticsScript } from "@bbcd0/analytics/next";
import type { ReactNode } from "react";
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<head>
<AnalyticsScript />
</head>
<body>{children}</body>
</html>
);
}2. Vite Connection Script
If you are using Vite, add the analytics plugin to your Vite config. It injects the connection script into index.html automatically:
import { analytics } from "@bbcd0/analytics/vite";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [analytics()],
});The plugin accepts optional id and identifier options. By default it uses id="bufferEvents" and the global analytics identifier "analytics".
3. React Router Analytics
If you are using React Router, use the route-aware components from @bbcd0/analytics/react-router.
Render them inside the router context so page views and performance events follow client-side navigation:
// main.ts
import { reportWebVitals } from "@bbcd0/analytics/react";
reportWebVitals({ ignoredSearchParams: ["modal"] });import { AnalyticsContext } from "@bbcd0/analytics/react";
import { PageViewAnalytics, PerformanceAnalytics } from "@bbcd0/analytics/react-router";
import { Outlet } from "react-router";
export function RootRoute() {
return (
<AnalyticsContext
value={{
writeKey: "YOUR_WRITE_KEY",
dataPlaneUrl: "YOUR_DATA_PLANE_URL",
source: {
id: "YOUR_SOURCE_ID",
name: "YOUR_SOURCE_NAME",
workspaceId: "YOUR_WORKSPACE_ID",
},
}}
>
<PageViewAnalytics ignoredSearchParams={["modal"]} />
<PerformanceAnalytics ignoredSearchParams={["modal"]} />
<Outlet />
</AnalyticsContext>
);
}The lower-level @bbcd0/analytics/react entrypoint is still available when you want to pass url manually.
4. Node Analytics
Use the Node entrypoint for server-side events. trackAndFlush waits until the SDK queue is processed, which is useful before returning from a short-lived request or issuing a redirect:
Reading a RudderStack cookie does not need the Node SDK. It lives in @bbcd0/analytics/cookies, a dependency-free entrypoint that any bundler can process without extra configuration:
import { anonymousUserIdKey, getAnonymousId } from "@bbcd0/analytics/cookies";
const anonymousId = getAnonymousId(request.cookies.get(anonymousUserIdKey)?.value);getAnonymousId returns undefined for a missing cookie and for any value that does not decode to a non-empty ID. The same entrypoint also re-exports the raw getDecryptedValue for the other RudderStack cookies. Cookie helpers live here and not in @bbcd0/analytics/node on purpose: the Node entrypoint pulls the Node SDK into the module graph, and bundlers that cannot resolve its worker fork fail the build.
When you also create a Node analytics client, externalize the underlying RudderStack Node SDK in next.config:
const nextConfig = {
serverExternalPackages: ["@rudderstack/rudder-sdk-node"],
};
export default nextConfig;import { anonymousUserIdKey, getAnonymousId } from "@bbcd0/analytics/cookies";
import { createAnalytics } from "@bbcd0/analytics/node";
const analytics = createAnalytics({
dataPlaneUrl: "YOUR_DATA_PLANE_URL",
writeKey: "YOUR_WRITE_KEY",
});
const anonymousId = getAnonymousId(request.cookies.get(anonymousUserIdKey)?.value);
if (anonymousId) {
await analytics.trackAndFlush({
anonymousId,
event: "Appointment Link Opened",
properties: {
companyId: 3,
recordId: 422,
},
});
}getDecryptedValue returns null for malformed or unsupported cookie values, and an object for the RudderStack cookies that hold one, so narrow it yourself when you reach for it directly. getAnonymousId already does that narrowing.
The Node SDK requires a string userId or anonymousId on every event. The package forwards identifiers unchanged. Delivery errors are propagated so the application can choose its own timeout and fail-open behavior.
flushAt defaults to 1. Long-lived Node processes can override any supported SDK option through clientOptions:
const analytics = createAnalytics({
clientOptions: { flushAt: 20 },
dataPlaneUrl: "YOUR_DATA_PLANE_URL",
writeKey: "YOUR_WRITE_KEY",
});5. Wrap your app with AnalyticsContext
Provide your RudderStack credentials:
import { AnalyticsContext } from "@bbcd0/analytics";
export default function App() {
return (
<AnalyticsContext
value={{
writeKey: "YOUR_WRITE_KEY",
dataPlaneUrl: "YOUR_DATA_PLANE_URL",
source: {
id: "YOUR_SOURCE_ID",
name: "YOUR_SOURCE_NAME",
workspaceId: "YOUR_WORKSPACE_ID",
},
}}
>
<YourApp />
</AnalyticsContext>
);
}6. Use the useAnalytics hook
import { useAnalytics } from "@bbcd0/analytics";
function MyComponent() {
const analytics = useAnalytics();
const handleClick = () => {
analytics?.track("Button Clicked", {
buttonId: "my-button",
});
};
return <button onClick={handleClick}>Click me</button>;
}Configuration
| Prop | Type | Required | Description |
| -------------------------- | --------- | -------- | ----------------------------------------------------------------------------------------- |
| value | object | Yes | Object containing all configuration options |
| value.writeKey | string | Yes | Your RudderStack write key |
| value.dataPlaneUrl | string | Yes | Your RudderStack data plane URL |
| value.source | object | Yes | Source configuration object |
| value.source.id | string | Yes | RudderStack source ID |
| value.source.name | string | Yes | RudderStack source name |
| value.source.workspaceId | string | Yes | RudderStack workspace ID |
| value.enabled | boolean | No | Explicitly enable/disable analytics. Defaults to true in production, false otherwise. |
Development vs Production
Analytics are automatically disabled in non-production environments. To override this:
<AnalyticsContext
value={{
writeKey: "YOUR_WRITE_KEY",
dataPlaneUrl: "YOUR_DATA_PLANE_URL",
source: {
id: "YOUR_SOURCE_ID",
name: "YOUR_SOURCE_NAME",
workspaceId: "YOUR_WORKSPACE_ID",
},
enabled: true, // Force enable in development
}}
>
<YourApp />
</AnalyticsContext>