@usageflow/fastify
v0.5.0
Published
UsageFlow plugin for Fastify applications
Readme
@usageflow/fastify
Fastify plugin for UsageFlow API tracking. Easily monitor and analyze your Fastify API usage with real-time tracking and allocation management.
Installation
npm install @usageflow/fastifyQuick Start
import fastify from 'fastify';
import { FastifyUsageFlowAPI } from '@usageflow/fastify';
const app = fastify();
// Initialize UsageFlow with API key
const usageFlow = new FastifyUsageFlowAPI('YOUR_API_KEY');
// Register UsageFlow plugin
app.register(usageFlow.createPlugin());
// Your routes
app.get('/api/users', async () => {
return { users: ['John', 'Jane'] };
});
const start = async () => {
try {
await app.listen({ port: 3000 });
} catch (err) {
app.log.error(err);
process.exit(1);
}
};
start();Configuration
FastifyUsageFlowAPI
Constructor
constructor(apiKey: string)apiKey: Your UsageFlow API key (required)
createPlugin
Creates a Fastify plugin for tracking API usage. The plugin automatically tracks all routes and handles route configuration through the UsageFlow dashboard.
createPlugin(): FastifyPluginAsyncUsage
// Simple usage - tracks all routes automatically
const usageFlow = new FastifyUsageFlowAPI('YOUR_API_KEY');
app.register(usageFlow.createPlugin());Route configuration (which routes to track, whitelist, etc.) is managed through the UsageFlow dashboard, not through code parameters.
Features
- Fastify Plugin Architecture: Native Fastify plugin using
fastify-plugin - Automatic Route Detection: Automatically detects route patterns from Fastify routes
- 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: Custom error handler for UsageFlow errors
Request Metadata
The plugin automatically collects the following metadata for each request:
- HTTP method
- Route pattern (from
routeOptions.url) - 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
Hooks
The plugin uses Fastify hooks:
- onRequest: Intercepts incoming requests to collect metadata and send allocation requests
- onResponse: Intercepts responses to finalize allocation requests
Error Handling
The plugin includes a custom error handler that:
- Catches
UsageFlowErrorinstances - Returns a 400 status code
- Includes an error message in the response
- Sets
blocked: truein the response body
// Error response format
{
message: "Error message",
blocked: true
}Advanced Usage
Route Pattern Extraction
The plugin extracts route patterns from Fastify's routeOptions.url property, which provides the route pattern as defined in your route handlers.
Ledger ID Generation
The plugin 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
- Fastify >= 4.0.0
- TypeScript >= 5.0.0 (for TypeScript projects)
Dependencies
@usageflow/core: Core UsageFlow functionalityfastify-plugin: Fastify plugin utilities
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.
