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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@usageflow/express

v0.2.0

Published

UsageFlow plugin for Express applications

Readme

@usageflow/express

Express.js middleware for UsageFlow API tracking. Easily monitor and analyze your Express.js API usage with real-time tracking and allocation management.

npm version License: MIT

Installation

npm install @usageflow/express

Quick Start

const express = require('express');
const { ExpressUsageFlowAPI } = require('@usageflow/express');

const app = express();
app.use(express.json());

// Initialize UsageFlow with API key and optional pool size
const usageFlow = new ExpressUsageFlowAPI({
  apiKey: 'YOUR_API_KEY',
  poolSize: 5, // Optional: Number of WebSocket connections (default: 5)
});

// Create middleware
const middleware = usageFlow.createMiddleware(
  [
    { method: '*', url: '*' }, // Track all routes
  ],
  [
    { method: 'GET', url: '/api/health' }, // Whitelist health check
  ]
);

// Apply middleware
app.use(middleware);

// Your routes
app.get('/api/users', (req, res) => {
  res.json({ users: ['John', 'Jane'] });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

TypeScript Support

import express from 'express';
import { ExpressUsageFlowAPI } from '@usageflow/express';

const app = express();
app.use(express.json());

// Initialize UsageFlow with API key and optional pool size
const usageFlow = new ExpressUsageFlowAPI({
  apiKey: 'YOUR_API_KEY',
  poolSize: 5, // Optional: Number of WebSocket connections (default: 5)
});

// Create middleware
const middleware = usageFlow.createMiddleware(
  [
    { method: '*', url: '*' }, // Track all routes
  ],
  [
    { method: 'GET', url: '/api/health' }, // Whitelist health check
  ]
);

// Apply middleware
app.use(middleware);

// Your routes
app.get('/api/users', (req, res) => {
  res.json({ users: ['John', 'Jane'] });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Configuration

ExpressUsageFlowAPI

Constructor Options

interface UsageFlowAPIConfig {
  apiKey: string; // Your UsageFlow API key (required)
  poolSize?: number; // Number of WebSocket connections (default: 5)
}

createMiddleware

Creates Express middleware for tracking API usage.

createMiddleware(
  routes: Route[],           // Routes to track
  whitelistRoutes?: Route[]  // Routes to exclude from tracking
): (req: Request, res: Response, next: NextFunction) => Promise<void>

Route Configuration

interface Route {
  method: string; // HTTP method ('GET', 'POST', 'PUT', 'DELETE', etc.) or '*' for all methods
  url: string; // URL pattern or '*' for all URLs
}

Examples

Track all routes:

const middleware = usageFlow.createMiddleware([{ method: '*', url: '*' }]);

Track specific routes:

const middleware = usageFlow.createMiddleware([
  { method: 'GET', url: '/api/users' },
  { method: 'POST', url: '/api/users' },
  { method: 'PUT', url: '/api/users/:id' },
]);

Track with whitelist:

const middleware = usageFlow.createMiddleware(
  [
    { method: '*', url: '*' }, // Track all routes
  ],
  [
    { method: 'GET', url: '/api/health' }, // Exclude health check
    { method: 'GET', url: '/api/metrics' }, // Exclude metrics
  ]
);

Features

  • Automatic Route Detection: Automatically detects route patterns from Express router
  • Request Metadata Collection: Collects comprehensive request metadata including headers, query params, path params, and body
  • Response Tracking: Tracks response status codes and duration
  • WebSocket Communication: Uses WebSocket for real-time communication with UsageFlow API
  • Connection Pooling: Maintains a pool of WebSocket connections for better performance
  • Header Sanitization: Automatically sanitizes sensitive headers (authorization, API keys)
  • Error Handling: Gracefully handles errors and provides meaningful error messages

Request Metadata

The middleware automatically collects the following metadata for each request:

  • HTTP method
  • Route pattern
  • Raw URL
  • Client IP (with X-Forwarded-For support)
  • User agent
  • Timestamp
  • Headers (sanitized)
  • Query parameters
  • Path parameters
  • Request body
  • Response status code
  • Request duration

Error Handling

If an allocation request fails, the middleware will:

  1. Return a 400 status code
  2. Include an error message in the response
  3. Set blocked: true in the response body
// Error response format
{
  message: "Error message",
  blocked: true
}

Advanced Usage

Custom Route Pattern Extraction

The middleware automatically extracts route patterns from Express. It supports:

  • Direct route paths (req.route.path)
  • Router stack traversal
  • Nested routers
  • Parameterized routes (/users/:id)

Ledger ID Generation

The middleware automatically generates ledger IDs based on:

  1. HTTP method and route pattern
  2. Configured identity fields from UsageFlow policies
  3. Identity field locations (path params, query params, body, bearer token, headers)

Requirements

  • Node.js >= 18.0.0
  • Express >= 4.17.0
  • TypeScript >= 5.0.0 (for TypeScript projects)

Dependencies

  • @usageflow/core: Core UsageFlow functionality
  • express: Express.js framework

Development

# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm test

License

MIT

Support

For issues, questions, or contributions, please visit our GitHub repository.