A lightweight, feature-rich API Gateway built with Express.js and TypeScript, designed for microservices architectures. This gateway provides load balancing, service discovery, authentication, and request routing capabilities.
- Load Balancing: Multiple strategies including Round Robin and Least Used
- Service Registry: Dynamic service registration and deregistration
- Authentication: Basic authentication middleware
- Security: Helmet.js integration for security headers
- Health Management: Enable/disable service instances
- TypeScript: Full TypeScript support with type definitions
- Hot Reload: Development support with nodemon
- Installation
- Quick Start
- Configuration
- API Reference
- Load Balancing Strategies
- Architecture
- Development
- Examples
- Contributing
- Node.js (v14 or higher)
- npm or pnpm
- TypeScript
- Clone the repository:
git clone <your-repo-url>
cd API Gateway- Install dependencies:
npm install
# or
pnpm install- Build the project:
npm run buildnpm run devThe gateway will start on http://localhost:3000
npm run build
npm startAll requests require basic authentication:
- Username:
admin - Password:
password
Include the Authorization header in your requests:
Authorization: YWRtaW46cGFzc3dvcmQ=
Services are managed through the routes/registry.json file. The structure includes:
{
"services": {
"serviceName": {
"loadBalanceStrategy": "ROUND_ROBIN",
"index": 0,
"instances": [
{
"name": "serviceName",
"protocol": "http",
"host": "localhost",
"port": 3001,
"url": "http://localhost:3001/",
"usage": 0,
"enabled": true
}
]
}
}
}The gateway runs on port 3000 by default. You can modify this in gateway.ts:
const PORT = 3000;POST /register
Content-Type: application/json
Authorization: Basic YWRtaW46cGFzc3dvcmQ=
{
"name": "user-service",
"protocol": "http",
"host": "localhost",
"port": 3001
}POST /deregister
Content-Type: application/json
Authorization: Basic YWRtaW46cGFzc3dvcmQ=
{
"name": "user-service",
"url": "http://localhost:3001/"
}POST /enable/:serviceName
Content-Type: application/json
Authorization: Basic YWRtaW46cGFzc3dvcmQ=
{
"url": "http://localhost:3001/",
"enabled": true
}All requests to registered services are automatically routed:
GET /:serviceName/:path
POST /:serviceName/:path
PUT /:serviceName/:path
DELETE /:serviceName/:pathExample:
GET /user-service/api/usersThis will be forwarded to one of the registered instances of user-service.
Distributes requests evenly across all enabled instances in a circular fashion.
{
"loadBalanceStrategy": "ROUND_ROBIN"
}Routes requests to the instance with the lowest usage count.
{
"loadBalanceStrategy": "LEAST_USED"
}βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Client App ββββββ API Gateway ββββββ Microservice A β
βββββββββββββββββββ β β βββββββββββββββββββ
β βββββββββββββββ β βββββββββββββββββββ
β β Auth β ββββββ Microservice B β
β β Middleware β β βββββββββββββββββββ
β βββββββββββββββ β βββββββββββββββββββ
β βββββββββββββββ ββββββ Microservice C β
β βLoad Balancerβ β βββββββββββββββββββ
β βββββββββββββββ β
β βββββββββββββββ β
β β Registry β β
β βββββββββββββββ β
ββββββββββββββββββββ
- Gateway (
gateway.ts): Main Express.js application - Routes (
routes/index.ts): Request routing and service management - Auth (
utils/auth.ts): Basic authentication middleware - Load Balancer (
utils/loadbalancer.ts): Load balancing strategies - Registry (
routes/registry.json): Service registry database
βββ gateway.ts # Main application entry point
βββ package.json # Dependencies and scripts
βββ tsconfig.json # TypeScript configuration
βββ routes/
β βββ index.ts # Route handlers and service management
β βββ registry.json # Service registry
βββ utils/
β βββ auth.ts # Authentication middleware
β βββ loadbalancer.ts # Load balancing algorithms
βββ fakeapi/ # Test API for development
npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm start- Start production servernpm run test- Run tests (if configured)
- Add your strategy to
utils/loadbalancer.ts:
loadbalancer.CUSTOM_STRATEGY = (service: ServiceEntry) => {
// Your custom logic here
// Return the index of the selected instance
return selectedIndex;
};- Use it in your service configuration:
{
"loadBalanceStrategy": "CUSTOM_STRATEGY"
}- Start the Gateway:
npm run dev- Register a Service:
curl -X POST http://localhost:3000/register \
-H "Content-Type: application/json" \
-H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
-d '{
"name": "user-service",
"protocol": "http",
"host": "localhost",
"port": 3001
}'- Make Requests Through Gateway:
curl -X GET http://localhost:3000/user-service/api/users \
-H "Authorization: Basic YWRtaW46cGFzc3dvcmQ="# Register first instance
curl -X POST http://localhost:3000/register \
-H "Content-Type: application/json" \
-H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
-d '{
"name": "user-service",
"protocol": "http",
"host": "localhost",
"port": 3001
}'
# Register second instance
curl -X POST http://localhost:3000/register \
-H "Content-Type: application/json" \
-H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
-d '{
"name": "user-service",
"protocol": "http",
"host": "localhost",
"port": 3002
}'Now requests to /user-service/* will be load-balanced between both instances.
- Helmet.js: Automatically sets various HTTP headers for security
- Basic Authentication: All requests require valid credentials
- Request Validation: Input validation for service registration
- Error Handling: Comprehensive error handling with appropriate HTTP status codes
- JWT Authentication support
- Rate limiting
- Request/Response logging
- Health checks for registered services
- Circuit breaker pattern
- Metrics and monitoring
- Docker support
- WebSocket support
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the ISC License - see the LICENSE file for details.
- Express.js community for the robust web framework
- Helmet.js for security middleware
- TypeScript team for excellent type support
Note: This is a educational/development API Gateway. For production use, consider additional features like SSL termination, advanced authentication, monitoring, and scaling capabilities.