Azure Application Insights Hook
Send feature flag telemetry to Azure Application Insights for monitoring, analytics, and diagnostics correlation.
Overview
The @ops-ai/toggly-appinsights-hook package automatically sends feature flag events and custom properties to Application Insights. This allows you to:
- Track feature flag evaluations as custom events
- Add feature flags as custom properties on all telemetry
- Correlate features with application behavior in Application Insights
- Set authenticated user context when identity changes
- Monitor real-time feature changes via custom events
- Analyze A/B test results using Application Insights analytics
Installation
$ npm i -s @ops-ai/toggly-appinsights-hook
Prerequisites
- Toggly SDK - Any JavaScript-based Toggly SDK with hooks support (v1.0.0+)
- Application Insights JavaScript SDK - Must be loaded on your page (
window.appInsights)
How It Works
The hook implements multiple lifecycle events:
| Hook | Application Insights Action |
|---|---|
afterEvaluation | Sends FeatureFlagEvaluated custom event via trackEvent() |
afterIdentify | Sets authenticated user via setAuthenticatedUserContext() |
afterRefresh | Sends FeatureFlagChanged event on state changes + updates telemetry properties |
Example evaluation event:
appInsights.trackEvent({
name: 'FeatureFlagEvaluated',
properties: {
feature_key: 'checkout-v2',
feature_enabled: 'true',
event_category: 'toggly'
}
});
Usage
Vanilla JavaScript
import { Toggly } from '@ops-ai/feature-flags-toggly';
import { AppInsightsHook } from '@ops-ai/toggly-appinsights-hook';
Toggly.init({
appKey: 'your-app-key',
environment: 'Production',
hooks: [
new AppInsightsHook({
trackEvaluations: true,
trackChanges: true,
setCustomProperties: true,
checkConsent: () => cookieConsent.analytics
})
]
});
React
import { createTogglyProvider } from '@ops-ai/react-feature-flags-toggly';
import { AppInsightsHook } from '@ops-ai/toggly-appinsights-hook';
const TogglyProvider = await createTogglyProvider({
appKey: 'your-app-key',
environment: 'Production',
hooks: [new AppInsightsHook({ setCustomProperties: true })]
});
Angular
import { provideToggly } from '@ops-ai/ngx-feature-flags-toggly';
import { AppInsightsHook } from '@ops-ai/toggly-appinsights-hook';
bootstrapApplication(AppComponent, {
providers: [
provideToggly({
appKey: 'your-app-key',
environment: 'Production',
hooks: [new AppInsightsHook({ setCustomProperties: true })]
})
]
});
Vue
import { createApp } from 'vue';
import { TogglyPlugin } from 'vue-feature-flags-toggly';
import { AppInsightsHook } from '@ops-ai/toggly-appinsights-hook';
app.use(TogglyPlugin, {
appKey: 'your-app-key',
environment: 'Production',
hooks: [new AppInsightsHook({ setCustomProperties: true })]
});
Svelte / Astro / Gatsby
import { Toggly } from '@ops-ai/feature-flags-toggly';
import { AppInsightsHook } from '@ops-ai/toggly-appinsights-hook';
Toggly.init({
appKey: 'your-app-key',
environment: 'Production',
hooks: [new AppInsightsHook({ setCustomProperties: true })]
});
Configuration
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable or disable the hook |
instrumentationKey | string | - | Instrumentation key (optional, uses global appInsights) |
evaluationEventName | string | "FeatureFlagEvaluated" | Custom event name for evaluations |
changeEventName | string | "FeatureFlagChanged" | Custom event name for changes |
trackEvaluations | boolean | true | Track feature flag evaluations |
trackAllResults | boolean | true | Track both true and false results |
setCustomProperties | boolean | false | Add feature flags as custom properties on all telemetry |
propertyPrefix | string | "feature_" | Prefix for property names |
trackChanges | boolean | true | Track real-time feature changes |
trackIdentity | boolean | true | Set authenticated user context |
customProperties | object | {} | Custom properties for all events |
customMeasurements | object | {} | Custom measurements for all events |
checkConsent | () => boolean | () => true | Consent callback called before each event |
debug | boolean | false | Enable debug logging |
Full Configuration Example
const appInsightsHook = new AppInsightsHook({
enabled: process.env.NODE_ENV === 'production',
evaluationEventName: 'FF_Evaluated',
changeEventName: 'FF_Changed',
trackEvaluations: true,
trackAllResults: true,
setCustomProperties: true,
propertyPrefix: 'feature_',
trackChanges: true,
trackIdentity: true,
customProperties: {
app_version: '2.0.0',
environment: 'production'
},
checkConsent: () => {
return window.cookieConsent?.analytics ?? false;
},
debug: false
});
Privacy & Consent (GDPR/CCPA)
The checkConsent callback integrates with consent management platforms:
// OneTrust
new AppInsightsHook({
checkConsent: () => window.OneTrust?.IsAlertBoxClosed() ?? false
});
// Simple cookie check
new AppInsightsHook({
checkConsent: () => document.cookie.includes('analytics_consent=true')
});
Only feature flag keys, evaluation results, optional custom properties, and (when enabled) user identity are sent. No automatic PII collection.
Viewing in Application Insights
- Go to Azure Portal → Application Insights resource → Logs
- Query custom events:
customEvents
| where name == "FeatureFlagEvaluated"
| extend feature_key = tostring(customDimensions.feature_key)
| extend feature_enabled = tostring(customDimensions.feature_enabled)
| summarize count() by feature_key, feature_enabled
| order by count_ desc
When setCustomProperties is enabled, feature flags appear as feature_* custom dimensions on all telemetry (page views, exceptions, requests, and more).
Error Handling
The hook never breaks the Toggly SDK:
- Application Insights API calls are wrapped in try-catch
- Missing appInsights is handled silently
- A console warning (not error) is shown if appInsights is not detected at initialization
- appInsights becoming available after initialization is handled automatically
Dynamic Management
// Add at runtime
Toggly.addHook(new AppInsightsHook({ setCustomProperties: true }));
// Remove by name
Toggly.removeHook('appinsights-hook');
Troubleshooting
Events not appearing
- Verify appInsights is loaded:
console.log(typeof window.appInsights !== 'undefined') - Check your connection string / instrumentation key
- Check your
checkConsentcallback returnstrue - Enable debug mode:
new AppInsightsHook({ debug: true }) - Allow a few minutes for Azure Portal ingestion delay
Console warning at startup
The warning "Application Insights SDK not detected" means appInsights was not loaded when the hook was created. The hook will start sending events once appInsights becomes available.
Custom properties not appearing
- Property names are sanitized (special characters → underscores)
- Property names are truncated to 150 characters (Application Insights limit)
- Ensure
setCustomPropertiesistrue
Performance
- Overhead: <0.1ms per evaluation
- Bundle size: ~2KB minified
- Uses Application Insights' internal batching