Set the Application Insights connection string programmatically
Pass the full connection string, not just the instrumentation key, to the options of whatever initialises telemetry: options.AzureMonitor.ConnectionString for the Microsoft OpenTelemetry Distro, UseAzureMonitor(o => o.ConnectionString = ...) for the Azure Monitor distro, and TelemetryConfiguration.ConnectionString or ApplicationInsightsServiceOptions for the Application Insights SDK. A value set in code beats the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable, which is what Microsoft recommends for production.
Setting the destination “in code” used to mean one line: assign the instrumentation key. Two things changed since. Microsoft replaced the bare key with a connection string that also carries the regional endpoints, and the SDK that read that line is being replaced by OpenTelemetry-based packages that each take the value somewhere different. This guide covers where it goes now, and when code is the right place for it at all.
What a connection string is
A connection string is a list of key=value settings separated by semicolons. You copy it from the Overview page of the Application Insights resource:
InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://southcentralus.in.applicationinsights.azure.com/
InstrumentationKey is the only required setting. The others point the SDK at specific services: IngestionEndpoint, LiveEndpoint for Live Metrics, ProfilerEndpoint and SnapshotEndpoint, or a single EndpointSuffix from which the SDK builds all of them (used for sovereign clouds). The portal may add settings you can’t configure, such as ApplicationId; leave them in. The whole string can be up to 4,096 characters.
The endpoints are why the key alone is no longer enough. A key with no connection string sends to the global ingestion endpoint; the connection string sends to your resource’s region. Microsoft ended support for instrumentation key ingestion on March 31, 2025: it keeps working, but without updates or support.
Code or environment: which wins
Every current package reads the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable, and Microsoft recommends exactly that for production. Code is the recommended place only for local development and test, plus the cases where the app genuinely chooses its destination at runtime. When both are present, code wins: the Microsoft OpenTelemetry Distro for .NET documents the order as code first, then the environment variable.
That ordering is the reason to be careful. A connection string hard-coded for a test and then shipped will quietly override the value operations set for production.
Microsoft OpenTelemetry Distro (.NET)
This is the package Microsoft points new .NET apps to. The connection string is an option of the Azure Monitor exporter:
using Microsoft.OpenTelemetry;
var builder = WebApplication.CreateBuilder(args);
builder.UseMicrosoftOpenTelemetry(options =>
{
options.Exporters = ExportTarget.AzureMonitor;
options.AzureMonitor.ConnectionString =
builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]
?? builder.Configuration["AzureMonitor:ConnectionString"];
});
var app = builder.Build();
app.Run();
Reading both keys explicitly, environment first, is Microsoft’s own pattern for keeping the value in appsettings.json under an AzureMonitor section without relying on implicit binding. Console and other non-hosted apps set the same option inside OpenTelemetrySdk.Create(...), and must keep the returned SDK object alive until shutdown so pending telemetry is flushed.
Azure Monitor OpenTelemetry Distro (.NET)
Apps already on Azure.Monitor.OpenTelemetry.AspNetCore need no change; Microsoft says existing users can stay. The value goes on AzureMonitorOptions:
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
options.ConnectionString = builder.Configuration["MyApp:Telemetry:ConnectionString"];
});
Call UseAzureMonitor() once; a second call throws. To authenticate ingestion with Microsoft Entra ID, set options.Credential as well; the connection string still names the resource.
Application Insights SDK for .NET (2.x and 3.x)
Microsoft’s advice for apps on the classic 2.x SDK is to upgrade to SDK 3.x, which keeps most of the TelemetryClient and TelemetryConfiguration API. The connection string property is one of the things that carries over.
ASP.NET Core and Worker Service
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.ConnectionString = builder.Configuration["MyApp:Telemetry:ConnectionString"];
});
Worker Service and console hosts use AddApplicationInsightsTelemetryWorkerService with the same options.
Code that builds its own configuration
Where an app creates a TelemetryClient by hand, give it a configuration with the connection string set:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
var configuration = TelemetryConfiguration.CreateDefault();
configuration.ConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
var client = new TelemetryClient(configuration);
In 3.x three older patterns stop compiling or stop working: the InstrumentationKey setting is replaced by ConnectionString, the static TelemetryConfiguration.Active is replaced by CreateDefault(), and the parameterless new TelemetryClient() that used it is replaced by the overload above. 3.x also requires a connection string at startup; see disabling Application Insights in development for what to do on machines that should not send.
Node.js
The Microsoft OpenTelemetry Distro for Node.js takes the value under azureMonitor.azureMonitorExporterOptions, and must run before the libraries it instruments are loaded:
const { useMicrosoftOpenTelemetry } = require("@microsoft/opentelemetry");
useMicrosoftOpenTelemetry({
azureMonitor: {
azureMonitorExporterOptions: {
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
},
},
});
Passing the environment variable through explicitly, as here, keeps a single source for the value while making the dependency visible in code.
One app, several resources
The real reason to set the value in code is an app that decides at runtime where telemetry goes: a multi-tenant service with a resource per customer, or a tool that reports to whichever environment it was pointed at. Two rules keep that sane:
- Decide once, at startup. The distros create their providers once per app (the Azure Monitor distro throws on a second registration), so pick the connection string before initialising, not per request.
- Keep the value outside the binary. Read it from configuration, a secret store or the environment, and log which resource was chosen (the region is enough; there is no need to log the key).
Common mistakes
- Pasting only the key into a
ConnectionStringsetting.InstrumentationKey=is required as a prefix; a bare GUID is not a connection string. - Initialising too late in Node.js. Libraries loaded before the distro starts may not be instrumented, and Microsoft warns you can lose their telemetry.
- A test value that ships. Because code beats the environment variable, a hard-coded string from a test run overrides production configuration. Search for
ConnectionString =before you release.
Frequently asked questions
Is the Application Insights connection string a secret?
Microsoft says the instrumentation key inside it is an identifier, not a security token: it tells the ingestion service which resource the data belongs to. Anyone who has it can still send telemetry to your resource, so keep it out of public repositories, and turn on Microsoft Entra ID authenticated ingestion if you need to stop unauthorised senders.
Can I still configure only the instrumentation key?
Microsoft ended support for instrumentation key ingestion on March 31, 2025. It still works, but gets no updates or support, and a key on its own sends to the global endpoint rather than your resource's regional one. Application Insights .NET SDK 3.x removes the InstrumentationKey setting entirely.
Which value wins if I set the connection string in code and in the environment?
For the Microsoft OpenTelemetry Distro in .NET, the value in code wins over the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable. That is why setting it in code is best kept for local development and tests, or for apps that choose the destination at runtime.