A high-performance, secure Backend API built with Node.js, Express, and MongoDB. This project integrates a robust Redis-backed Rate Limiting system, ensuring protection against DDoS attacks, brute-force attempts, and resource abuse.
- 🔐 Secure Authentication: JWT-based flow with Access and Refresh tokens (stored securely and invalidated on logout).
- 🛡️ Multi-Layered Middleware:
- Logging: Real-time request/response tracking via Winston.
- Security: CORS, multi-role authorization (RBAC), and IP-based rate limiting.
- ⚡ Redis Acceleration: Offloads rate limiting to Redis for sub-millisecond overhead and horizontal scalability.
- 📦 Reliable Storage: Mongoose-based data modeling with automated indexing.
- 🧩 Scalable Architecture: Domain-driven directory structure for easy maintenance and expansion.
The following diagram illustrates how a request flows through the API's security and processing layers:
sequenceDiagram
participant Client
participant RateLimiter as Redis Rate Limiter
participant Logger as Logger Middleware
participant Auth as Auth & RBAC
participant Controller
participant DB as MongoDB
Client->>RateLimiter: Incoming Request
RateLimiter->>RateLimiter: Check IP + Route Prefix
alt Limit Exceeded
RateLimiter-->>Client: 429 Too Many Requests
else Allowed
RateLimiter->>Logger: Pass to Logger
Logger->>Auth: Pass to Security
Auth->>Auth: Verify JWT + Roles
alt Unauthorized
Auth-->>Client: 401/403 Error
else Authorized
Auth->>Controller: Route Logic
Controller->>DB: CRUD Operation
DB-->>Controller: Data
Controller-->>Client: JSON Response (200 OK)
end
end
- Node.js: v20 or higher
- MongoDB: Atlas or local instance
- Redis: Cloud or local instance (use the port from
.env- this project defaults to13365)
-
Clone & Install:
git clone <repository-url> cd <repository-directory> pnpm install
-
Environment Configuration: Create a
.envfile from the example:cp .env.example .env
Variable Description MONGO_URIFull connection string for MongoDB REDIS_HOSTHostname of your Redis instance REDIS_PORTPort of your Redis instance REDIS_PASSWORDAuthentication password for Redis JWT_SECRETSecret for signing access tokens JWT_REFRESH_SECRETSecret for signing refresh tokens
- Development:
pnpm dev(Auto-restarts on changes) - Production:
pnpm start(Optimized start)
The API implements rate-limiter-flexible with a Redis backend. This architecture is crucial for distributed systems where multiple server nodes share the same limit state.
Key behaviors:
- The limiter key is based on the real client IP. If your app is behind a proxy/load balancer, it uses the first value from
x-forwarded-for(and falls back toreq.ip). - If Redis is temporarily unavailable or errors occur, the middleware is fail-open (requests are allowed through) to avoid taking your API down due to limiter storage issues.
| Endpoint Prefix | Points (Req) | Duration | Key Prefix | Purpose |
|---|---|---|---|---|
/users/register, /users/login |
5 | 60s | auth |
Prevent brute-force |
/users/me |
100 | 60s | profile |
Standard user limit |
/users/admin |
50 | 60s | admin |
Admin action protection |
| General | 5 | 60s | genericrl |
Default global fallback |
When a user exceeds the limit, the API returns a structured error:
{
"success": false,
"message": "Too Many Requests. Please try again later.",
"retryAfterSeconds": 45
}All responses include real-time rate limiting metadata:
X-RateLimit-Limit: Maximum requests allowed in the window.X-RateLimit-Remaining: Remaining points for the current client.X-RateLimit-Reset: Timestamp for when the limit resets. (Only on 429)Retry-After: Seconds to wait before retrying. (Only on 429)
POST /users/register
- Body:
{ "fullName": "...", "email": "...", "password": "..." } - Response:
201 Created
POST /users/login
- Body:
{ "email": "...", "password": "..." } - Response:
200 OKwith JSON containingaccess_tokenandrefresh_token.
POST /users/refresh
- Body:
{ "refresh_token": "..." } - Response: Generates a new pair of tokens.
GET /users/me
- Headers:
Authorization: Bearer <token> - Response: Details of the currently authenticated user.
GET /users/admin
- Headers:
Authorization: Bearer <admin_token> - Roles Required:
admin(the user must have at least one of the required roles in theirrolesarray) - Response:
200 OKwith a message confirming admin access.
.
├── config/ # Core configurations (Redis, MongoDB, Logger)
├── controllers/ # Logical entry points for routes
├── middleware/ # Security, Rate Limiting, Error handling
├── models/ # Mongoose schemas & data validation
├── routes/ # API route definitions & mapping
├── utils/ # JWT helpers, formatters, constants
├── logs/ # Local log files (app.log, errors.log)
└── index.js # Main application entry point- Ensure
MONGO_URIandREDIS_credentials are encrypted in your CI/CD. - Set
NODE_ENV=production. - Configure
trust proxyinindex.jsif deploying behind Load Balancers (AWS ALB, Nginx). - Enable
RateLimiterRedisto avoid "Memory Leaks" associated with local dev in-memory limiters.
This project is licensed under the MIT License.