frontend-observability
v1.0.3
Published
A comprehensive frontend observability package with Application Insights integration, web vitals tracking, and user engagement metrics
Downloads
10
Maintainers
Readme
Frontend Observability
A comprehensive frontend observability package that provides seamless integration with Azure Application Insights, including web vitals tracking, user engagement metrics, and session analytics.
Features
- Azure Application Insights Integration: Full integration with Application Insights for comprehensive monitoring
- Web Vitals Tracking: Automatic tracking of Core Web Vitals (CLS, INP, LCP, FCP, TTFB)
- Engagement Metrics: Track user interactions, scroll depth, and time on page
- Session Analytics: Monitor session duration and user behavior
- Intelligent Sampling: Flexible sampling configuration to reduce costs while maintaining data quality
- Critical Page Tracking: Ensure 100% tracking on your most important pages
- User ID Tracking: Automatic user ID inclusion in telemetry for better user journey analysis
- React Support: Built-in React plugin for SPA route tracking
- TypeScript Support: Fully typed for excellent developer experience
- Zero Configuration: Works out of the box with sensible defaults
Tracked Metrics
Web Vitals
The package automatically tracks the following Core Web Vitals:
- CLS (Cumulative Layout Shift): Visual stability
- INP (Interaction to Next Paint): Responsiveness
- LCP (Largest Contentful Paint): Loading performance
- FCP (First Contentful Paint): Initial render time
- TTFB (Time to First Byte): Server response time
Engagement Metrics
- TimeOnPage: Duration user spends on each page (includes page URL)
- ScrollDepth: Maximum scroll percentage reached
- ButtonClick: User button interactions with context (includes page URL)
- FormSubmit: Form submission events (includes formId, formName, page URL, and user ID if configured)
Session Metrics
- SessionDuration: Total session length
- NavigationType: How the user navigated to the page
Installation
npm install frontend-observabilityPeer Dependencies
This package requires the following peer dependencies:
npm install @microsoft/applicationinsights-web @microsoft/applicationinsights-react-js web-vitalsQuick Start
Basic Usage
import { initMetrics } from 'frontend-observability';
// Initialize with your Application Insights connection string
const metrics = initMetrics({
connectionString: 'YOUR_CONNECTION_STRING_HERE'
});React Application
import { initMetrics } from 'frontend-observability';
import { AppInsightsContext } from '@microsoft/applicationinsights-react-js';
// Initialize metrics
const metrics = initMetrics({
connectionString: 'YOUR_CONNECTION_STRING_HERE',
enableAutoRouteTracking: true,
enableWebVitals: true,
enableEngagementTracking: true,
enableSessionTracking: true
});
// Wrap your app with the context provider
function App() {
return (
<AppInsightsContext.Provider value={metrics.reactPlugin}>
<YourApp />
</AppInsightsContext.Provider>
);
}Configuration
Sampling Configuration (Cost Optimization)
Reduce telemetry costs while maintaining data quality with intelligent sampling:
The sampling strategy is client-side probabilistic sampling where consuming applications have complete control over what percentage of each metric type gets sent to Application Insights.
Sampling Configuration Options:
Sampling Rates: Package allows sampling rate customizations for each event type. By default, the sampling rate is set to 50% across all events types other than "form-submissions".
Always Tracked Events: Form-submission event types are always tracked and enriched with additional data (formName, page path, full URL, and userId if available via consuming product).
Always Tracked Pages: A customizable prop (critical pages) is added for applications to define pages where all user interactions are fully tracked 100% of the time. This is useful for sensitive pages such as those where permissions are granted, user subscribed to lists, etc. Metrics captured here include button clicks, scroll depth, time on page, and form submissions.
User Id for Tracked Events: UserId is expected from the consuming app and will be sent to App Insights as part of each tracked event.
Sampling Priorities
If sampling is disabled: 100% of user interactions are tracked.
If sampling is enabled:
- If the "criticalPages" prop is populated by the consuming application, all events in the given pages are tracked.
- If the "alwaysInclude" prop is populated by the consuming application, all instances of this event type are tracked.
- If the "eventRates" prop is populated by the consuming application, event-specific rates are evaluated to implement custom sampling rate per event.
- If no config options are provided, default sampling rate of 50% per event is implemented.
The Three Control Mechanisms
| Mechanism | Scope | Priority | Example | |---------------|---------------------------|-------------------------|--------------------------------------------------| | criticalPages | Page-based 100% override | High (checked first) | /checkout → 100% of ALL events on that page | | alwaysInclude | Event-based 100% override | Medium (checked second) | FormSubmit → 100% of form submissions everywhere | | eventRates | Per-event percentages | Low (checked last) | ButtonClick: 25 → 25% of button clicks |
Usage Example
import { initMetrics } from 'frontend-observability';
const metrics = initMetrics({
connectionString: 'YOUR_APP_INSIGHTS_CONNECTION_STRING',
userId: 'user-123', // User ID for tracking
sampling: {
enabled: true,
defaultRate: 50, // 50% overall sampling
eventRates: {
// Customize per event
WebVital_LCP: 100, // 100% of LCP events tracked
WebVital_INP: 100, // 100% of INP events tracked
WebVital_CLS: 75, // 75% of CLS events tracked
WebVital_FCP: 50, // 50% of FCP events tracked
ButtonClick: 10, // 10% of button clicks tracked
FormSubmit: 100, // Always tracked unless specified otherwise
TimeOnPage: 50, // 50% of time on page metrics
ScrollDepth: 25, // 25% of scroll depth
SessionDuration: 75, // 75% of session duration
},
// 100% tracking on these pages
criticalPages: [
'/checkout',
'/payment',
],
// Event Types that should always be captured
alwaysInclude: ['FormSubmit'],
},
});Best Practices
- Initialize Early: Call
initMetricsas early as possible in your application lifecycle - Use Environment Variables: Never hardcode connection strings in your source code
- Track User Actions: Use custom events to track important user interactions
- Error Tracking: Always wrap critical sections with try-catch and use
trackException
Browser Support
This package supports all modern browsers that support:
- ES2020
- Web Vitals API
- Application Insights SDK
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For issues and questions, please create an issue in the GitHub repository.
