API Gateway Service
Relevant source files
The following files were used as context for generating this wiki page:The API Gateway is the single entry point for all client requests in the e-commerce microservices platform. It exposes a public REST API and communicates with backend microservices via a NATS message broker. Its primary responsibilities include request routing, composition, and implementing the Perimeter Security Pattern. This involves handling authentication, authorization, rate limiting, and audit logging at the edge of the system.
The Gateway is designed to be a lightweight and efficient layer, offloading business logic to the respective microservices. It translates incoming HTTP requests into NATS messages, forwards them to the appropriate service, and then transforms the NATS responses back into HTTP responses for the client. This architecture decouples clients from the internal microservice infrastructure and provides a centralized point for cross-cutting concerns.
Sources: README.md, apps/gateway/README.md, apps/gateway/REFACTORING-GUIDE.md
Architecture
The Gateway sits between the client and the internal microservices, acting as a reverse proxy and message translator.
Sources: deploys/README.md, SETUP.md
High-Level Data Flow
This diagram illustrates the overall request flow from the client, through the Gateway, to the backend services.
Sources: deploys/README.md, README.md, apps/gateway/README.md
Bootstrap Process
The application is initialized in apps/gateway/src/main.ts. During the bootstrap phase, several global configurations are applied to the NestJS application instance.
Sources: apps/gateway/src/main.ts
Key Configurations
- Global Filters:
HttpExceptionFilteris applied globally to catch and format HTTP exceptions, ensuring consistent error responses. - Global Pipes: A global
ValidationPipeis used to validate all incoming request DTOs. This enforces type correctness and validation rules defined withclass-validator.whitelist: true: Strips properties from the request body that are not defined in the DTO.forbidNonWhitelisted: true: Throws an error if non-whitelisted properties are present.transform: true: Automatically transforms plain request payloads into typed DTO instances.
- CORS: Cross-Origin Resource Sharing is enabled with a specific list of allowed origins, and credentials are permitted.
- Cache Control: HTTP caching is explicitly disabled by setting
Cache-Control,Pragma, andExpiresheaders on all responses to prevent stale data.
// File: apps/gateway/src/main.ts:16-48
async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
app.enableCors({
origin: [
'http://localhost:3000',
'http://localhost:3001',
'https://v0-eyewear-store-website-kohl.vercel.app',
'https://*.vercel.app',
],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'ngrok-skip-browser-warning'],
});
app.use((req: Request, res: Response, next: () => void) => {
res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
next();
});
const port = process.env.PORT || 3000;
await app.listen(port);
}
Sources: apps/gateway/src/main.ts:16-48
Perimeter Security
The Gateway implements the Perimeter Security pattern, where all security-related concerns are handled at the network edge. This centralizes security logic and simplifies the internal microservices, which can then trust incoming requests from the Gateway.
Sources: apps/gateway/REFACTORING-GUIDE.md
Security Components
| Feature | Implementation | Purpose |
|---|---|---|
| Authentication | AuthGuard with local JWT verification. | Verifies user identity before allowing access to protected routes. |
| Authorization | RolesGuard (inferred from tests). | Restricts access to endpoints based on user roles (e.g., ADMIN). |
| Rate Limiting | RateLimitMiddleware | Prevents DDoS and brute-force attacks by limiting requests per IP. |
| Audit Logging | AuditLogMiddleware | Creates an audit trail of all requests for security monitoring. |
Sources: apps/gateway/REFACTORING-GUIDE.md, apps/gateway/test/gateway.e2e-spec.ts
1. Authentication and Authorization
Authentication is handled by the AuthGuard, which verifies a JWT from the Authorization header. For performance, the token is verified locally within the Gateway using an RSA public key, without needing a round-trip to the user-app. The public key is distributed to the Gateway via NATS on startup.
Authorization is handled by a RolesGuard that checks the user's role (decoded from the JWT) against the roles required by the endpoint.
Sources: apps/gateway/README.md, deploys/README.md, apps/gateway/test/auth-authorization.integration.spec.ts
The following diagram shows the sequence for a protected endpoint request.
2. Middleware
The Gateway applies two key security middlewares to all incoming requests.
Sources: apps/gateway/REFACTORING-GUIDE.md
Rate Limiting Middleware
The RateLimitMiddleware protects against brute-force and DDoS attacks. It uses an in-memory store to track the number of requests from each IP address.
- Max Requests: 100 (per window)
- Window: 60,000 ms (1 minute)
Sources: apps/gateway/REFACTORING-GUIDE.md
Audit Logging Middleware
The AuditLogMiddleware logs structured information for every request after it has finished. This creates a security audit trail.
The following data is logged:
methodpathstatusCodedurationipuserId(if authenticated)
Sources: apps/gateway/REFACTORING-GUIDE.md, apps/gateway/src/middleware/audit-log.middleware.spec.ts
Middleware Configuration
Both middlewares are applied to all routes (*) in the main application module.
// Described in: apps/gateway/REFACTORING-GUIDE.md
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(AuditLogMiddleware, RateLimitMiddleware).forRoutes('*');
}
}
Sources: apps/gateway/REFACTORING-GUIDE.md
Communication Pattern
The Gateway uses a refactored pattern where controllers communicate directly with microservices via NATS, eliminating an unnecessary service layer within the Gateway itself. This is facilitated by a BaseGatewayController.
Sources: apps/gateway/REFACTORING-GUIDE.md
BaseGatewayController
All controllers in the Gateway extend the BaseGatewayController. This base class provides type-safe send and emit methods for interacting with the NATS ClientProxy.
// Described in: apps/gateway/REFACTORING-GUIDE.md
export abstract class BaseGatewayController {
constructor(protected readonly client: ClientProxy) {}
protected async send<TRequest, TResponse>(
pattern: string,
data: TRequest,
options: SendOptions = {},
): Promise<TResponse> {
// Implementation with timeout, retry, error handling
}
}
This pattern ensures that all communication is strongly typed, reducing runtime errors and improving maintainability.
Sources: apps/gateway/REFACTORING-GUIDE.md
Request-Response Flow
The following diagram shows the typical flow for a request that is forwarded to a microservice.
API Endpoints
The Gateway exposes a variety of REST endpoints, which are mapped to NATS messages for different microservices.
| Method | Path | Microservice | Description |
|---|---|---|---|
POST | /auth/register | user-app | Register a new user. |
POST | /auth/login | user-app | Log in and receive JWTs. |
GET | /auth/me | user-app | Get current user's profile. |
GET | /users | user-app | List all users (Admin only). |
GET | /users/:id | user-app | Get user details. |
GET | /products | product-app | List products with pagination. |
GET | /products/:id | product-app | Get product details. |
GET | /categories | product-app | List all categories. |
GET | /cart | cart-app | Get the current user's cart. |
POST | /cart/items | cart-app | Add an item to the cart. |
GET | /orders | order-app | List the current user's orders. |
POST | /orders | order-app | Create a new order. |
Sources: apps/gateway/README.md
Configuration
The Gateway is configured using environment variables.
| Variable | Description | Example |
|---|---|---|
PORT | The port on which the HTTP server listens. | 3000 |
CORS_ORIGIN | Comma-separated list of allowed origins for CORS. | http://localhost:3001,https://yourdomain.com |
NATS_URL | The connection URL for the NATS server. | nats://nats-host:4222 |
Sources: apps/gateway/README.md, deploys/README.md, apps/gateway/src/main.ts
Summary
The API Gateway is a critical component of the architecture, serving as a secure and robust entry point. By implementing the Perimeter Security pattern, it centralizes authentication, rate limiting, and logging, thereby simplifying the downstream microservices. Its direct, type-safe communication pattern with NATS ensures efficient and maintainable integration with the rest of the system.
Sources: apps/gateway/REFACTORING-GUIDE.md, README.md