@usageflow/nestjs
v0.4.1
Published
UsageFlow plugin for NestJS applications
Readme
@usageflow/nestjs
NestJS module for UsageFlow API tracking. Easily monitor and analyze your NestJS API usage with real-time tracking and allocation management.
Installation
npm install @usageflow/nestjsQuick Start
// app.module.ts
import { Module } from '@nestjs/common';
import { UsageFlowModule } from '@usageflow/nestjs';
@Module({
imports: [
UsageFlowModule.forRoot({
apiKey: 'YOUR_API_KEY',
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}Configuration
UsageFlowModule.forRoot
Configures the UsageFlow module with your API key. The module automatically tracks all routes and handles route configuration through the UsageFlow dashboard.
UsageFlowModule.forRoot({
apiKey: string; // Your UsageFlow API key (required)
})Examples
Basic usage:
UsageFlowModule.forRoot({
apiKey: 'YOUR_API_KEY',
});Route configuration (which routes to track, whitelist, etc.) is managed through the UsageFlow dashboard, not through code parameters. The middleware is automatically applied to all routes.
Advanced Configuration
Using UsageFlowService Directly
You can inject UsageFlowService into your services or controllers:
import { Injectable } from '@nestjs/common';
import { UsageFlowService } from '@usageflow/nestjs';
@Injectable()
export class MyService {
constructor(private readonly usageFlowService: UsageFlowService) {}
async someMethod() {
// Access UsageFlowService methods
const apiKey = this.usageFlowService.getApiKey();
// ...
}
}Using UsageFlowRouteScanner
The module includes a route scanner that automatically detects routes in your NestJS application:
import { Injectable } from '@nestjs/common';
import { UsageFlowRouteScanner } from '@usageflow/nestjs';
@Injectable()
export class MyService {
constructor(private readonly routeScanner: UsageFlowRouteScanner) {}
async someMethod() {
// Match a route pattern
const pattern = this.routeScanner.match('GET', '/api/users/123');
// Returns: '/api/users/:id' (if matched)
}
}Features
- NestJS Module Architecture: Native NestJS module with dependency injection
- Automatic Route Scanning: Automatically scans and matches NestJS 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: Gracefully handles errors and provides meaningful error messages
- Express and Fastify Support: Works with both Express and Fastify adapters
Request Metadata
The middleware automatically collects the following metadata for each request:
- HTTP method
- Route pattern (detected from NestJS routes)
- 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
Route Pattern Detection
The module uses multiple methods to detect route patterns:
- Route Scanner: Scans the Express/Fastify router stack to build a route map
- Request Route Path: Uses
req.route.pathwhen available - Router Stack Traversal: Searches through the router stack for matching routes
- Parameter Reconstruction: Reconstructs route patterns from path parameters
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
}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
- NestJS >= 10.0.0
- TypeScript >= 5.0.0
Dependencies
@usageflow/core: Core UsageFlow functionality@nestjs/common: NestJS common utilities@nestjs/core: NestJS core functionality
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.
