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

ga4-client

v1.0.0

Published

Type-safe GA4 Measurement Protocol client for Node.js

Readme

ga4-client

Type-safe Google Analytics 4 Measurement Protocol client for Node.js.

Features

  • Full TypeScript support with comprehensive types
  • Event batching with automatic flush
  • Retry with exponential backoff (5xx, 429)
  • Debug endpoint validation
  • Zero dependencies (native fetch)

Installation

npm install ga4-client

Quick Start

import { GA4Client, generateClientId } from 'ga4-client';

const client = new GA4Client({
  measurementId: 'G-XXXXXXXXXX',
  apiSecret: 'your-api-secret',
});

await client.send({
  client_id: generateClientId(),
  events: [{ name: 'purchase', params: { value: 99.99, currency: 'USD' } }],
});

API

GA4Client

const client = new GA4Client({
  measurementId: string;  // G-XXXXXXXXXX
  apiSecret: string;      // From GA4 Admin > Data Streams > Measurement Protocol
  baseUrl?: string;       // Default: 'https://www.google-analytics.com'
  timeoutMs?: number;     // Default: 30000
  debug?: boolean;        // Use debug endpoint
});

// Send single event
await client.send(event);

// Send batch (max 25 events)
await client.sendBatch(events);

// Send with retry (5xx, 429)
await client.sendWithRetry(events, { maxRetries: 3 });

// Validate without sending to production
const result = await client.debug(events);

GA4BatchHandler

import { GA4Client, GA4BatchHandler } from 'ga4-client';

const batch = new GA4BatchHandler(client, {
  batchSize: 20,         // Auto-flush threshold (1-25)
  flushIntervalMs: 5000, // Periodic flush interval
  maxRetries: 3,
  onFlush: (events) => console.log(`Sent ${events.length} events`),
  onError: (error, events) => console.error('Failed:', error),
});

batch.start();  // Start periodic flushing
await batch.add(event);
await batch.stop(); // Flush remaining and stop

Utilities

import { generateClientId, generateSessionId, toMicros } from 'ga4-client';

// Generate UUID v4 client identifier
const clientId = generateClientId();

// Generate session ID (Unix timestamp in seconds)
const sessionId = generateSessionId();

// Convert Date to microseconds for timestamp_micros
const timestamp = toMicros(new Date());

Error Handling

import { GA4Error, GA4ErrorCode } from 'ga4-client';

try {
  await client.send(event);
} catch (error) {
  if (error instanceof GA4Error) {
    console.log(error.code);       // GA4ErrorCode.RateLimited
    console.log(error.statusCode); // 429
    console.log(error.isRetryable()); // true
  }
}

Constants

import { GA4 } from 'ga4-client';

GA4.MAX_EVENTS;      // 25 - max events per request
GA4.MAX_EVENT_NAME;  // 40 - max event name length
GA4.MAX_PARAMS;      // 25 - max parameters per event
GA4.MAX_PARAM_VALUE; // 100 - max parameter value length

Event Structure

interface GA4Event {
  client_id: string;           // Required: UUID identifying the client
  user_id?: string;            // Cross-device user identifier
  timestamp_micros?: number;   // Event time (backdate up to 72h)
  user_properties?: Record<string, { value: string | number | boolean }>;
  events: Array<{
    name: string;              // Max 40 chars, alphanumeric + underscore
    params?: Record<string, string | number | boolean>;
  }>;
}

Credentials

  1. Measurement ID: GA4 Admin > Data Streams > select stream
  2. API Secret: GA4 Admin > Data Streams > select stream > Measurement Protocol > Create

Requirements

  • Node.js 22+

License

MIT