@pawells/react-federation-service
v1.0.3-rc1
Published
Standalone NestJS service for React Module Federation — production-ready with caching, GraphQL, observability, and security
Maintainers
Readme
@pawells/react-federation-service
A production-ready, fully standalone NestJS service for managing React Module Federation, providing centralized module discovery, intelligent caching, version management, and lifecycle management for micro-frontend architectures.
Status: As of February 2025, this service is fully self-contained. The previously separate @pawells/react-federation-module package has been merged into this service, eliminating external dependencies and simplifying the dependency graph.
📋 Table of Contents
- Overview
- Quick Start
- Features
- Architecture
- Installation & Prerequisites
- Configuration
- Usage Examples
- API Overview
- Integration
- Testing
- Performance
- Security
- Troubleshooting
- Contributing
- Related Packages
- Support
Overview
The React Federation Service is a standalone NestJS microservice designed to serve Module Federation remotes for React applications. It provides a centralized, scalable solution for managing, versioning, caching, and serving dynamically loaded React components across distributed systems.
Key Use Cases
- 🎯 Dynamic Component Loading: Load React components at runtime without rebuilding the host application
- 🏗️ Micro-Frontend Architecture: Enable independent teams to develop and deploy React components
- 📦 Template Management: Centralized management of graphics templates for broadcast systems
- 🧪 A/B Testing: Serve different component versions to different users
- 🚀 Feature Flags: Enable/disable components dynamically without redeployment
- 👥 Multi-Tenant Applications: Serve tenant-specific components from a single service
Quick Start
Prerequisites
- Node.js: 18.0.0 or higher
- npm or yarn: Latest stable version
- MongoDB: 4.4+ (for template metadata storage)
- Redis: 6.0+ (for caching layer)
- Docker (optional): For containerized deployment
Installation
# Clone the repository
git clone https://github.com/pawells/react-federation-service.git
cd react-federation-service
# Install dependencies
npm install
# Or using yarn
yarn installEnvironment Setup
Create a .env file in the project root:
# Application Configuration
PORT=3000
NODE_ENV=development
LOG_LEVEL=info
# Database Configuration
MONGODB_URI=mongodb://localhost:27017
MONGODB_DB_NAME=react-federation
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
# Federation Configuration
FEDERATION_MODULE_PATHS=./modules
FEDERATION_CACHE_TTL=3600
FEDERATION_MAX_MODULES=100
# Security
JWT_SECRET=your-secret-key-change-in-production
JWT_EXPIRATION=15m
API_KEY_SECRET=your-api-key-change-in-production
CORS_ORIGINS=http://localhost:3100,http://localhost:4200
# Observability
OTEL_EXPORTER_JAEGER_ENDPOINT=http://localhost:14268/api/traces
OTEL_SERVICE_NAME=react-federation-service
OTEL_TRACING_ENABLED=true
# Monitoring
PROMETHEUS_ENABLED=true
PROMETHEUS_PORT=9090
METRICS_ENABLED=trueRunning the Service
# Development mode with hot reload
npm run start:dev
# Production mode
npm run build
npm run start
# Debug mode
npm run start:debug
# Watch mode for development
npm run start -- --watchVerify Installation
# Check health status
curl http://localhost:3000/health
# Check readiness
curl http://localhost:3000/health/ready
# Check liveness
curl http://localhost:3000/health/live
# View metrics
curl http://localhost:3000/metricsFeatures
✅ Module Federation Support
- Serves Webpack 5+ Module Federation remotes with version management
- Dynamic module loading and unloading
- Dependency resolution and version negotiation
✅ Version Management
- Semantic versioning (MAJOR.MINOR.PATCH)
- Version history tracking with timestamps
- Rollback capabilities to previous versions
- Version comparison and compatibility checking
✅ Intelligent Caching
- Multi-level caching (in-memory + Redis)
- TTL-based cache expiration
- Event-driven cache invalidation
- Cache statistics and monitoring
✅ Template Registry
- Metadata-driven template discovery
- Schema validation for templates
- Template categorization and tagging
- Full-text search capabilities
✅ Health Monitoring
- Comprehensive health checks (liveness, readiness, startup)
- Dependency health monitoring
- Kubernetes integration support
- Detailed health status reporting
✅ Performance Optimization
- Code splitting and lazy loading
- Bundle size monitoring
- Gzip and Brotli compression
- HTTP caching headers
✅ Security
- API key authentication
- JWT token validation
- Rate limiting
- CORS configuration
- Security headers (CSP, X-Frame-Options, etc.)
- Input validation and sanitization
✅ Observability
- Prometheus metrics collection
- OpenTelemetry distributed tracing
- Structured logging
- Request/response logging
✅ Flexible Deployment
- Standalone service
- Docker containerization
- Docker Compose orchestration
- Kubernetes deployment
- Cloud platform support (AWS, GCP, Azure)
Architecture
High-Level Architecture
┌─────────────────────────────────────────────────────────────┐
│ React Federation Service │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ REST API Layer │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │ │
│ │ │ Federation │ │ Templates │ │ Health │ │ │
│ │ │ Controller │ │ Controller │ │ Ctrl │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Business Logic Layer │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │ │
│ │ │ Federation │ │ Template │ │ Version │ │ │
│ │ │ Service │ │ Registry │ │ Manager │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Data Access Layer │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │ │
│ │ │ Cache │ │ File Storage │ │ Database │ │ │
│ │ │ Manager │ │ Service │ │ Service │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ External Services │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │ │
│ │ │ Redis Cache │ │ File System │ │ Database │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘Design Patterns
- Service-Oriented Architecture: Separation of concerns with dedicated services
- Dependency Injection: NestJS DI container for loose coupling
- Cache-Aside Pattern: Check cache first, load from source on miss
- Semantic Versioning: Major.Minor.Patch versioning scheme
- Event-Driven Architecture: Cache invalidation via events
Installation & Prerequisites
System Requirements
| Component | Minimum | Recommended | | --------- | ------- | ----------- | | Node.js | 18.0.0 | 20.0.0+ | | npm | 9.0.0 | 10.0.0+ | | MongoDB | 4.4 | 6.0+ | | Redis | 6.0 | 7.0+ | | Memory | 512MB | 2GB+ | | Disk | 1GB | 10GB+ |
Dependencies
{
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/config": "^3.0.0",
"@nestjs/cache-manager": "^2.0.0",
"@nestjs/graphql": "^12.0.0",
"@nestjs/terminus": "^10.0.0",
"@pawells/react-federation-module": "^0.1.0",
"@pawells/nestjs-shared": "^0.1.0",
"express": "^4.18.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.0",
"joi": "^17.9.0",
"semver": "^7.5.0"
}Configuration
Environment Variables
See Configuration Guide for comprehensive configuration options.
Configuration File
// config/federation.config.ts
export const federationConfig = {
service: {
name: 'react-federation-service',
port: parseInt(process.env.PORT || '3000', 10),
environment: process.env.NODE_ENV || 'development',
},
redis: {
host: process.env.REDIS_HOST || 'localhost',
port: parseInt(process.env.REDIS_PORT || '6379', 10),
password: process.env.REDIS_PASSWORD,
},
database: {
uri: process.env.MONGODB_URI || 'mongodb://localhost:27017',
name: process.env.MONGODB_DB_NAME || 'react-federation',
},
security: {
jwtSecret: process.env.JWT_SECRET,
apiKeySecret: process.env.API_KEY_SECRET,
corsOrigins: (process.env.CORS_ORIGINS || '').split(','),
},
};Usage Examples
REST API Example
# Get available remotes
curl -X GET http://localhost:3000/api/v1/federation/remotes \
-H "X-API-Key: your-api-key"
# Get remote entry point
curl -X GET http://localhost:3000/api/v1/federation/lower-third/1.0.0/remoteEntry.js \
-H "X-API-Key: your-api-key"
# Register a template
curl -X POST http://localhost:3000/api/v1/templates \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"name": "lower-third",
"version": "1.0.0",
"category": "graphics",
"scope": "@cg/lower-third",
"module": "./LowerThird"
}'
# List templates
curl -X GET http://localhost:3000/api/v1/templates \
-H "X-API-Key: your-api-key"GraphQL Example
query GetTemplates {
templates {
name
version
category
tags
lastUpdated
}
}
mutation RegisterTemplate($input: RegisterTemplateInput!) {
registerTemplate(input: $input) {
name
version
message
}
}TypeScript Integration
import { FederationService } from '@pawells/react-federation-service';
// Get remote entry point
const remoteEntry = await federationService.getRemoteEntry('lower-third', '1.0.0');
// Get available remotes
const remotes = await federationService.getAvailableRemotes();
// Get template metadata
const metadata = await federationService.getRemoteMetadata('lower-third', '1.0.0');API Overview
Core Endpoints
| Method | Endpoint | Description |
| ------ | -------------------------------------------------- | -------------------------- |
| GET | /api/v1/federation/remotes | List all available remotes |
| GET | /api/v1/federation/:name/:version/remoteEntry.js | Get remote entry point |
| GET | /api/v1/federation/:name/:version/metadata | Get remote metadata |
| POST | /api/v1/federation/:name/:version/validate | Validate remote |
| GET | /api/v1/templates | List templates |
| POST | /api/v1/templates | Register template |
| GET | /api/v1/templates/:name | Get template |
| PUT | /api/v1/templates/:name/:version | Update template |
| DELETE | /api/v1/templates/:name/:version | Delete template |
| GET | /health | Health status |
| GET | /health/ready | Readiness probe |
| GET | /health/live | Liveness probe |
See API Documentation for detailed endpoint documentation.
Integration
With @pawells/react-federation-module
The service integrates seamlessly with the @pawells/react-federation-module package:
import { FederationModule } from '@pawells/react-federation-module';
@Module({
imports: [FederationModule.forRoot(federationConfig)],
})
export class AppModule {}With @pawells/nestjs-shared
Uses shared NestJS utilities for common functionality:
import { SharedModule } from '@pawells/nestjs-shared';
@Module({
imports: [SharedModule],
})
export class AppModule {}With Host Applications
Configure Module Federation in your host application:
// webpack.config.js
new ModuleFederationPlugin({
remotes: {
'@cg/lower-third': 'lower_third@http://localhost:3000/api/v1/federation/lower-third/latest/remoteEntry.js',
},
shared: {
react: { singleton: true, strictVersion: false },
'react-dom': { singleton: true, strictVersion: false },
},
});See Integration Guide for comprehensive integration instructions.
Testing
Run Tests
# Run all tests
npm run test
# Run tests in watch mode
npm run test -- --watch
# Run tests with coverage
npm run test:cov
# Run specific test file
npm run test -- federation.service.spec.tsTest Coverage
Target coverage metrics:
- Statements: ≥ 80%
- Branches: ≥ 75%
- Functions: ≥ 80%
- Lines: ≥ 80%
See Testing Guide for detailed testing guidelines.
Performance
Response Time Targets
| Endpoint | Target | SLA | | ----------------- | ------- | ------ | | Get Remote Entry | < 100ms | 99.9% | | Get Metadata | < 50ms | 99.9% | | List Templates | < 200ms | 99% | | Register Template | < 500ms | 99% | | Health Check | < 10ms | 99.99% |
Throughput
- Requests per Second: 1,000+ RPS
- Concurrent Connections: 10,000+
- Cache Hit Rate: > 95%
See Performance Guide for optimization strategies.
Security
Authentication
- ✅ API Key authentication via
X-API-Keyheader - ✅ JWT token validation
- ✅ Rate limiting (100 requests per 15 minutes by default)
Security Headers
- ✅ Content Security Policy (CSP)
- ✅ X-Frame-Options: DENY
- ✅ X-Content-Type-Options: nosniff
- ✅ Strict-Transport-Security
- ✅ X-XSS-Protection
Input Validation
- ✅ Request body validation
- ✅ Parameter validation
- ✅ Schema validation for templates
See Security Guide for comprehensive security information.
Troubleshooting
Common Issues
Issue: Service fails to start with MongoDB connection error
Solution: Ensure MongoDB is running and MONGODB_URI is correctIssue: Cache not working
Solution: Verify Redis is running and REDIS_HOST/REDIS_PORT are correctIssue: 401 Unauthorized errors
Solution: Ensure X-API-Key header is included in requestsIssue: High memory usage
Solution: Check cache size limits and adjust CACHE_MAX_SIZE if neededSee Troubleshooting Guide for more issues and solutions.
Contributing
We welcome contributions! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Code Style
- Follow TypeScript best practices
- Use ESLint and Prettier for formatting
- Write unit tests for new features
- Update documentation
Commit Messages
feat: Add new feature
fix: Fix bug
docs: Update documentation
test: Add tests
refactor: Refactor codeRelated Packages
- @pawells/react-federation-module: Core federation functionality
- @pawells/nestjs-shared: Shared NestJS utilities
- @pawells/react-federation-client: Client library for consuming remotes
Support
Documentation
Getting Help
- 📖 Check the documentation
- 🐛 Report bugs on GitHub Issues
- 💬 Join our community discussions
- 📧 Email: [email protected]
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
See CHANGELOG.md for version history and updates.
Last Updated: January 15, 2026 Maintainer: Technical Documentation Team Version: 0.1.0
