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

@codereb00t/next-request-telemetry

v1.0.1

Published

Framework-agnostic request telemetry SDK for Next.js — captures, enriches, batches, and exports all client and server HTTP requests.

Readme

next-request-telemetry

Framework-agnostic request telemetry SDK for Next.js.
Automatically captures all HTTP requests on both client and server, enriches them with metadata, batches them efficiently, and exports to any telemetry provider.

npm version TypeScript License: MIT


What it does

| Question | Answer | |---|---| | Which APIs are being called? | ✅ Captured automatically | | How many times per page load? | ✅ Per-event with pageUrl | | Which requests are slow? | ✅ Duration on every event | | Which requests fail? | ✅ Status + error field | | Client-side or server-side? | ✅ side: "client" \| "server" | | Which page triggered it? | ✅ pageUrl field | | Request & response sizes? | ✅ Content-Length captured | | External API visibility? | ✅ category: "external" |


Installation

npm install next-request-telemetry
# or
yarn add next-request-telemetry
# or
pnpm add next-request-telemetry

Requirements: Node.js ≥ 18, Next.js ≥ 14, React ≥ 18.


Quick Start

1. Server-side (instrumentation.ts)

Create instrumentation.ts in your project root (alongside next.config.ts):

// instrumentation.ts
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const {
      initTelemetry,
      installServerInterceptor,
      hyperdxExporter,
      consoleExporter,
    } = await import("next-request-telemetry/server");

    initTelemetry({
      service: "my-next-app",
      squad: "platform",
      environment: process.env.NODE_ENV,
      version: process.env.NEXT_PUBLIC_APP_VERSION,

      exporters: [
        hyperdxExporter({
          endpoint: "https://in-otel.hyperdx.io/v1/logs",
          apiKey: process.env.HYPERDX_API_KEY!,
        }),
        // Add consoleExporter() during development
      ],

      ignorePatterns: ["/_next/", "/favicon.ico", "/api/health"],
    });

    installServerInterceptor();
  }
}

Enable instrumentationHook in next.config.ts (Next.js < 15):

// next.config.ts
const nextConfig = {
  experimental: {
    instrumentationHook: true, // Not needed for Next.js 15+
  },
};

export default nextConfig;

2. Client-side (App Router)

// app/providers.tsx
"use client";

import { useEffect } from "react";
import {
  initTelemetry,
  installClientInterceptor,
  hyperdxExporter,
} from "next-request-telemetry";

export function TelemetryProvider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    initTelemetry({
      service: "my-next-app",
      environment: process.env.NODE_ENV,
      exporters: [
        hyperdxExporter({
          endpoint: process.env.NEXT_PUBLIC_HYPERDX_ENDPOINT!,
          apiKey: process.env.NEXT_PUBLIC_HYPERDX_API_KEY!,
        }),
      ],
    });

    installClientInterceptor();
  }, []);

  return <>{children}</>;
}
// app/layout.tsx
import { TelemetryProvider } from "./providers";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <TelemetryProvider>{children}</TelemetryProvider>
      </body>
    </html>
  );
}

2b. Client-side (Pages Router)

// pages/_app.tsx
import type { AppProps } from "next/app";
import { useEffect } from "react";
import { initTelemetry, installClientInterceptor, consoleExporter } from "next-request-telemetry";

let installed = false;

export default function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    if (installed) return;
    installed = true;

    initTelemetry({
      service: "my-next-app",
      environment: process.env.NODE_ENV,
      exporters: [consoleExporter()],
    });

    installClientInterceptor();
  }, []);

  return <Component {...pageProps} />;
}

Configuration

initTelemetry({
  // ── Required ────────────────────────────────
  service: "my-next-app",        // Appears on every event
  environment: "production",     // "development" | "staging" | "production"
  exporters: [consoleExporter()],

  // ── Optional ────────────────────────────────
  squad: "platform",             // Team/squad identifier
  version: "1.2.3",              // App version / git SHA

  // URLs to never capture (string prefix match or RegExp)
  ignorePatterns: [
    "/_next/",
    "/favicon.ico",
    "/api/health",
    /^https:\/\/analytics\./,
  ],

  // Override URL categorization
  categorizer: (url) => {
    if (url.includes("/graphql")) return "api";
    return null; // null falls back to built-in logic
  },

  // Batching (these are the defaults)
  batching: {
    maxSize: 50,           // Flush when queue reaches this size
    flushIntervalMs: 3000, // Or after this many milliseconds
    maxRetries: 3,         // Retry failed exports this many times
    retryBaseDelayMs: 500, // Exponential backoff starting delay
  },

  debug: false,            // Log SDK internals to console
});

Telemetry Event Schema

Every captured request produces a RequestTelemetryEvent:

{
  id: "lf3x2k-abc12-001",          // Unique event ID
  timestamp: "2024-01-15T10:30:00.000Z",

  method: "POST",
  url: "https://api.stripe.com/v1/payment_intents",
  normalizedPath: "/v1/payment_intents",  // Dynamic segments replaced with :id

  status: 200,
  duration: 234,            // Milliseconds

  requestSize: 512,         // Bytes (from Content-Length or body estimate)
  responseSize: 1024,       // Bytes (from Content-Length header)

  side: "server",           // "client" | "server"
  runtime: "node",          // "browser" | "node"

  pageUrl: "https://myapp.com/checkout",  // Current page (client-side only)
  route: undefined,

  category: "external",     // See URL categorization below
  error: undefined,

  metadata: {
    service: "my-next-app",
    squad: "payments",
    environment: "production",
    version: "2.1.0",
    userAgent: "Mozilla/5.0 ...",   // Client-side only
  }
}

URL Categorization

Requests are automatically classified:

| Pattern | Category | |---|---| | /api/* | api | | /_next/static/*, /_next/* | static | | .js, .mjs, .jsx | script | | .css, .scss | style | | .png, .jpg, .webp, .svg, etc. | image | | .woff2, .ttf, fonts/ | font | | Different origin | external | | Everything else | other |

Override with a custom categorizer:

initTelemetry({
  categorizer: (url) => {
    if (url.includes("/graphql")) return "api";
    if (url.includes("cdn.myapp.com")) return "static";
    return null; // null = use built-in rules
  },
  // ...
});

Exporters

Console Exporter (development)

import { consoleExporter } from "next-request-telemetry";

consoleExporter()
// Prints a console.table of captured events

HyperDX Exporter

import { hyperdxExporter } from "next-request-telemetry";

hyperdxExporter({
  endpoint: "https://in-otel.hyperdx.io/v1/logs",
  apiKey: process.env.HYPERDX_API_KEY,
  timeoutMs: 5000, // optional, default 5000
})

OTEL Exporter (OTLP HTTP)

import { otelExporter } from "next-request-telemetry/server";

otelExporter({
  endpoint: "http://otel-collector:4318/v1/traces",
  headers: {
    Authorization: "Bearer my-token",
  },
  timeoutMs: 5000,
})

Custom Exporter

Implement the TelemetryExporter interface:

import type { TelemetryExporter, RequestTelemetryEvent } from "next-request-telemetry";

const myExporter: TelemetryExporter = {
  name: "my-exporter",

  async send(events: RequestTelemetryEvent[]): Promise<void> {
    await fetch("https://my-backend.com/ingest", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(events),
    });
  },
};

Batching & Performance

Events are never sent one-by-one. The SDK queues events and flushes in batches:

  • Timer flush: every flushIntervalMs (default 3 s)
  • Size flush: when queue reaches maxSize (default 50 events)
  • Keepalive: uses fetch(..., { keepalive: true }) so batches survive page unloads
  • Retry: failed batches are retried up to maxRetries times with exponential backoff
  • Process safety: errors in export never throw or crash the host app
100 API calls → queue → [flush every 3s] → 2–3 batched uploads

Architecture

src/
├── types/          # Core interfaces (RequestTelemetryEvent, TelemetryConfig, …)
├── config/         # Config resolution, defaults, exporter endpoint registry
├── utils/          # ID gen, URL normalization, categorization, size helpers
├── enrichers/      # Raw data → normalized RequestTelemetryEvent
├── batching/       # BatchQueue with timer, size trigger, retry + backoff
├── interceptors/
│   ├── fetch.client.ts   # Browser fetch() patch
│   ├── xhr.client.ts     # Browser XMLHttpRequest patch
│   ├── fetch.server.ts   # Node.js global fetch() patch
│   └── http.server.ts    # Node.js http/https.request patch
├── exporters/
│   ├── console.ts        # Development console.table exporter
│   ├── hyperdx.ts        # HyperDX OTLP/HTTP exporter
│   └── otel.ts           # OTLP HTTP trace exporter
├── transport/      # Module-level registry, prevents double-install
├── runtime/        # Runtime environment detection
├── index.ts        # Client public API
└── server.ts       # Server public API

Key design decisions:

  • No singletons by default — the registry is module-scoped to the runtime (browser window or Node.js process), not a class static. This is the correct scope.
  • Safe monkey-patching — every interceptor checks __nrt_*_patched__ before installing and provides a restore function.
  • Tree-shakeablesideEffects: false. Server interceptors are in a separate entry point (/server) and never bundled into client code.
  • No any types — strictly typed throughout.
  • Exporter endpoint auto-exclusion — registered exporter URLs are excluded from capture automatically to prevent telemetry-on-telemetry loops.

Safety Guarantees

| Risk | Mitigation | |---|---| | Infinite loops (telemetry capturing itself) | Exporter URLs registered and auto-excluded | | Double-patching | __nrt_*_patched__ guard on every interceptor | | Crashing host app | All exporter errors are caught and logged, never re-thrown | | Memory leaks | Queue is drained on flush; destroy() for graceful shutdown | | Edge Runtime crashes | Server entry guarded by NEXT_RUNTIME === "nodejs" | | Performance overhead | Async queue; never blocks the intercepted request |


Environment Variables

| Variable | Used in | Description | |---|---|---| | HYPERDX_API_KEY | Server | HyperDX API key (server-side) | | HYPERDX_ENDPOINT | Server | HyperDX OTLP endpoint | | NEXT_PUBLIC_HYPERDX_API_KEY | Client | HyperDX API key (client-side) | | NEXT_PUBLIC_HYPERDX_ENDPOINT | Client | HyperDX OTLP endpoint | | NEXT_PUBLIC_SERVICE_NAME | Both | Service name | | NEXT_PUBLIC_SQUAD | Both | Team/squad identifier | | NEXT_PUBLIC_APP_VERSION | Both | App version / git SHA | | NEXT_RUNTIME | Server | Set by Next.js — used to guard Node-only code |


TypeScript

The package is written entirely in TypeScript. All types are exported:

import type {
  TelemetryConfig,
  TelemetryExporter,
  RequestTelemetryEvent,
  EventMetadata,
  RequestCategory,
  BatchingConfig,
  UrlCategorizerFn,
} from "next-request-telemetry";

License

MIT