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

appinsights-rest

v0.2.3

Published

Application Insights REST API client for Nuxt4 and other modern frameworks

Downloads

21

Readme

appinsights-rest

A lightweight, framework-independent Application Insights REST API client for Node.js applications, optimized for Nuxt 4 and other modern frameworks.

Features

  • Framework-independent core with optional Nuxt integration
  • Full telemetry support (events, requests, dependencies, exceptions, traces, metrics)
  • Automatic batching and retry with exponential backoff
  • TypeScript support with full type definitions
  • Zero external dependencies for core functionality
  • Correlation ID support for distributed tracing

Installation

npm install appinsights-rest

Quick Start

Basic Usage

import { AppInsightsLogger } from 'appinsights-rest'

// Initialize the logger
const logger = new AppInsightsLogger({
  connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
  role: 'my-app',
  appVersion: '1.0.0'
})

// Track an event (synchronous - queued for batching)
logger.trackEvent('user_login', {
  userId: '123',
  method: 'oauth'
})

// Track a request (synchronous - returns request ID)
const requestId = logger.trackRequest({
  name: 'GET /api/users',
  url: 'https://example.com/api/users',
  duration: 150,
  responseCode: 200,
  success: true
})

// Track an exception (synchronous - queued for batching)
try {
  // some code
} catch (error) {
  logger.trackException(error, {
    context: 'user_registration'
  })
}

// Clean up when done (async - waits for flush)
await logger.dispose()

Getting Your Connection String

  1. Go to the Azure Portal
  2. Navigate to your Application Insights resource
  3. Copy the Connection String from the Overview page
  4. It should look like: InstrumentationKey=xxx;IngestionEndpoint=https://xxx.applicationinsights.azure.com/

API Reference

Constructor Options

interface AppInsightsConfig {
  connectionString: string    // Required: Azure Application Insights connection string
  role?: string              // Optional: Application role name (default: 'web-portal')
  appVersion?: string        // Optional: Application version
  batchSize?: number         // Optional: Batch size for telemetry (default: 16)
  flushIntervalMs?: number   // Optional: Flush interval in ms (default: 1000)
}

Tracking Methods

trackEvent(name, properties?): void

Track custom events. Synchronous - telemetry is queued and sent in batches.

logger.trackEvent('button_clicked', {
  buttonId: 'submit',
  page: 'checkout'
})

trackRequest(options): string

Track HTTP requests. Returns the request ID. Synchronous - telemetry is queued and sent in batches.

const requestId = logger.trackRequest({
  name: 'GET /api/users',
  url: 'https://example.com/api/users',
  duration: 150,            // in milliseconds
  responseCode: 200,
  success: true,
  properties: {
    userId: '123'
  }
})

trackDependency(options): string

Track dependencies (external API calls, database queries, etc.). Returns the dependency ID. Synchronous - telemetry is queued and sent in batches.

const dependencyId = logger.trackDependency({
  name: 'GET external-api',
  data: 'https://api.example.com/data',
  type: 'HTTP',
  target: 'api.example.com',
  duration: 250,
  resultCode: 200,
  success: true
})

trackException(error, properties?): void

Track exceptions and errors. Synchronous - telemetry is queued and sent in batches.

logger.trackException(new Error('Something went wrong'), {
  userId: '123',
  operation: 'checkout'
})

trackTrace(message, severityLevel?, properties?): void

Track trace messages. Synchronous - telemetry is queued and sent in batches.

logger.trackTrace('User authenticated', 1, {
  userId: '123'
})

Severity levels:

  • 0 - Verbose
  • 1 - Information (default)
  • 2 - Warning
  • 3 - Error
  • 4 - Critical

trackMetric(name, value, properties?): void

Track custom metrics. Synchronous - telemetry is queued and sent in batches.

logger.trackMetric('response_time', 245, {
  endpoint: '/api/users'
})

dispose(): Promise<void>

Flush remaining telemetry and clean up resources. Async - waits for all telemetry to be sent. Always call this before your application exits.

await logger.dispose()

Utility Functions

import {
  generateGuid,
  createRequestId,
  createDependencyId,
  formatDuration
} from 'appinsights-rest'

// Generate a GUID
const guid = generateGuid()

// Create Application Insights compatible IDs
const reqId = createRequestId()
const depId = createDependencyId()

// Format duration for Application Insights
const duration = formatDuration(1500) // "00:00:01.500"

Advanced Features

Correlation IDs

Pass correlation IDs in properties to link related telemetry:

const correlationId = generateGuid()

logger.trackRequest({
  name: 'GET /api/users',
  url: 'https://example.com/api/users',
  duration: 150,
  responseCode: 200,
  success: true,
  properties: {
    correlationId
  }
})

logger.trackDependency({
  name: 'Database Query',
  data: 'SELECT * FROM users',
  type: 'SQL',
  duration: 50,
  resultCode: 200,
  success: true,
  properties: {
    correlationId
  }
})

Batching and Retries

The logger automatically batches telemetry and retries failed requests with exponential backoff:

  • Default batch size: 16 items
  • Default flush interval: 1000ms
  • Automatic retry for 429 (rate limit) and 5xx errors
  • Exponential backoff up to 60 seconds

TypeScript Support

Full TypeScript definitions are included:

import type {
  AppInsightsConfig,
  TelemetryEnvelope,
  TrackRequestOptions,
  TrackDependencyOptions,
  Dict
} from 'appinsights-rest'

License

MIT

Repository

https://github.com/mizukoshi-yuki/appinsights-rest

Author

Yuki Mizukoshi