npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nuxt-otel-appinsights

v0.0.12

Published

Nuxt module to integrate OpenTelemetry (Azure Monitor) and Azure Application Insights.

Readme

nuxt-otel-appinsights

Nuxt module that wires:

  • Server-side OpenTelemetry via Azure Monitor (@azure/monitor-opentelemetry)
  • Client-side Azure Application Insights (@microsoft/applicationinsights-web)
  • Nitro middleware to create SERVER spans for matching incoming routes and automatically correlate plain server-side fetch(...) calls made during those requests

This module bundles its runtime dependencies. Consuming apps should not need to install Azure Monitor OpenTelemetry, Application Insights, or OpenTelemetry API packages separately.

Quick start

1. Install

pnpm add nuxt-otel-appinsights
# or
npm i nuxt-otel-appinsights

2. Configure Nuxt

Add the module early in your modules array so tracing initializes before your app plugins and middleware where possible.

export default defineNuxtConfig({
  modules: ['nuxt-otel-appinsights'],
  otel: {
    enableAppInsightsServer: true,
    enableAppInsightsClient: true,
    serverApiRouteFilter: ['/api/'],
  },
  runtimeConfig: {
    otel: {
      appinsightsConnectionString:
        process.env.APPLICATIONINSIGHTS_CONNECTION_STRING ||
        process.env.NUXT_OTEL_APPINSIGHTS_CONNECTION_STRING ||
        '',
    },
    public: {
      otel: {
        appinsightsConnectionString: process.env.NUXT_PUBLIC_OTEL_APPINSIGHTS_CONNECTION_STRING || '',
      },
    },
  },
})

3. Set connection strings

  • Server: APPLICATIONINSIGHTS_CONNECTION_STRING or NUXT_OTEL_APPINSIGHTS_CONNECTION_STRING
  • Client: NUXT_PUBLIC_OTEL_APPINSIGHTS_CONNECTION_STRING

The server and client may point at different Application Insights resources. Do not put secrets in public runtime config; use a browser-safe/client-specific connection string for NUXT_PUBLIC_OTEL_APPINSIGHTS_CONNECTION_STRING.

4. Verify server request and dependency telemetry

Create or use a Nitro endpoint that makes a plain downstream fetch(...) call:

export default defineEventHandler(async () => {
  const response = await fetch('https://example.com')
  return { ok: response.ok }
})

Call the endpoint from a route matching serverApiRouteFilter, such as /api/hello. In Application Insights you should expect:

  • one incoming request span for the Nitro route
  • one dependency span for the downstream fetch(...)

If you do not see the dependency span, first confirm the route matches serverApiRouteFilter and that server-side tracing is enabled.

5. Track a custom client event

Use a small composable so components do not depend directly on the Application Insights SDK:

type TrackEventInput = {
  name: string
  properties?: Record<string, string | number | boolean | null | undefined>
  measurements?: Record<string, number>
}

type AppInsightsLike = {
  trackEvent: (event: TrackEventInput) => void
}

type TelemetryNuxtApp = ReturnType<typeof useNuxtApp> & {
  $appInsights?: AppInsightsLike
  $initializeAppInsightsClient?: () => Promise<AppInsightsLike | undefined>
}

export function useTelemetry() {
  const nuxtApp = useNuxtApp() as TelemetryNuxtApp

  async function getAppInsightsClient() {
    return (await nuxtApp.$initializeAppInsightsClient?.()) || nuxtApp.$appInsights
  }

  async function trackEvent(event: TrackEventInput) {
    const appInsights = await getAppInsightsClient()

    appInsights?.trackEvent(event)

    return Boolean(appInsights)
  }

  return { getAppInsightsClient, trackEvent }
}

Then call it from a component, composable, or plugin:

const { trackEvent } = useTelemetry()

await trackEvent({
  name: 'Checkout Started',
  properties: {
    plan: 'pro',
    source: 'pricing-page',
  },
  measurements: {
    value: 49,
  },
})

Query custom events in Application Insights:

customEvents
| where name == "Checkout Started"
| order by timestamp desc

Client-side telemetry

Custom events

The recommended pattern is to keep Application Insights access behind a small app-level helper or composable. This lets the rest of your app emit business events without caring whether client telemetry started automatically or was delayed for consent.

The client plugin injects:

  • useNuxtApp().$initializeAppInsightsClient() - starts the browser SDK if needed, then returns the Application Insights client
  • useNuxtApp().$appInsights - the injected browser SDK instance when one is already available

Prefer calling $initializeAppInsightsClient() from your helper before tracking. The method is safe to call repeatedly and returns the cached client after the first successful initialization, so the same helper works for both clientInitialization: 'auto' and clientInitialization: 'manual'.

Custom event properties should be low-cardinality business dimensions where possible. Avoid sending secrets, access tokens, email addresses, or other unnecessary personal data from browser telemetry.

The playground includes a working example in playground/composables/useTelemetry.ts and playground/pages/index.vue.

Manual initialization for consent

If you need to delay browser telemetry until a user grants consent, set:

export default defineNuxtConfig({
  modules: ['nuxt-otel-appinsights'],
  otel: {
    enableAppInsightsClient: true,
    clientInitialization: 'manual',
  },
})

The client plugin will still register its helpers, but it will not call loadAppInsights() until you explicitly start it:

const { $initializeAppInsightsClient } = useNuxtApp()

async function allowTelemetry() {
  await $initializeAppInsightsClient()
}

This keeps the consent logic in your app small: your cookie banner can persist consent and then call one method on Allow all.

$setAppInsightsUserContext(...) remains safe to call before initialization. The plugin caches the requested authenticated user id and applies it once the client is started.

Authenticated user context

The client plugin injects a helper you can call from your app:

  • useNuxtApp().$initializeAppInsightsClient()
  • useNuxtApp().$setAppInsightsUserContext({ authenticatedUserId })

This sets the authenticated user context, which maps to ai.user.authUserId.

Set it on login and clear it on logout:

const { $setAppInsightsUserContext } = useNuxtApp()

// after login
$setAppInsightsUserContext({ authenticatedUserId: user.id })

// on logout
$setAppInsightsUserContext(null)

Or keep it in sync with reactive auth state:

export default defineNuxtPlugin(() => {
  const { $setAppInsightsUserContext } = useNuxtApp()
  const auth = useAuth() // your composable

  watch(
    () => auth.user?.id,
    (id) => $setAppInsightsUserContext(id ? { authenticatedUserId: id } : null),
    { immediate: true },
  )
})

Server-side telemetry

For incoming Nitro routes that match otel.serverApiRouteFilter, the module:

  • creates a SERVER span for the request
  • binds that request trace context for downstream async work
  • automatically correlates plain server-side fetch(...) calls made during that request as dependency spans

This means a normal Nitro/H3 handler can usually just call await fetch(...) and expect request to dependency correlation without additional tracing code.

sequenceDiagram
  participant Browser
  participant NitroRoute as Nitro route
  participant Middleware as OTel middleware
  participant Fetch as server-side fetch(...)
  participant Downstream as downstream API
  participant AI as Application Insights

  Browser->>NitroRoute: Request
  NitroRoute->>Middleware: Incoming handler pipeline
  Middleware->>Middleware: Create SERVER span
  Middleware->>NitroRoute: Bind request trace context
  NitroRoute->>Fetch: await fetch(...)
  Fetch->>Downstream: Outbound HTTP request
  Downstream-->>Fetch: HTTP response
  Fetch-->>NitroRoute: Response
  NitroRoute-->>Browser: Response
  Middleware->>AI: Request span
  Fetch->>AI: Dependency span

If a route does not match serverApiRouteFilter, this module will not create a request span for it, and downstream fetch(...) calls from that route will not automatically inherit a parent span from this module.

BFF and proxy routes

For backend-for-frontend or proxy routes, prefer letting the server-side request span own downstream correlation.

In practice, that means you generally should not manually forward inbound tracing headers such as traceparent, tracestate, or baggage from the browser to downstream services when this module is already auto-instrumenting server-side dependencies. Forwarding those headers through a BFF can create misleading parentage or apparent duplicate correlation.

Enrich server spans

This module installs a Nitro event handler middleware that creates a SERVER span for incoming requests and binds that request context so plain server-side fetch(...) calls can be correlated automatically.

The enrichment APIs below are optional. They are for adding attributes or events to the request span, not for making dependency correlation work.

Provide attributes via event.context.otelSpanAttributes

In any server handler/middleware, set event.context.otelSpanAttributes to a plain object of primitive values. The module middleware will attach these to the SERVER span.

export default defineEventHandler((event) => {
  // Example only: adapt to your auth/session setup.
  const authenticatedUserId = event.context.auth?.user?.id
  const dealId = event.context.auth?.dealId

  // Only primitive values are copied to span attributes.
  event.context.otelSpanAttributes = {
    ...(event.context.otelSpanAttributes || {}),
    'enduser.id': authenticatedUserId,
    'deal.id': dealId,
  }
})

Add events or attributes directly on the active SERVER span

For advanced scenarios, the middleware also exposes the span instance as event.context.serverSpan. Treat this as best-effort because it may be missing if tracing is disabled.

export default defineEventHandler((event) => {
  const span = (event.context as any).serverSpan
  if (span) {
    span.setAttribute('app.feature', 'checkout')
    span.addEvent('checkout validation started')
  }
  return { ok: true }
})

In Application Insights, these show up on the request trace as custom dimensions/attributes and span events.

Configuration reference

Full example

export default defineNuxtConfig({
  modules: ['nuxt-otel-appinsights'],
  otel: {
    // Server-side OpenTelemetry via Azure Monitor (Node/Nitro).
    enableAppInsightsServer: true,
    // Client-side Application Insights (browser plugin).
    enableAppInsightsClient: true,
    // Optional: defer browser initialization until your app explicitly starts it.
    // Useful for consent-gated telemetry.
    clientInitialization: 'auto',
    // Server-side incoming request filter.
    // If non-empty, only requests whose path starts with any entry are traced.
    // Set to [] to trace all incoming requests.
    serverApiRouteFilter: ['/api/'],
    // Third-party domains where we should NOT attach correlation headers.
    correlationHeaderExcludedDomains: ['*.google-analytics.com', '*.sentry.io', 'api.iconify.design'],
    // Third-party domains where we should NOT record browser dependency telemetry
    // (fetch/XHR "RemoteDependencyData").
    // Patterns supported:
    // - 'example.com' (exact)
    // - '*.example.com' (subdomains + apex)
    dependencyExcludedDomainsClient: ['*.google-analytics.com', '*.launchdarkly.com', 'api.iconify.design'],
    // Optional: ignore querystring-only navigations for pageview tracking.
    // If only these query params change, we won't send an additional pageView.
    // Also strips them from the `uri` sent with pageView telemetry.
    pageViewIgnoreQueryParams: ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'],
    // Client batching interval (ms) for Application Insights. Default: 5_000.
    maxBatchInterval: 5_000,
    // Enables extra console logging from this module/plugins.
    debug: false,
  },
  runtimeConfig: {
    // server-only
    otel: {
      // Server plugin checks `APPLICATIONINSIGHTS_CONNECTION_STRING` first,
      // then falls back to this runtimeConfig value.
      appinsightsConnectionString:
        process.env.APPLICATIONINSIGHTS_CONNECTION_STRING ||
        process.env.NUXT_OTEL_APPINSIGHTS_CONNECTION_STRING ||
        '',
    },
    public: {
      // client
      otel: {
        // Connection string exposed to the browser plugin.
        // Avoid putting secrets here; use a client-specific connection string.
        appinsightsConnectionString: process.env.NUXT_PUBLIC_OTEL_APPINSIGHTS_CONNECTION_STRING || '',
        // The client plugin reads its settings from `runtimeConfig.public.otel`.
        // This module copies values from the `otel:` module options into `runtimeConfig.public.otel`.
        // If you prefer, you can also set client options directly here instead of under `otel:`.
        // dependencyExcludedDomainsClient: ['*.launchdarkly.com'],
        // pageViewIgnoreQueryParams: ['utm_source', 'utm_medium', 'gclid'],
        // maxBatchInterval: 5_000,
      },
    },
  },
})

Module order

This module registers:

  • a Nitro plugin for server-side Azure Monitor OpenTelemetry
  • a Nuxt client plugin for Application Insights
  • a Nitro middleware for incoming request span/context binding

Nuxt runs module setup in the order listed in modules, and plugin/middleware registration order follows from that.

Recommendation: put nuxt-otel-appinsights early, ideally first, in your modules array so tracing initializes as early as possible and any plugins/middleware you add later are more likely to run under an active trace/span.

Environment variable precedence

Server precedence:

  1. APPLICATIONINSIGHTS_CONNECTION_STRING
  2. runtimeConfig.otel.appinsightsConnectionString
  3. legacy fallback runtimeConfig.appinsightsConnectionString

Client precedence:

  1. runtimeConfig.public.otel.appinsightsConnectionString
  2. legacy fallback runtimeConfig.public.appinsightsConnectionString

Backward compatibility

These older config keys are still recognized for compatibility, but new integrations should prefer the current names:

  • enableAzureMonitor -> enableAppInsightsServer
  • enableClientAI -> enableAppInsightsClient
  • traceApiRoutesOnly -> serverApiRouteFilter

Development

pnpm install
pnpm dev

Releasing

Maintainers: see RELEASING.md.