// API Gateway example for microservices
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const cors = require('cors');
const app = express();
const PORT = 8080;
// Add security headers
app.use(helmet());
// Enable CORS
app.use(cors());
// Basic request logging middleware
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} ${res.statusCode} - ${duration}ms`);
});
next();
});
// Apply rate limiting
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later'
});
app.use('/api/', apiLimiter);
// Authentication middleware
function authenticate(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized: Missing or invalid token' });
}
const token = authHeader.split(' ')[1];
// In a real app, verify the token (e.g., with JWT)
if (token === 'valid-token') {
// Add user info to request for downstream services
req.user = { id: 123, role: 'user' };
next();
} else {
res.status(401).json({ error: 'Unauthorized: Invalid token' });
}
}
// Service discovery (hardcoded for simplicity)
const serviceRegistry = {
userService: 'http://localhost:3001',
productService: 'http://localhost:3002',
orderService: 'http://localhost:3003'
};
// Proxy configurations
const userServiceProxy = createProxyMiddleware({
target: serviceRegistry.userService,
changeOrigin: true,
pathRewrite: { '^/api/users': '/users' }
});
const productServiceProxy = createProxyMiddleware({
target: serviceRegistry.productService,
changeOrigin: true,
pathRewrite: { '^/api/products': '/products' }
});
const orderServiceProxy = createProxyMiddleware({
target: serviceRegistry.orderService,
changeOrigin: true,
pathRewrite: { '^/api/orders': '/orders' }
});
// Route requests to appropriate services
app.use('/api/users', authenticate, userServiceProxy);
app.use('/api/products', productServiceProxy);
app.use('/api/orders', authenticate, orderServiceProxy);
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({ status: 'OK', timestamp: new Date() });
});
// Error handling
app.use((err, req, res, next) => {
console.error(`[ERROR] ${err.stack}`);
res.status(500).json({ error: 'Internal Server Error' });
});
// Start the server
app.listen(PORT, () => {
console.log(`API Gateway running on port ${PORT}`);
});