@welytics/next-rudder-tracker
v1.0.7
Published
Next.js integration for RudderTracker - privacy-first analytics
Maintainers
Readme
@welytics/next-rudder-tracker
🚀 Easy Next.js integration for RudderTracker - Privacy-first analytics made simple.
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
useAnalyticshook - 🔗 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-tracker2. 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=trueThen 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
- Check initialization:
const { isInitialized } = useAnalytics();
console.log('Analytics initialized:', isInitialized);- Enable debug mode:
<Analytics
siteId="your-site-id"
endpoint="https://api.yourdomain.com"
debug={true}
/>- Verify environment variables:
echo $NEXT_PUBLIC_RUDDER_SITE_ID
echo $NEXT_PUBLIC_RUDDER_ENDPOINTCommon 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
Analytics- Main analytics componentAnalyticsProvider- Context providerTrackingLink- Link with automatic tracking
Hooks
useAnalytics- Manual tracking hookuseAnalyticsContext- Access provider context
License
MIT © Welytics
Contributing
We welcome contributions! Please see our Contributing Guide for details.
