@optic7409/resolvo-analytics
Version:
Simplified analytics client library for Next.js with automatic SSR handling, one-line integration, and comprehensive tracking
298 lines (229 loc) • 8.7 kB
Markdown
# @resolvo/analytics
A powerful analytics client library for connecting Next.js applications to the Resolvo Analytics API. Built with TypeScript and designed for seamless integration with React and Tailwind CSS.
## Features
- 🚀 **Next.js Optimized**: Built specifically for Next.js applications with App Router support
- 📊 **Comprehensive Tracking**: Page views, custom events, clicks, forms, and user interactions
- 🔄 **Offline Support**: Event queuing and retry mechanisms for reliable data collection
- 🎯 **TypeScript First**: Full type safety and IntelliSense support
- 🎨 **Tailwind Ready**: Pre-styled components that work with your design system
- ⚡ **Performance Focused**: Minimal bundle size and optimized for speed
- 🔒 **Privacy Compliant**: Configurable tracking with user consent management
- 🛡️ **SSR Safe**: Automatic server-side rendering detection and handling
- 🔧 **Auto-Detection**: Automatically detects Next.js environment and router type
## Installation
```bash
npm install @resolvo/analytics
# or
yarn add @resolvo/analytics
```
## Environment Setup
Add these environment variables to your `.env.local` file:
```bash
# Required: Your API key (server-side secret)
NEXT_PUBLIC_RESOLVO_API_KEY=your-api-key
# Required: Your website token (client-side safe)
NEXT_PUBLIC_RESOLVO_WEBSITE_TOKEN=your-website-token
# Optional: Custom API endpoint
NEXT_PUBLIC_RESOLVO_API_URL=https://www.resolvo.com/api/v1/analytics
```
### Token Management
- **API Key**: Server-side secret for API access control
- **Website Token**: Client-side token unique to your website/domain
- Both tokens are required for all analytics requests
- Website tokens are safe to expose in client-side code
## Quick Start (Super Simple!)
### One-Line Integration (RECOMMENDED) 🚀
Just add one component and you're done!
```tsx
// pages/_app.tsx or app/layout.tsx
import { ResolvoAnalytics } from '@resolvo/analytics';
export default function App({ Component, pageProps }) {
return (
<>
{/* Simple one-line integration - automatically handles everything */}
<ResolvoAnalytics
apiKey={process.env.NEXT_PUBLIC_RESOLVO_API_KEY || ''}
websiteToken={process.env.NEXT_PUBLIC_RESOLVO_WEBSITE_TOKEN || ''}
debug={process.env.NODE_ENV === 'development'}
/>
<Component {...pageProps} />
</>
);
}
```
### Next.js App Router
```tsx
// app/layout.tsx
import { ResolvoAnalytics } from '@resolvo/analytics';
export default function RootLayout({ children }) {
return (
<html>
<body>
<ResolvoAnalytics
apiKey={process.env.NEXT_PUBLIC_RESOLVO_API_KEY || ''}
websiteToken={process.env.NEXT_PUBLIC_RESOLVO_WEBSITE_TOKEN || ''}
debug={process.env.NODE_ENV === 'development'}
/>
{children}
</body>
</html>
);
}
```
### Using the Hook
```tsx
// Any component
import { useAnalytics } from '@resolvo/analytics';
export default function HomePage() {
const { track, identify, isReady } = useAnalytics();
const handleSignUp = async () => {
if (isReady) {
await track('signup_click', {
source: 'homepage',
timestamp: Date.now()
});
}
};
return (
<div>
<h1>Welcome to Our App</h1>
<button onClick={handleSignUp}>Sign Up</button>
</div>
);
}
```
## Advanced Usage
### Provider Pattern
For more control over analytics configuration:
```tsx
import { ResolvoAnalytics } from '@resolvo/analytics';
export default function App({ Component, pageProps }) {
return (
<ResolvoAnalytics
apiKey={process.env.NEXT_PUBLIC_RESOLVO_API_KEY || ''}
websiteToken={process.env.NEXT_PUBLIC_RESOLVO_WEBSITE_TOKEN || ''}
debug={process.env.NODE_ENV === 'development'}
autoTrackPages={true}
autoTrackClicks={true}
autoTrackForms={true}
>
<Component {...pageProps} />
</ResolvoAnalytics>
);
}
```
### Manual Tracking
```tsx
import { useAnalytics } from '@resolvo/analytics';
export function CustomComponent() {
const { track, identify } = useAnalytics();
const handleCustomAction = () => {
track('custom_action', {
component: 'CustomComponent',
action: 'button_click'
});
};
const handleUserLogin = (userId: string) => {
identify(userId, {
email: 'user@example.com',
plan: 'premium'
});
};
return (
<div>
<button onClick={handleCustomAction}>Custom Action</button>
<button onClick={() => handleUserLogin('user-123')}>Login</button>
</div>
);
}
```
## Configuration Options
The `ResolvoAnalytics` component accepts the following props:
```tsx
interface ResolvoConfig {
apiKey: string; // Required: Your API key
websiteToken?: string; // Optional: Auto-detected from env
apiUrl?: string; // Optional: Custom API endpoint
debug?: boolean; // Optional: Enable debug mode
ssr?: boolean; // Optional: Enable SSR (default: false)
autoInitialize?: boolean; // Optional: Auto-initialize (default: true)
environment?: 'development' | 'production' | 'test';
autoTrackPages?: boolean; // Optional: Auto-track page views (default: true)
autoTrackClicks?: boolean; // Optional: Auto-track clicks (default: true)
autoTrackForms?: boolean; // Optional: Auto-track forms (default: true)
}
```
## Automatic Features
The package automatically:
- ✅ Detects Next.js environment and router type (App Router vs Pages Router)
- ✅ Handles SSR safely (no router mounting errors)
- ✅ Provides graceful error handling
- ✅ Auto-tracks page views and route changes
- ✅ Auto-tracks button clicks and form submissions
- ✅ Provides helpful debug messages in development
- ✅ Disables analytics in test environments
- ✅ Handles offline scenarios with event queuing
## Troubleshooting
### Common Issues
1. **"Missing API key" Error**
- Check that `NEXT_PUBLIC_RESOLVO_API_KEY` is set in your `.env.local`
- Restart your development server after adding environment variables
2. **"Invalid website token" Error**
- Verify `NEXT_PUBLIC_RESOLVO_WEBSITE_TOKEN` is correct
- Ensure the token was generated for your API key
3. **SSR Issues**
- The package handles SSR automatically
- Set `ssr={true}` only if you need server-side analytics
4. **Events Not Sending**
- Check browser console for errors
- Verify both tokens are set correctly
- Ensure API endpoint is accessible
### Debug Mode
Enable debug mode to see detailed logs:
```tsx
<ResolvoAnalytics
apiKey={process.env.NEXT_PUBLIC_RESOLVO_API_KEY || ''}
websiteToken={process.env.NEXT_PUBLIC_RESOLVO_WEBSITE_TOKEN || ''}
debug={true} // Enable debug mode
/>
```
## Migration from Previous Versions
If you're upgrading from a previous version:
1. **Replace complex setup with simple component:**
```tsx
// Old way
<PageTracker config={complexConfig} />
<AnalyticsTracker config={complexConfig}>
{children}
</AnalyticsTracker>
// New way
<ResolvoAnalytics apiKey="..." websiteToken="..." />
```
2. **Update environment variables:**
- Ensure both `NEXT_PUBLIC_RESOLVO_API_KEY` and `NEXT_PUBLIC_RESOLVO_WEBSITE_TOKEN` are set
3. **Remove manual SSR handling:**
- The package now handles SSR automatically
## API Reference
### Components
- `ResolvoAnalytics` - Main component for one-line integration
- `NextJsPageTracker` - Next.js specific page tracker
- `PagesPageTracker` - Pages Router specific tracker
### Hooks
- `useAnalytics()` - Main hook for tracking events
- `usePageTracking()` - Hook for page view tracking
### Methods
- `track(eventName, properties)` - Track custom events
- `identify(userId, properties)` - Identify users
- `trackPageView(url, title)` - Track page views
- `trackClick(element, text, url)` - Track click events
## Examples
See the `examples/` directory for complete implementation examples:
- `simple-usage.tsx` - Basic integration
- `nextjs-app-router.tsx` - Next.js App Router example
- `advanced-usage.tsx` - Advanced configuration
## Support
For support and questions:
1. Check the troubleshooting section above
2. Review the examples in the `examples/` directory
3. Check browser console for error messages
4. Contact Resolvo Analytics support with error details