npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@codeswayam/analytics

v0.1.5

Published

Centralized analytics and tracking for CodeSwayam apps

Downloads

567

Readme

@codeswayam/analytics

npm version License: MIT TypeScript React 19 Bundle size

Centralized analytics and event tracking for all CodeSwayam applications. Drop-in React component for automatic page views with support for custom events and server-side tracking.


Table of Contents


Overview

@codeswayam/analytics is the single analytics integration layer for the entire CodeSwayam platform. Rather than each app implementing its own tracking setup, this package provides:

  • A zero-config <Analytics /> component — automatically tracks page views on route changes
  • Custom event tracking functions for user actions and feature usage
  • Server-side tracking utilities for SSR apps (Next.js App Router server components, API routes)
  • React 19 compatible with no deprecated APIs

The package is intentionally lightweight, with the analytics provider configuration centralized in this package so all apps stay in sync.


Installation

# npm
npm install @codeswayam/analytics

# yarn
yarn add @codeswayam/analytics

# pnpm
pnpm add @codeswayam/analytics

Peer Dependencies

| Dependency | Version | Purpose | |---|---|---| | react | ^18.0.0 \|\| ^19.0.0 | React runtime (for <Analytics /> component) | | react-dom | ^18.0.0 \|\| ^19.0.0 | DOM bindings | | next | ^14.0.0 \|\| ^15.0.0 | Required only for Next.js router integration |

Install required peer dependencies:

npm install react react-dom

Architecture

packages/analytics/src/
├── index.tsx     — Main exports: Analytics component + client tracking functions
├── Analytics.tsx — React component: automatic page view tracking (5.7 KB)
└── server.ts     — Server-side tracking utilities (1.5 KB)

Entry points:

| Import Path | Contents | |---|---| | @codeswayam/analytics | <Analytics /> component + client-side event tracking | | @codeswayam/analytics/server | Server-side tracking utilities (Node.js only) |


API Reference

Analytics Component

import { Analytics } from '@codeswayam/analytics';

A React component that initializes the analytics provider and automatically fires a page view event on every route change.

| Prop | Type | Required | Default | Description | |---|---|---|---|---| | debug | boolean | ❌ | false | Log all tracked events to the console | | disabled | boolean | ❌ | false | Disable all tracking (useful for test/CI environments) |

Renders nothing to the DOM. Place it once in your root layout — it handles everything automatically.


Client-Side Tracking

Imported from @codeswayam/analytics:

trackEvent(name, properties?)

Track a custom user action or feature interaction.

| Parameter | Type | Required | Description | |---|---|---|---| | name | string | ✅ | Event name (e.g., 'agent_created', 'workflow_run') | | properties | Record<string, unknown> | ❌ | Additional key-value metadata for the event |

trackPageView(url?)

Manually fire a page view event. The <Analytics /> component calls this automatically on route changes — use this only when you need manual control.

| Parameter | Type | Required | Description | |---|---|---|---| | url | string | ❌ | Page URL (defaults to window.location.href) |

identify(userId, traits?)

Associate subsequent events with a specific user identity.

| Parameter | Type | Required | Description | |---|---|---|---| | userId | string | ✅ | Your internal user ID | | traits | Record<string, unknown> | ❌ | User attributes (name, email, plan, etc.) |


Server-Side Tracking

Import from @codeswayam/analytics/server in server components, API routes, or middleware:

import { trackServerEvent, trackServerPageView } from '@codeswayam/analytics/server';

trackServerEvent(name, properties?, context?)

Track an event from a server context (API route, server action, middleware).

| Parameter | Type | Required | Description | |---|---|---|---| | name | string | ✅ | Event name | | properties | Record<string, unknown> | ❌ | Event metadata | | context | ServerTrackingContext | ❌ | Request context (userId, IP, user-agent) |

Returns Promise<void>.

trackServerPageView(url, context?)

Track a server-rendered page view (e.g., from middleware or a server component).

| Parameter | Type | Required | Description | |---|---|---|---| | url | string | ✅ | The page URL | | context | ServerTrackingContext | ❌ | Request context |

Returns Promise<void>.


TypeScript Types

// Props for the <Analytics /> component
interface AnalyticsProps {
  debug?: boolean;
  disabled?: boolean;
}

// Custom event tracking
interface TrackEventOptions {
  name: string;
  properties?: Record<string, unknown>;
}

// Server-side context
interface ServerTrackingContext {
  userId?: string;
  anonymousId?: string;
  ip?: string;
  userAgent?: string;
  referrer?: string;
}

// Page view
interface PageViewEvent {
  url: string;
  referrer?: string;
  title?: string;
}

Code Examples

1. Installation

npm install @codeswayam/analytics

For Next.js projects with server-side tracking:

npm install @codeswayam/analytics react react-dom

2. App Layout Integration (<Analytics />)

Add <Analytics /> once to your root layout. It fires page views automatically on every navigation.

Next.js App Router (app/layout.tsx):

import { Analytics } from '@codeswayam/analytics';
import type { ReactNode } from 'react';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        {/* Analytics component — renders nothing, tracks automatically */}
        <Analytics />
      </body>
    </html>
  );
}

Next.js Pages Router (pages/_app.tsx):

import { Analytics } from '@codeswayam/analytics';
import type { AppProps } from 'next/app';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <Analytics />
    </>
  );
}

Vite / React SPA (src/main.tsx):

import { Analytics } from '@codeswayam/analytics';
import { BrowserRouter } from 'react-router-dom';
import { App } from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <BrowserRouter>
    <App />
    <Analytics />
  </BrowserRouter>,
);

3. Custom Event Tracking

Track meaningful user actions throughout your application:

import { trackEvent } from '@codeswayam/analytics';

// Track when a user creates an agent
async function handleCreateAgent(formData: CreateAgentFormData) {
  const agent = await apiClient.agents.create(formData);

  trackEvent('agent_created', {
    agentId: agent.id,
    agentName: agent.name,
    model: agent.model,
  });

  return agent;
}

// Track feature usage
function handleWorkflowRun(workflowId: string) {
  trackEvent('workflow_run_started', {
    workflowId,
    source: 'dashboard',
  });
}

// Track subscription events
function handleUpgrade(plan: string) {
  trackEvent('plan_upgrade_clicked', {
    targetPlan: plan,
    currentPlan: user.plan,
  });
}

// Track errors
function handleApiError(error: Error, context: string) {
  trackEvent('api_error', {
    errorMessage: error.message,
    context,
    timestamp: new Date().toISOString(),
  });
}

4. Server-Side Tracking

Use server-side utilities in Next.js API routes, server actions, or middleware:

Next.js API Route (app/api/agents/route.ts):

import { trackServerEvent } from '@codeswayam/analytics/server';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(req: NextRequest) {
  const body = await req.json();
  const userId = req.headers.get('x-user-id') ?? undefined;

  // Create the agent
  const agent = await db.agents.create(body);

  // Track on the server (no client-side JS needed)
  await trackServerEvent('agent_created', {
    agentId: agent.id,
    model: agent.model,
  }, {
    userId,
    ip: req.ip,
    userAgent: req.headers.get('user-agent') ?? undefined,
  });

  return NextResponse.json(agent);
}

Next.js Server Action (app/actions/billing.ts):

'use server';

import { trackServerEvent } from '@codeswayam/analytics/server';
import { auth } from '@/lib/auth';

export async function upgradePlan(planId: string) {
  const session = await auth();

  // Process the upgrade
  const result = await billing.upgrade(session.user.id, planId);

  // Track from the server
  await trackServerEvent('subscription_upgraded', {
    planId,
    userId: session.user.id,
    previousPlan: session.user.plan,
  }, {
    userId: session.user.id,
  });

  return result;
}

Next.js Middleware (middleware.ts):

import { trackServerPageView } from '@codeswayam/analytics/server';
import { type NextRequest, NextResponse } from 'next/server';

export async function middleware(req: NextRequest) {
  // Track server-side page views for SSR accuracy
  await trackServerPageView(req.nextUrl.pathname, {
    userAgent: req.headers.get('user-agent') ?? undefined,
    referrer: req.headers.get('referer') ?? undefined,
  });

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

5. User Identification

Identify users after authentication to associate events with specific accounts:

import { identify } from '@codeswayam/analytics';

// After successful login
async function handleLoginSuccess(user: User) {
  identify(user.id, {
    name: user.name,
    email: user.email,
    plan: user.subscription.plan,
    company: user.organization?.name,
    createdAt: user.createdAt,
  });
}

// After signup
async function handleSignupSuccess(user: User) {
  identify(user.id, {
    name: user.name,
    email: user.email,
    plan: 'trial',
    signupSource: user.referralSource,
  });

  trackEvent('signup_completed', {
    method: 'email',
    referralSource: user.referralSource,
  });
}

// On logout — reset identity
async function handleSignOut() {
  // No explicit reset needed; next session will create a new anonymous ID
  await signOut();
}

6. Debug Mode

Enable debug mode during development to log all events to the browser console:

// Only enable in development
<Analytics debug={process.env.NODE_ENV === 'development'} />

Console output in debug mode:

[Analytics] page_view { url: '/dashboard', referrer: '/login', title: 'Dashboard' }
[Analytics] agent_created { agentId: 'agent_123', model: 'gpt-4o' }
[Analytics] workflow_run_started { workflowId: 'wf_456', source: 'dashboard' }

7. Disabling in Test Environments

Prevent analytics events from firing during automated tests:

// Disable analytics in test environments
<Analytics disabled={process.env.NODE_ENV === 'test'} />

Or with an environment variable:

<Analytics disabled={process.env.NEXT_PUBLIC_ANALYTICS_DISABLED === 'true'} />

Integration Guide

Next.js App Router (Recommended)

  1. Install the package
  2. Add <Analytics /> to app/layout.tsx
  3. Import server utilities from @codeswayam/analytics/server in server files
  4. Call trackEvent() in client components and trackServerEvent() in server code

Next.js Pages Router

  1. Install the package
  2. Add <Analytics /> to pages/_app.tsx
  3. Call trackEvent() in any client-side component or page

Vite / Create React App

  1. Install the package
  2. Add <Analytics /> near the root of your component tree (inside your router)
  3. Call trackEvent() anywhere in client code

Environment Variables

The package reads the following optional environment variables:

| Variable | Description | |---|---| | NEXT_PUBLIC_ANALYTICS_WRITE_KEY | Analytics provider write key (client-side) | | ANALYTICS_WRITE_KEY | Analytics provider write key (server-side) |


Compatibility Matrix

| Environment | Supported | Notes | |---|---|---| | React 18.x | ✅ | Full support | | React 19.x | ✅ | Full support — no deprecated APIs used | | Next.js 14 (App Router) | ✅ | Client + server tracking | | Next.js 14 (Pages Router) | ✅ | Client tracking | | Next.js 15 | ✅ | Full support | | Vite (React) | ✅ | Client tracking | | Remix | ✅ | Client tracking; use server utilities in loaders/actions | | Node.js 18.x | ✅ | Server-side tracking | | Node.js 20.x | ✅ | Server-side tracking (recommended) | | Edge Runtime | ✅ | Server-side utilities work in edge functions | | TypeScript 4.x | ✅ | Minimum supported | | TypeScript 5.x | ✅ | Recommended | | SSR | ✅ | Server utilities designed for SSR | | CJS | ✅ | CommonJS supported | | ESM | ✅ | ES modules supported |


Changelog

v0.1.5

  • Optimized client-side pageview tracking debounce and React 19 forward-compatibility.

License

MIT © CodeSwayam