ReadMe Metrics SDK for Node.js

6.2.1 · active · verified Wed Apr 22

The `readmeio` package provides a Node.js SDK for integrating server-side API metrics with ReadMe.com's API Metrics Dashboard. This library, currently at version 6.2.1, allows developers to track API usage, troubleshoot issues, and gain deep insights into API performance. It supports both generic Node.js integrations and specific middleware for frameworks like Express.js, enabling the capture of incoming request and outgoing response details. Key differentiators include its tight integration with the ReadMe.com platform for centralized API documentation and metrics visualization, and robust features for redacting sensitive parameters or headers before logs are sent. The SDK helps teams monitor aggregate usage data and analyze specific API calls within the ReadMe ecosystem. While no explicit release cadence is published, the project is actively maintained, receiving regular updates to support new features and address issues.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize the ReadMe Metrics SDK, create a basic HTTP server, and log simulated API requests and responses, including data redaction for sensitive fields, to the ReadMe.com dashboard. Includes graceful shutdown.

import { Metrics } from 'readmeio';
import http from 'http';

// Initialize the ReadMe Metrics SDK
// In a real application, retrieve process.env.README_API_KEY and process.env.NODE_ENV securely
const metrics = new Metrics({
  apiKey: process.env.README_API_KEY ?? 'your_readme_api_key_here',
  development: process.env.NODE_ENV !== 'production',
});

// Create a simple HTTP server to simulate API calls
const server = http.createServer(async (req, res) => {
  // Simulate an incoming request
  const requestBody = { user: 'testuser', data: 'some data', sensitive_id: '12345' };
  const requestHeaders = {
    'content-type': 'application/json',
    'x-api-key': 'super-secret-internal-key', // Example of a header that might be redacted
    'user-agent': 'node-http-client',
  };

  // Simulate an outgoing response
  const responseBody = { status: 'success', message: 'Hello from API', internal_ref: 'xyz' };
  const responseHeaders = {
    'content-type': 'application/json',
    'x-response-id': 'uuid-12345',
  };

  // Log the request and response to ReadMe
  try {
    await metrics.log({
      // Full URL is important for ReadMe metrics to categorize endpoints
      url: new URL(`http://localhost:3000${req.url}`),
      method: req.method ?? 'GET',
      api: {
        key: 'user-id-123', // Identifier for the user making the API call
        // label: 'Optional label for this user/API key'
      },
      // Redaction example: prevent 'x-api-key' header from being sent to ReadMe
      // and prevent 'user' field in request body
      redact: {
        headers: ['x-api-key'],
        body: ['user', 'sensitive_id'],
      },
      request: {
        headers: requestHeaders,
        body: JSON.stringify(requestBody),
      },
      response: {
        status: 200,
        headers: responseHeaders,
        body: JSON.stringify(responseBody),
      },
    });
  } catch (error) {
    console.error('Failed to log metrics:', error);
  }

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(responseBody));
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
  console.log('Send a request, e.g., curl http://localhost:3000/api/test');
  console.log('Check your ReadMe.com dashboard for metrics.');
});

// Example of how to shut down cleanly
process.on('SIGINT', () => {
  console.log('Shutting down server...');
  server.close(async () => {
    // Ensure any buffered logs are sent before exiting
    try {
      await metrics.sendQueue();
      console.log('Buffered logs sent.');
    } catch (error) {
      console.error('Failed to send remaining logs:', error);
    }
    console.log('Server gracefully shut down.');
    process.exit(0);
  });
});

view raw JSON →