Getting Started with UsageFlow

UsageFlow is a powerful API usage tracking and management solution that helps you monitor, control, and optimize your API usage across different frameworks and languages.

Quick Start

Choose your framework below to get started with UsageFlow integration:

Node.js Frameworks

Install the UsageFlow package for your Node.js framework:

# For Express.js
npm install @usageflow/express

# For Fastify
npm install @usageflow/fastify

# For NestJS
npm install @usageflow/nestjs

Express.js

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

const app = express();
const port = process.env.PORT || 4001;

// Initialize UsageFlow
const usageFlow = new ExpressUsageFlowAPI();
usageFlow.init('YOUR_API_KEY');

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

// Use the middleware
app.use(middleware);

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

Fastify

import fastify from 'fastify';
import { FastifyUsageFlowAPI } from '@usageflow/fastify';

const app = fastify();
const usageFlow = new FastifyUsageFlowAPI();

// Initialize UsageFlow
usageFlow.init('YOUR_API_KEY');

// Register UsageFlow plugin
app.register(
 usageFlow.createPlugin(
  [{ method: '*', url: '*' }],
  [{ method: 'GET', url: '/api/health' }]
 )
);

NestJS

import { Module } from '@nestjs/common';
import { UsageFlowModule } from '@usageflow/nestjs';

@Module({
 imports: [
  UsageFlowModule.forRoot({
   apiKey: 'YOUR_API_KEY',
   routes: [{ method: '*', url: '*' }],
   whitelistRoutes: [{ method: 'GET', url: '/api/health' }],
  }),
 ],
})
export class AppModule {}

Python Frameworks

Install the UsageFlow package for your Python framework:

# For FastAPI
pip install usageflow-fastapi

# For Flask
pip install usageflow-flask

FastAPI

from fastapi import FastAPI
from usageflow.fastapi import FastAPIUsageFlowAPI

app = FastAPI()
usage_flow = FastAPIUsageFlowAPI()

# Initialize UsageFlow
usage_flow.init('YOUR_API_KEY')

# Create middleware
middleware = usage_flow.request_interceptor(
    routes=[{'method': '*', 'url': '*'}],
    whitelist_routes=[{'method': 'GET', 'url': '/api/health'}]
)

# Add middleware to app
app.add_middleware(middleware)

Flask

from flask import Flask
from usageflow.flask import FlaskUsageFlowAPI

app = Flask(__name__)
usage_flow = FlaskUsageFlowAPI()

# Initialize UsageFlow
usage_flow.init('YOUR_API_KEY')

# Create and apply middleware
middleware = usage_flow.request_interceptor(
    routes=[{'method': '*', 'url': '*'}],
    whitelist_routes=[{'method': 'GET', 'url': '/api/health'}]
)
middleware(app)

Go

Install the UsageFlow package for Go:

# Install UsageFlow Go package
go get -u github.com/usageflow/go

Gin Framework

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/usageflow/go"
)

func main() {
    app := gin.New()

    usageAPI := usageflow.UsageFlowAPI{}
    usageAPI.Init("YOUR_API_KEY")

    routes := []usageflow.Route{
        {Method: "*", URL: "*"},
    }

    whitelist := []usageflow.Route{
        {Method: "GET", URL: "/api/health"},
    }

    // Apply middleware
    app.Use(usageAPI.RequestInterceptor(routes, whitelist))
}

Configuration Options

Route Patterns

UsageFlow supports various route patterns:

// Match all routes
{ method: '*', url: '*' }

// Match specific HTTP methods
{ method: 'GET', url: '/api/*' }
{ method: 'POST', url: '/api/users/*' }

// Match exact paths
{ method: 'PUT', url: '/api/users/:id' }

Whitelist Routes

Exclude specific routes from tracking using the whitelist configuration.

const whitelistRoutes = [
 { method: 'GET', url: '/api/health' },
 { method: 'GET', url: '/metrics' },
 { method: '*', url: '/internal/*' },
];

Metadata Collection

UsageFlow automatically collects:

  • Request method and URL
  • Client IP and User Agent
  • Headers (sanitized)
  • Query parameters
  • Request body (for POST/PUT)
  • Response status code
  • Timing information

Advanced Usage

Custom Metadata

Add custom metadata to your requests:

// Express.js example
app.use((req, res, next) => {
 req.usageflow = {
  metadata: {
   customField: 'value',
   userId: req.user?.id,
  },
 };
 next();
});

Error Handling

UsageFlow automatically tracks API errors, but you can customize error handling as needed.

// Express.js example
app.use((err, req, res, next) => {
 // UsageFlow will automatically track this error
 res.status(500).json({ error: 'Internal Server Error' });
});

Rate Limiting

Configure rate limits per endpoint:

const usageFlow = new ExpressUsageFlowAPI({
 rateLimits: {
  '/api/users': {
   limit: 1000,
   window: '1h',
  },
 },
});

Best Practices

  1. API Key Security

Never commit API keys to version control. Always use environment variables.

  1. Route Organization
    • Group similar endpoints under common prefixes
    • Use consistent naming conventions
    • Document route patterns clearly

Support

Need help? Contact our support team:

  • Email: [email protected]
  • Documentation: docs.usageflow.com
  • GitHub: github.com/usageflow