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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@welytics/next-rudder-tracker

v1.0.7

Published

Next.js integration for RudderTracker - privacy-first analytics

Readme

@welytics/next-rudder-tracker

🚀 Easy Next.js integration for RudderTracker - Privacy-first analytics made simple.

NPM Version License: MIT

Features

  • 🔧 Zero Configuration - Works out of the box with sensible defaults
  • Next.js Optimized - Built specifically for Next.js App Router and Pages Router
  • 🛡️ Privacy First - GDPR compliant, respects Do Not Track
  • 📱 SPA Ready - Automatic page view tracking for client-side navigation
  • 🎯 TypeScript - Full TypeScript support with detailed types
  • 🪝 React Hooks - Easy manual tracking with useAnalytics hook
  • 🔗 Smart Components - Pre-built components like TrackingLink

Quick Start

1. Installation

npm install @welytics/next-rudder-tracker
# or
yarn add @welytics/next-rudder-tracker
# or
pnpm add @welytics/next-rudder-tracker

2. Basic Setup

App Router (Next.js 13+)

// app/layout.tsx
import { Analytics } from '@welytics/next-rudder-tracker';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        {children}

        {/* Add analytics to the bottom of your layout */}
        <Analytics
          siteId="your-site-id"
          endpoint="https://api.yourdomain.com"
        />
      </body>
    </html>
  );
}

Pages Router (Next.js 12 and below)

// pages/_app.tsx
import type { AppProps } from 'next/app';
import { Analytics } from '@welytics/next-rudder-tracker';

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

      {/* Add analytics to your app */}
      <Analytics
        siteId="your-site-id"
        endpoint="https://api.yourdomain.com"
      />
    </>
  );
}

That's it! 🎉 Your Next.js app now has privacy-first analytics with automatic page view tracking.

Configuration

Analytics Component Props

interface AnalyticsProps {
  siteId: string;           // Required: Your site ID
  endpoint: string;         // Required: RudderTracker API endpoint
  trackPageViews?: boolean; // Auto track page views (default: true)
  respectDNT?: boolean;     // Respect Do Not Track (default: true)
  enableSPA?: boolean;      // Enable SPA mode (default: true)
  debug?: boolean;          // Debug mode (default: false)
  productionOnly?: boolean; // Only load in production (default: false)
  config?: Partial<RudderConfig>; // Additional RudderTracker config
}

Environment Variables

Create a .env.local file:

NEXT_PUBLIC_RUDDER_SITE_ID=your-site-id
NEXT_PUBLIC_RUDDER_ENDPOINT=https://api.yourdomain.com
NEXT_PUBLIC_ENABLE_ANALYTICS=true

Then use in your layout:

import { Analytics } from '@welytics/next-rudder-tracker';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        {process.env.NEXT_PUBLIC_ENABLE_ANALYTICS && (
          <Analytics
            siteId={process.env.NEXT_PUBLIC_RUDDER_SITE_ID!}
            endpoint={process.env.NEXT_PUBLIC_RUDDER_ENDPOINT!}
            productionOnly={true}
          />
        )}
      </body>
    </html>
  );
}

Manual Event Tracking

Use the useAnalytics hook for custom event tracking:

'use client';
import { useAnalytics } from '@welytics/next-rudder-tracker';

export default function ContactForm() {
  const { track, trackPageView, isInitialized } = useAnalytics();

  const handleSubmit = (formData) => {
    // Track custom events
    track('form_submission', {
      form_name: 'contact',
      form_type: 'lead_generation',
      user_type: 'visitor'
    });
  };

  const handleViewProduct = (productId) => {
    track('product_viewed', {
      product_id: productId,
      category: 'electronics',
      source: 'search_results'
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="email" type="email" required />
      <button type="submit">Submit</button>
    </form>
  );
}

Advanced Components

AnalyticsProvider

For more control, use the provider pattern:

// app/layout.tsx
import { AnalyticsProvider } from '@welytics/next-rudder-tracker';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <AnalyticsProvider
          siteId="your-site-id"
          endpoint="https://api.yourdomain.com"
          productionOnly={true}
        >
          {children}
        </AnalyticsProvider>
      </body>
    </html>
  );
}

TrackingLink

Automatically track link clicks:

import { TrackingLink } from '@welytics/next-rudder-tracker';

export default function Navigation() {
  return (
    <nav>
      <TrackingLink
        href="/products"
        eventName="nav_click"
        eventProperties={{ location: 'header', destination: 'products' }}
      >
        Products
      </TrackingLink>

      <TrackingLink
        href="/contact"
        eventName="cta_click"
        eventProperties={{ type: 'contact', position: 'nav' }}
      >
        Contact Us
      </TrackingLink>
    </nav>
  );
}

Common Use Cases

E-commerce Tracking

'use client';
import { useAnalytics } from '@welytics/next-rudder-tracker';

export default function ProductPage({ product }) {
  const { track } = useAnalytics();

  const handleAddToCart = () => {
    track('add_to_cart', {
      product_id: product.id,
      product_name: product.name,
      price: product.price,
      currency: 'USD',
      category: product.category
    });
  };

  const handlePurchase = (orderData) => {
    track('purchase', {
      transaction_id: orderData.id,
      value: orderData.total,
      currency: 'USD',
      items: orderData.items
    });
  };

  return (
    <div>
      <h1>{product.name}</h1>
      <button onClick={handleAddToCart}>Add to Cart</button>
    </div>
  );
}

Newsletter Signup

'use client';
import { useAnalytics } from '@welytics/next-rudder-tracker';

export default function Newsletter() {
  const { track } = useAnalytics();

  const handleSignup = (email) => {
    track('newsletter_signup', {
      email_domain: email.split('@')[1],
      source: 'footer',
      timestamp: new Date().toISOString()
    });
  };

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      const formData = new FormData(e.target);
      handleSignup(formData.get('email'));
    }}>
      <input name="email" type="email" placeholder="Enter email" />
      <button type="submit">Subscribe</button>
    </form>
  );
}

Page Performance Tracking

'use client';
import { useAnalytics } from '@welytics/next-rudder-tracker';
import { useEffect } from 'react';

export default function PerformanceTracker() {
  const { track } = useAnalytics();

  useEffect(() => {
    // Track page load performance
    if (typeof window !== 'undefined' && window.performance) {
      const navigation = window.performance.getEntriesByType('navigation')[0];

      track('page_performance', {
        load_time: navigation.loadEventEnd - navigation.loadEventStart,
        dom_ready: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart,
        page_url: window.location.pathname
      });
    }
  }, [track]);

  return null;
}

TypeScript Support

Full TypeScript support with detailed type definitions:

import type {
  AnalyticsProps,
  UseAnalyticsReturn,
  TrackingEvent,
  RudderConfig
} from '@welytics/next-rudder-tracker';

// Custom analytics wrapper
const createAnalytics = (config: AnalyticsProps): JSX.Element => {
  return <Analytics {...config} />;
};

// Typed event tracking
const trackTypedEvent = (analytics: UseAnalyticsReturn) => {
  analytics.track('custom_event', {
    user_id: 'user123',
    action: 'click',
    timestamp: Date.now()
  });
};

Best Practices

1. Environment-Based Loading

// Only load analytics in production
<Analytics
  siteId="your-site-id"
  endpoint="https://api.yourdomain.com"
  productionOnly={true}
/>

2. Error Boundaries

import { ErrorBoundary } from 'react-error-boundary';

<ErrorBoundary fallback={<div>Analytics Error</div>}>
  <Analytics siteId="your-site-id" endpoint="https://api.yourdomain.com" />
</ErrorBoundary>

3. Conditional Tracking

const { track } = useAnalytics();

const handleEvent = () => {
  // Only track for authenticated users
  if (user?.isAuthenticated) {
    track('authenticated_action', { user_id: user.id });
  }
};

Privacy & GDPR

This package is built with privacy in mind:

  • No Cookies - Session-based tracking only
  • IP Anonymization - Automatic IP address anonymization
  • DNT Respect - Respects browser Do Not Track settings
  • No Personal Data - No user identification by default
  • GDPR Compliant - Built for privacy-first analytics

Troubleshooting

Analytics Not Tracking

  1. Check initialization:
const { isInitialized } = useAnalytics();
console.log('Analytics initialized:', isInitialized);
  1. Enable debug mode:
<Analytics
  siteId="your-site-id"
  endpoint="https://api.yourdomain.com"
  debug={true}
/>
  1. Verify environment variables:
echo $NEXT_PUBLIC_RUDDER_SITE_ID
echo $NEXT_PUBLIC_RUDDER_ENDPOINT

Common Issues

Q: "RudderTracker not available" error A: This is a module resolution issue. The package handles this automatically with:

import * as RudderTrackerModule from "@welytics/rudder-tracker";
const RudderTracker = RudderTrackerModule.default || RudderTrackerModule;

Q: Events not tracking in development A: Set productionOnly={false} or use production build

Q: Page views not working with Next.js routing A: Ensure enableSPA={true} (default) and Analytics is in layout

Q: Module import errors A: If you encounter import issues, try this pattern:

"use client";
import { useEffect } from "react";
import * as RudderTrackerModule from "@welytics/rudder-tracker";

const RudderTracker = RudderTrackerModule.default || RudderTrackerModule;

// Then use RudderTracker normally
RudderTracker.init({ ... });

Q: TypeScript errors A: Install @types/react and ensure proper imports

API Reference

Components

Hooks

License

MIT © Welytics

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Support