api-response-time-tracker
v1.0.1
Published
Middleware and utilities for tracking and logging API response times in BFF architecture
Downloads
88
Maintainers
Readme
API Response Time Tracker
Documentation moved to
docs/folder!
For complete documentation, see docs/INDEX.md
A comprehensive Node.js module for tracking and logging API response times in Backend-For-Frontend (BFF) architecture. Track both BFF processing time and downstream service response times with automatic header attachment and structured logging.
🆕 Recent Updates
v1.0.1 (December 20, 2025)
- ✅ Enhanced TimingLogger: Improved service timing handling to support both numeric values and structured timing objects
- ✅ Better Data Flexibility: TimingLogger now automatically handles both legacy format (numeric) and new format (object with
duration_ms) - ✅ Bug Fixes: Fixed import path in example.js for proper module resolution
📦 Installation
npm install api-response-time-trackerMinified Version Available: The package includes both source and minified versions (~46% smaller).
// Use regular version (recommended for development)
const { ResponseTimeTracker } = require('api-response-time-tracker');
// Use minified version (production)
const { ResponseTimeTracker } = require('api-response-time-tracker/dist');✨ Features
- ✅ Express Middleware - Easy integration with Express applications
- ✅ Response Time Tracking - Automatically track BFF response times
- ✅ Service Time Tracking - Track individual downstream service call durations
- ✅ Response Headers - Attach timing information to response headers
- ✅ Structured Logging - Comprehensive logging with configurable logger support
- ✅ Design Patterns - Factory, Singleton, Observer, and Strategy patterns
- ✅ Complete Tests - 100% test coverage with Jest
- ✅ Zero Dependencies - Core module has no external dependencies
- ✅ Minified Build - Includes minified version (46% smaller) for production use
🚀 Quick Start
npm install
npm run structure # View project structure
npm test # Run tests
npm start # Run BFF example📖 Documentation
All documentation has been moved to the docs/ folder for better organization.
| Document | Purpose | |----------|---------| | docs/QUICK_START.md | Get started in 5 minutes | | docs/README.md | Complete API documentation | | docs/DESIGN_PATTERNS.md | Design patterns guide | | docs/TESTING.md | Testing guide | | docs/INDEX.md | Documentation index |
💡 Basic Usage
const express = require('express');
const { ResponseTimeTracker, ServiceTimingTracker } = require('./index');
const app = express();
const tracker = new ResponseTimeTracker();
app.use(tracker.middleware());
app.get('/api/users/:id', async (req, res) => {
const user = await ServiceTimingTracker.track(
req,
'userService',
() => getUserFromDatabase(req.params.id)
);
res.json({ user });
});
app.listen(3000);📁 Project Structure
api-response-time-tracker/
├── docs/ # 📚 All documentation
├── patterns/ # 🎨 Design patterns
├── services/ # 🔧 Sample services
├── __tests__/ # 🧪 Test suite
├── scripts/ # 🛠️ Utility scripts
├── examples/ # 💡 Examples
└── Core modules (root) # 📦 Main filesSee docs/PROJECT_STRUCTURE.md for details.
🎯 Common Use Cases
Single Service Call
const data = await ServiceTimingTracker.track(
req,
'myService',
() => callMyService()
);Parallel Service Calls (BFF Pattern)
const results = await ServiceTimingTracker.trackParallel(req, [
{ name: 'userService', call: () => getUser(userId) },
{ name: 'orderService', call: () => getOrders(userId) },
{ name: 'paymentService', call: () => getPayments(userId) }
]);With Design Patterns
const TimingFactory = require('./patterns/TimingFactory');
// Create tracker with preset
const tracker = TimingFactory.createTracker('production');📊 Response Headers
X-Response-Time: 487.23ms
X-Service-Times: userService=152.34ms, orderService=203.45ms🧪 Testing
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:verbose # Verbose output
npm run validate # Validate structure📚 API Reference
Core Classes
- ResponseTimeTracker - Express middleware for tracking BFF response time
- ServiceTimingTracker - Utility for tracking downstream service calls
- TimingLogger - Structured logging utility
Design Patterns
- TimingFactory - Factory pattern for creating trackers
- PerformanceObserver - Observer pattern for monitoring metrics
- LoggingStrategy - Strategy pattern for flexible logging
See docs/README.md for complete API documentation.
🎓 Examples
- example.js - Basic example with mock services
- services/bff-app.js - Complete BFF application
- USAGE_EXAMPLES.js - 10+ practical examples
🏗️ Design Patterns
This module implements four professional design patterns:
- Factory Pattern - Flexible object creation with presets
- Singleton Pattern - Shared state across the application
- Observer Pattern - Performance event monitoring
- Strategy Pattern - Pluggable logging strategies
See docs/DESIGN_PATTERNS.md for detailed explanations.
🔧 Configuration
Environment Variables
Copy .env.example to .env:
cp .env.example .envAvailable variables:
PORT- Server port (default: 3000)NODE_ENV- Environment (development, production, test)LOG_LEVEL- Logging level (info, warn, error)
📦 NPM Scripts
| Command | Description |
|---------|-------------|
| npm test | Run tests with coverage |
| npm run test:watch | Watch mode |
| npm run test:verbose | Verbose output |
| npm start | Run BFF application |
| npm run start:dev | Run with nodemon |
| npm run example | Run basic example |
| npm run structure | Display structure |
| npm run validate | Validate structure |
📋 Support
Getting Help
- Quick questions? Check docs/QUICK_START.md
- Need API details? See docs/README.md
- Testing help? Read docs/TESTING.md
- Pattern explanations? Check docs/DESIGN_PATTERNS.md
Need More Information?
See the complete documentation index at docs/INDEX.md
📈 Performance Metrics
- Middleware Overhead: ~0.1ms per request
- Service Tracking: ~0.05ms per service call
- No External Dependencies: Fast and lightweight
🔐 Security
- ✅ No sensitive data logged by default
- ✅ Environment-based configuration
- ✅ Headers are customizable
- ✅ Logging strategies are pluggable
📄 License
MIT
📝 Changelog
v1.0.1 (December 20, 2025)
- Enhanced
TimingLoggerto handle both numeric and object-based service timing data - Improved backward compatibility with legacy timing formats
- Fixed import path in examples/example.js
v1.0.0
- Initial release with core functionality
- ResponseTimeTracker, ServiceTimingTracker, and TimingLogger
- Design patterns implementation
- Complete test coverage
For detailed changelog, see CHANGELOG.md
🤝 Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new features
- Run
npm testto verify - Submit a pull request
See docs/TESTING.md for testing guidelines.
Start here: docs/QUICK_START.md
Full docs: docs/README.md
All guides: docs/INDEX.md
