AnalyticsProvider
The AnalyticsProvider component initializes and configures the analytics context for your application. It must wrap your application at the root level to enable analytics tracking throughout your component tree.
Installation
npm install @54vie/analytics
# or
yarn add @54vie/analytics
Basic Usage
import { AnalyticsProvider } from '@54vie/analytics';
function App() {
return (
<AnalyticsProvider
apiKey="your-api-key"
projectId="your-project-id"
>
<YourApp />
</AnalyticsProvider>
);
}
TypeScript Interfaces
interface AnalyticsProviderProps {
/**
* Your 54Vie Analytics API key
* @required
*/
apiKey: string;
/**
* Your project identifier
* @required
*/
projectId: string;
/**
* Optional configuration options
*/
config?: AnalyticsConfig;
/**
* Child components that will have access to analytics context
*/
children: React.ReactNode;
}
interface AnalyticsConfig {
/**
* Enable debug mode for development
* @default false
*/
debug?: boolean;
/**
* Custom API endpoint URL
* @default 'https://api.54vie.com/v1/analytics'
*/
endpoint?: string;
/**
* Flush events after this many milliseconds
* @default 10000
*/
flushInterval?: number;
/**
* Maximum number of events to batch before flushing
* @default 20
*/
batchSize?: number;
/**
* Enable automatic page view tracking
* @default true
*/
autoTrackPageViews?: boolean;
/**
* Enable automatic session tracking
* @default true
*/
autoTrackSessions?: boolean;
/**
* Custom session timeout in milliseconds
* @default 1800000 (30 minutes)
*/
sessionTimeout?: number;
/**
* Respect user's Do Not Track browser setting
* @default true
*/
respectDoNotTrack?: boolean;
/**
* Storage mechanism for persisting data
* @default 'localStorage'
*/
storage?: 'localStorage' | 'sessionStorage' | 'memory' | 'none';
/**
* Cookie domain for cross-subdomain tracking
*/
cookieDomain?: string;
/**
* Enable secure cookies (HTTPS only)
* @default true in production
*/
secureCookies?: boolean;
/**
* Custom user ID resolver function
*/
userIdResolver?: () => string | null | Promise<string | null>;
/**
* Event enrichment middleware
*/
middleware?: AnalyticsMiddleware[];
/**
* Sampling rate for events (0.0 to 1.0)
* @default 1.0
*/
samplingRate?: number;
/**
* Retry failed requests
* @default true
*/
retryOnFailure?: boolean;
/**
* Maximum retry attempts
* @default 3
*/
maxRetries?: number;
}
interface AnalyticsMiddleware {
/**
* Unique identifier for the middleware
*/
name: string;
/**
* Process and optionally modify events before sending
* Return null to drop the event
*/
process: (event: AnalyticsEvent) => AnalyticsEvent | null | Promise<AnalyticsEvent | null>;
}
interface AnalyticsEvent {
name: string;
properties?: Record<string, unknown>;
timestamp?: number;
userId?: string;
sessionId?: string;
metadata?: Record<string, unknown>;
}
Configuration Examples
Development Configuration
import { AnalyticsProvider } from '@54vie/analytics';
function App() {
return (
<AnalyticsProvider
apiKey={process.env.REACT_APP_ANALYTICS_KEY!}
projectId={process.env.REACT_APP_PROJECT_ID!}
config={{
debug: process.env.NODE_ENV === 'development',
autoTrackPageViews: true,
flushInterval: 5000,
}}
>
<YourApp />
</AnalyticsProvider>
);
}
Production Configuration with Custom Settings
import { AnalyticsProvider } from '@54vie/analytics';
function App() {
return (
<AnalyticsProvider
apiKey={process.env.REACT_APP_ANALYTICS_KEY!}
projectId={process.env.REACT_APP_PROJECT_ID!}
config={{
debug: false,
endpoint: 'https://custom-analytics.yourcompany.com/v1',
flushInterval: 15000,
batchSize: 50,
autoTrackPageViews: true,
autoTrackSessions: true,
sessionTimeout: 3600000, // 1 hour
respectDoNotTrack: true,
storage: 'localStorage',
cookieDomain: '.yourcompany.com',
secureCookies: true,
samplingRate: 1.0,
retryOnFailure: true,
maxRetries: 5,
}}
>
<YourApp />
</AnalyticsProvider>
);
}
With Custom User ID Resolver
import { AnalyticsProvider } from '@54vie/analytics';
import { useAuth } from './auth';
function App() {
const { user } = useAuth();
return (
<AnalyticsProvider
apiKey="your-api-key"
projectId="your-project-id"
config={{
userIdResolver: async () => {
// Return user ID from your auth system
return user?.id ?? null;
},
}}
>
<YourApp />
</AnalyticsProvider>
);
}
With Event Middleware
import { AnalyticsProvider, AnalyticsMiddleware } from '@54vie/analytics';
const enrichmentMiddleware: AnalyticsMiddleware = {
name: 'enrichment',
process: (event) => ({
...event,
properties: {
...event.properties,
appVersion: '2.1.0',
environment: process.env.NODE_ENV,
},
}),
};
const filterMiddleware: AnalyticsMiddleware = {
name: 'filter',
process: (event) => {
// Drop internal debug events in production
if (event.name.startsWith('debug_') && process.env.NODE_ENV === 'production') {
return null;
}
return event;
},
};
function App() {
return (
<AnalyticsProvider
apiKey="your-api-key"
projectId="your-project-id"
config={{
middleware: [enrichmentMiddleware, filterMiddleware],
}}
>
<YourApp />
</AnalyticsProvider>
);
}
Server-Side Rendering (Next.js)
// app/providers.tsx
'use client';
import { AnalyticsProvider } from '@54vie/analytics';
export function Providers({ children }: { children: React.ReactNode }) {
return (
<AnalyticsProvider
apiKey={process.env.NEXT_PUBLIC_ANALYTICS_KEY!}
projectId={process.env.NEXT_PUBLIC_PROJECT_ID!}
config={{
storage: typeof window === 'undefined' ? 'memory' : 'localStorage',
}}
>
{children}
</AnalyticsProvider>
);
}
Context Value
The provider exposes the following context value to child components:
interface AnalyticsContextValue {
/**
* Track a custom event
*/
track: (eventName: string, properties?: Record<string, unknown>) => void;
/**
* Identify a user
*/
identify: (userId: string, traits?: Record<string, unknown>) => void;
/**
* Set user properties
*/
setUserProperties: (properties: Record<string, unknown>) => void;
/**
* Reset user identity (for logout)
*/
reset: () => void;
/**
* Manually flush queued events
*/
flush: () => Promise<void>;
/**
* Check if analytics is ready
*/
isReady: boolean;
/**
* Check if user has opted out
*/
isOptedOut: boolean;
/**
* Opt out of analytics tracking
*/
optOut: () => void;
/**
* Opt back in to analytics tracking
*/
optIn: () => void;
}
Error Handling
import { AnalyticsProvider, AnalyticsErrorBoundary } from '@54vie/analytics';
function App() {
return (
<AnalyticsErrorBoundary
onError={(error) => {
console.error('Analytics error:', error);
// Report to error tracking service
}}
fallback={<YourApp />} // App continues working if analytics fails
>
<AnalyticsProvider
apiKey="your-api-key"
projectId="your-project-id"
>
<YourApp />
</AnalyticsProvider>
</AnalyticsErrorBoundary>
);
}
Related
- Hooks - useAnalytics, useUserProperties, useExperiment
- Events - StandardEvents and custom event tracking
- Experiments - A/B testing and feature flags