Skip to main content

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​

  1. Toggly SDK - Any JavaScript-based Toggly SDK with hooks support (v1.0.0+)
  2. Application Insights JavaScript SDK - Must be loaded on your page (window.appInsights)

How It Works​

The hook implements multiple lifecycle events:

HookApplication Insights Action
afterEvaluationSends FeatureFlagEvaluated custom event via trackEvent()
afterIdentifySets authenticated user via setAuthenticatedUserContext()
afterRefreshSends 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​

OptionTypeDefaultDescription
enabledbooleantrueEnable or disable the hook
instrumentationKeystring-Instrumentation key (optional, uses global appInsights)
evaluationEventNamestring"FeatureFlagEvaluated"Custom event name for evaluations
changeEventNamestring"FeatureFlagChanged"Custom event name for changes
trackEvaluationsbooleantrueTrack feature flag evaluations
trackAllResultsbooleantrueTrack both true and false results
setCustomPropertiesbooleanfalseAdd feature flags as custom properties on all telemetry
propertyPrefixstring"feature_"Prefix for property names
trackChangesbooleantrueTrack real-time feature changes
trackIdentitybooleantrueSet authenticated user context
customPropertiesobject{}Custom properties for all events
customMeasurementsobject{}Custom measurements for all events
checkConsent() => boolean() => trueConsent callback called before each event
debugbooleanfalseEnable 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
});

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​

  1. Go to Azure Portal → Application Insights resource → Logs
  2. 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​

  1. Verify appInsights is loaded: console.log(typeof window.appInsights !== 'undefined')
  2. Check your connection string / instrumentation key
  3. Check your checkConsent callback returns true
  4. Enable debug mode: new AppInsightsHook({ debug: true })
  5. 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 setCustomProperties is true

Performance​

  • Overhead: <0.1ms per evaluation
  • Bundle size: ~2KB minified
  • Uses Application Insights' internal batching