Skip to main content

Azure Application Insights

Track feature flag usage in Azure Application Insights for monitoring, analytics, and diagnostics correlation.

Overview​

The Toggly Application Insights Hook automatically sends feature flag telemetry to Azure Application Insights, allowing 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
  • Create alerts based on feature flag state changes

Installation​

npm install @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)

Setting up Application Insights​

Add the Application Insights JavaScript SDK to your page:

<script type="text/javascript">
!(function (cfg){function e(){cfg.onInit&&cfg.onInit(i)}var S,u,D,t,n,i,C=window,x=document,w=C.location,I="script",b="ingestionendpoint",E="disableExceptionTracking",A="ai.device.";"instrumentationKey"[S="connectionString"];(D=cfg[S]||"")&&(D.indexOf("InstrumentationKey=")!==-1?u="IngestionEndpoint=https://dc.services.visualstudio.com/v2/track":u.indexOf("IngestionEndpoint=")!==-1||(u+=";IngestionEndpoint=https://dc.services.visualstudio.com/v2/track"));var l=D?D.replace("InstrumentationKey=",""):cfg.instrumentationKey||"",G=cfg.sdk||"javascript:snippet";G+=","+l;var v=["src","name","ld","useXhr","crossOrigin","onInit","cfg"];(function(cfg){for(var i=0;i<v.length;i++){var x=cfg[v[i]];x&&(D+=(D?";":"")+v[i]+"="+encodeURIComponent(x))}})(cfg);var c=C[t="appInsights"];c&&c.queue||(C[t]=i={config:cfg,initialize:!0,queue:[],sv:"8",version:2,snippet:G},cfg[E]||i.queue.push(["trackPageView",{}]),e())})(
{connectionString:"YOUR_CONNECTION_STRING"}
);
</script>
<script type="text/javascript" src="https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js" crossorigin="anonymous"></script>

Quick Start​

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,
})
]
});

Configuration Options​

OptionTypeDefaultDescription
enabledbooleantrueEnable or disable the hook entirely
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
setCustomPropertiesbooleantrueAdd feature flags as custom properties on all telemetry
propertyPrefixstring"ff_"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
checkConsentfunction() => trueConsent check callback
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'
},
customMeasurements: {
session_duration: 120
},
checkConsent: () => {
return window.cookieConsent?.analytics ?? false;
},
debug: false
});

What Gets Tracked​

Feature Evaluations​

When a feature flag is evaluated:

appInsights.trackEvent({
name: 'FeatureFlagEvaluated',
properties: {
feature_key: 'new-checkout-flow',
feature_enabled: 'true',
category: 'toggly'
}
});

Feature Changes (Real-time)​

When a feature flag state changes via WebSocket:

appInsights.trackEvent({
name: 'FeatureFlagChanged',
properties: {
feature_key: 'dark-mode',
old_value: 'false',
new_value: 'true',
category: 'toggly'
}
});

Custom Properties on All Telemetry​

When setCustomProperties: true, feature flags are added as custom properties to all telemetry:

// All telemetry (page views, exceptions, requests, etc.) will include:
{
ff_dark_mode: 'enabled',
ff_new_checkout: 'disabled'
}

This is achieved via Application Insights' addTelemetryInitializer API, allowing you to correlate any error, performance issue, or user action with the active feature flags.

User Identity​

When identity is set in Toggly:

appInsights.setAuthenticatedUserContext('[email protected]');

Framework Examples​

import { createTogglyProvider } from '@ops-ai/react-feature-flags-toggly';
import { AppInsightsHook } from '@ops-ai/toggly-appinsights-hook';

const TogglyProvider = await createTogglyProvider({
appKey: process.env.REACT_APP_TOGGLY_KEY,
environment: 'Production',
hooks: [
new AppInsightsHook({
setCustomProperties: true,
})
]
});

export default function App() {
return (
<TogglyProvider>
<Routes />
</TogglyProvider>
);
}

Viewing Data in Azure Portal​

Custom Events​

  1. Go to Azure Portal -> Application Insights resource
  2. Navigate to Logs (Analytics)
  3. 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

Feature Flag Correlation​

Correlate feature flags with other telemetry:

// Find exceptions by feature flag
exceptions
| extend dark_mode = tostring(customDimensions.ff_dark_mode)
| summarize count() by dark_mode, type
// Performance by feature flag
requests
| extend checkout_v2 = tostring(customDimensions.ff_checkout_v2)
| summarize avg(duration), percentile(duration, 95) by checkout_v2

Creating Alerts​

Create alerts when feature flags change:

  1. Go to Alerts -> Create alert rule
  2. Select Custom log search
  3. Query:
    customEvents
    | where name == "FeatureFlagChanged"
    | where customDimensions.feature_key == "critical-feature"

GDPR/CCPA Compliance​

The checkConsent callback allows integration with consent management platforms:

// OneTrust example
new AppInsightsHook({
checkConsent: () => window.OneTrust?.IsAlertBoxClosed() &&
window.OneTrust?.GetDomainData()?.Groups
?.find(g => g.CustomGroupId === 'C0002')?.Status === 'active'
});

// Simple cookie consent example
new AppInsightsHook({
checkConsent: () => document.cookie.includes('analytics_consent=true')
});

What data is sent​

  • Feature flag key name (e.g., "dark-mode")
  • Feature evaluation result (true / false)
  • Custom properties you explicitly configure
  • User ID (only if trackIdentity is enabled and identity is set)
  • No automatic PII collection

Error Handling​

The hook is designed to never break the Toggly SDK:

  • All Application Insights API calls are wrapped in try-catch
  • If appInsights is not loaded, events are silently skipped
  • If appInsights throws an error, it is caught and logged to console
  • The hook provides a console warning (not error) if appInsights is not detected at initialization

Troubleshooting​

Events not appearing in Application Insights​

  1. Check appInsights is loaded: Ensure the Application Insights SDK is on the page before Toggly initializes

    console.log('appInsights available:', typeof window.appInsights !== 'undefined');
  2. Check connection string: Verify your Application Insights connection string is correct

  3. Check consent: Verify your checkConsent callback returns true

  4. Enable debug mode:

    new AppInsightsHook({ debug: true })
  5. Check Azure Portal delay: Application Insights data may take a few minutes to appear

Console warning at startup​

[Toggly AppInsights Hook] Application Insights SDK not detected.

This means appInsights was not loaded when the hook was created. The hook will automatically start sending events once appInsights becomes available.

Custom properties not appearing​

  • Property names are sanitized: special characters replaced with underscores
  • Property names are truncated to 150 characters (Application Insights limit)
  • Ensure setCustomProperties is set to true