Introduction
API Management is essential for securing, monitoring, and scaling your services. It centralizes authentication, rate control, and observability. This tutorial walks you through building a professional API management layer with Express and TypeScript step by step. You will learn how to protect your endpoints while maintaining optimal performance.
Prerequisites
- Node.js 20+
- TypeScript 5+
- Basic knowledge of Express and REST
- npm or pnpm
Project Initialization
mkdir api-management && cd api-management
npm init -y
npm install express jsonwebtoken express-rate-limit helmet winston
npm install -D typescript @types/express @types/node ts-nodeThis command initializes the project and installs the core dependencies for API management: authentication, rate limiting, and structured logging.
TypeScript Configuration
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
}
}The tsconfig file configures TypeScript compilation for clean, modern code ready for production.
Basic Express Server
import express from 'express';
import helmet from 'helmet';
const app = express();
app.use(helmet());
app.use(express.json());
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date() });
});
app.listen(3000, () => console.log('API Management actif sur le port 3000'));This base server integrates Helmet for security and lays the foundation for a managed API with protected endpoints.
Rate Limiting Implementation
import rateLimit from 'express-rate-limit';
export const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: { error: 'Trop de requêtes, réessayez plus tard.' },
standardHeaders: true,
legacyHeaders: false,
});This middleware limits requests to 100 per IP every 15 minutes, protecting the API from abuse and DDoS attacks.
JWT Authentication
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
export const authenticate = (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Token manquant' });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!);
(req as any).user = decoded;
next();
} catch {
res.status(403).json({ error: 'Token invalide' });
}
};This middleware verifies JWT tokens to secure sensitive routes and inject user information into the request.
Best Practices
- Always use HTTPS in production
- Centralize middleware configuration
- Log all requests with correlation IDs
- Version your APIs (/v1/)
- Monitor metrics with Prometheus
Common Mistakes to Avoid
- Forgetting to handle async errors in middleware
- Applying rate limiting globally without exclusions
- Hardcoding secrets in the code
- Ignoring CORS and security headers
Going Further
Discover our advanced courses on API Management and microservices architecture: https://learni-group.com/formations