NetDiag JavaScript Client | @netdiag/client npm Package

Official JavaScript/TypeScript SDK for NetDiag API. Run network diagnostics (DNS, TLS, HTTP, ping) from Node.js or browsers with full TypeScript support.

JS
@netdiag/client npm

Official JavaScript/TypeScript SDK for NetDiag API

Installation

npm install @netdiag/client

Or using other package managers:

# Yarn
yarn add @netdiag/client

# pnpm
pnpm add @netdiag/client

Requirements: Node.js 18+ or modern browsers with Fetch API support.


Quick Start

import { NetDiagClient } from '@netdiag/client';

const client = new NetDiagClient({ apiKey: 'your-api-key' });

// Run diagnostics on a target
const result = await client.check('example.com');

console.log(result.status);        // "Healthy" | "Warning" | "Unhealthy"
console.log(result.quorum);        // "3/3"
console.log(result.locations);     // Array of regional results

For quick health checks without full diagnostics:

// Simple boolean check
const isUp = await client.isHealthy('example.com');

// Get status enum
const status = await client.getStatus('example.com');

API Reference

Constructor

new NetDiagClient(options?: NetDiagClientOptions)
Option Type Default Description
baseUrl string "https://api.netdiag.dev" API base URL
apiKey string undefined API key for authenticated requests
timeout number 30000 Request timeout in milliseconds
fetch typeof fetch globalThis.fetch Custom fetch implementation

Methods

check(target)

Run full diagnostics on a target.

check(target: string): Promise<CheckResponse>
check(request: CheckRequest): Promise<CheckResponse>

Examples:

// Simple check with just hostname
const result = await client.check('example.com');

// Check with options
const result = await client.check({
  target: 'example.com',
  port: 443,
  pingCount: 10,
  regions: 'us-east,eu-west,ap-southeast'
});

checkPrometheus(target)

Get diagnostics results in Prometheus metrics format.

checkPrometheus(target: string): Promise<string>
checkPrometheus(request: CheckRequest): Promise<string>

Example:

const metrics = await client.checkPrometheus('example.com');
// Returns Prometheus-formatted metrics string

isHealthy(target)

Quick boolean health check.

isHealthy(target: string): Promise<boolean>

Example:

if (await client.isHealthy('api.example.com')) {
  console.log('Service is healthy!');
}

getStatus(target)

Get the status enum for a target.

getStatus(target: string): Promise<Status>

Example:

import { Status } from '@netdiag/client';

const status = await client.getStatus('example.com');

switch (status) {
  case Status.Healthy:
    console.log('All systems operational');
    break;
  case Status.Warning:
    console.log('Degraded performance');
    break;
  case Status.Unhealthy:
    console.log('Service is down');
    break;
}

Request Options

When using the object form of check() or checkPrometheus():

Property Type Default Description
target string required Hostname, IP address, or URL to check
port number 443 Port to check (80, 443, 8080, 8443)
pingCount number 4 Number of ping packets (1-100)
pingTimeout number 5 Ping timeout in seconds (1-30)
dns string undefined Custom DNS server to use
regions string undefined Comma-separated region codes

Available Regions: us-east, us-west, eu-west, eu-central, ap-southeast, ap-northeast


Response Types

CheckResponse

interface CheckResponse {
  runId: string;                    // Unique diagnostic run ID
  target: string;                   // Target that was checked
  status: Status;                   // Overall health status
  quorum: string;                   // Healthy regions ratio (e.g., "3/4")
  dnsPropagationStatus: string;     // "consistent" | "mismatched" | "unknown"
  startedAt: string;                // ISO timestamp
  completedAt: string;              // ISO timestamp
  locations: LocationResult[];      // Per-region results
}

LocationResult

interface LocationResult {
  region: string;
  status: Status;
  ping: PingResult | null;
  dns: DnsResult | null;
  tls: TlsResult | null;
  http: HttpResult | null;
}

Diagnostic Results

interface PingResult {
  status: Status;
  latencyMs: number;
  minRttMs?: number;
  maxRttMs?: number;
  packetLossPercent?: number;
  tcpFallbackUsed: boolean;
  message?: string;
  error?: ErrorInfo;
}
interface DnsResult {
  status: Status;
  resolvedAddresses: string[];
  message?: string;
  error?: ErrorInfo;
}
interface TlsResult {
  status: Status;
  certificateValid: boolean;
  daysUntilExpiry?: number;
  expiresAt?: string;
  subject?: string;
  issuer?: string;
  protocol?: string;
  message?: string;
  error?: ErrorInfo;
}
interface HttpResult {
  status: Status;
  statusCode?: number;
  reasonPhrase?: string;
  responseTimeMs?: number;
  message?: string;
  error?: ErrorInfo;
}

Error Handling

The client throws typed errors for different failure scenarios:

import {
  NetDiagError,
  NetDiagApiError,
  NetDiagRateLimitError
} from '@netdiag/client';

try {
  const result = await client.check('example.com');
} catch (error) {
  if (error instanceof NetDiagRateLimitError) {
    // Rate limited - wait and retry
    console.log(`Retry after ${error.retryAfterSeconds} seconds`);
    await sleep(error.retryAfterSeconds * 1000);
  } else if (error instanceof NetDiagApiError) {
    // API error (4xx/5xx)
    console.error(`API Error: ${error.statusCode} - ${error.body}`);
  } else if (error instanceof NetDiagError) {
    // Other client errors
    console.error(`Client Error: ${error.message}`);
  }
}

Error Types

Error Description
NetDiagError Base error class for all client errors
NetDiagApiError HTTP errors (4xx/5xx) with statusCode and body
NetDiagRateLimitError Rate limit exceeded with retryAfterSeconds

Advanced Usage

Custom Fetch Implementation

Use a custom fetch for advanced networking scenarios:

import { fetch as undiciFetch } from 'undici';

const client = new NetDiagClient({
  apiKey: 'your-api-key',
  fetch: undiciFetch
});

Browser Usage

The client works in modern browsers:

<script type="module">
  import { NetDiagClient } from 'https://esm.sh/@netdiag/client';

  const client = new NetDiagClient({ apiKey: 'your-key' });
  const result = await client.check('example.com');
  console.log(result);
</script>

Prometheus Integration

Scrape diagnostics as Prometheus metrics:

import express from 'express';
import { NetDiagClient } from '@netdiag/client';

const app = express();
const client = new NetDiagClient({ apiKey: 'your-key' });

app.get('/metrics', async (req, res) => {
  const metrics = await client.checkPrometheus('your-service.com');
  res.type('text/plain').send(metrics);
});

app.listen(9090);

TypeScript Support

The package includes complete TypeScript declarations. All types are exported:

import type {
  NetDiagClientOptions,
  CheckRequest,
  CheckResponse,
  Status,
  LocationResult,
  PingResult,
  DnsResult,
  TlsResult,
  HttpResult,
  ErrorCode,
  ErrorInfo
} from '@netdiag/client';

Related