@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.
Installation
npm install @usageflow/expressQuick 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:
- Return a 400 status code
- Include an error message in the response
- Set
blocked: truein 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:
- HTTP method and route pattern
- Configured identity fields from UsageFlow policies
- 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 functionalityexpress: Express.js framework
Development
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm testLicense
MIT
Support
For issues, questions, or contributions, please visit our GitHub repository.
