This document explains the middleware used in the CodeX Club Backend. Middleware is responsible for processing requests before they reach the controllers and handling responses after the controllers finish execution.
Middleware is a function that executes during the request-response lifecycle.
It can:
- Authenticate users
- Validate requests
- Handle file uploads
- Add security headers
- Parse request data
- Log requests
- Handle errors
- Compress responses
Every incoming request passes through multiple middleware before reaching the API route.
Client Request
│
▼
Helmet
│
▼
Morgan Logger
│
▼
Rate Limiter
│
▼
Compression
│
▼
CORS
│
▼
JSON / URL Parser
│
▼
Cookie Parser
│
▼
Mongo Sanitization
│
▼
Authentication (Protected Routes)
│
▼
Controller
│
▼
Error Handler
│
▼
Client Response
The following middleware is applied to every request.
| Middleware | Purpose |
|---|---|
| Helmet | Adds security-related HTTP headers |
| Morgan | Logs incoming HTTP requests |
| Rate Limiter | Prevents excessive requests |
| Compression | Compresses responses for better performance |
| CORS | Allows requests from approved origins |
| Express JSON | Parses JSON request bodies |
| Express URL Encoded | Parses form data |
| Cookie Parser | Reads cookies from incoming requests |
| Express Static | Serves static files |
| Mongo Sanitize | Prevents NoSQL Injection attacks |
| Error Handler | Handles all application errors |
Helmet helps secure the application by automatically setting several HTTP security headers.
- Protect against common web vulnerabilities
- Improve browser security
- Hide unnecessary server information
Applied globally before all routes.
Morgan logs every incoming HTTP request.
- Request debugging
- Development logging
- API monitoring
Example log:
GET /api/v1/events 200 15ms
The backend limits repeated requests to reduce abuse.
| Property | Value |
|---|---|
| Window | 15 Minutes |
| Maximum Requests | 100 |
| Applied To | /api/* |
When the limit is exceeded:
429 Too Many RequestsResponse:
{
"message": "Too many requests from this IP, please try again after 15 minutes"
}Compression reduces the size of API responses before sending them to clients.
- Faster responses
- Reduced bandwidth usage
- Improved performance
Cross-Origin Resource Sharing controls which frontend applications can access the backend.
- Allowed Origin comes from
.env - Credentials are enabled
- Supports HTTP Only Cookies
Example
origin: process.env.CORS_ORIGIN
credentials: trueThe backend automatically parses incoming request data.
Supports JSON payloads up to:
16 KB
Supports HTML form submissions.
Maximum payload:
16 KB
Reads cookies sent by the browser.
Used for:
- JWT Authentication
- Session validation
Example
req.cookies.accessTokenServes public files from:
public/
Examples include:
- Uploaded images
- Temporary files
- Static assets
Protects the application against NoSQL Injection attacks.
Incoming data is sanitized from:
- Request Body
- URL Parameters
- Query Parameters
- Request Headers
This prevents malicious MongoDB operators such as:
$gt
$ne
$where
from being injected into queries.
Middleware Name
verifyJWT
This middleware protects administrator-only routes.
For every protected request:
Request
│
▼
Read JWT Cookie
│
▼
Verify JWT Signature
│
▼
Validate Session ID
│
▼
Check User Role
│
▼
Find Session
│
▼
Find Admin
│
▼
Attach Admin to Request
│
▼
Continue Request
The middleware performs the following checks:
Looks for a JWT in:
- HTTP Only Cookie
- Authorization Header
The token is verified using the application secret.
If verification fails:
401 UnauthorizedThe middleware checks whether:
- Session exists
- Session token matches
If not:
401 Session expired or invalidOnly administrators can access protected routes.
If another role attempts access:
403 Access DeniedThe authenticated administrator is loaded from the database.
The password field is excluded.
After successful authentication:
req.admin
req.sessionIdbecome available for controllers.
The backend uses Multer for handling file uploads.
Files are temporarily stored inside:
public/temp/
The directory is automatically created if it does not exist.
Uploaded files receive a unique filename.
Example
coverImage-1720953876123.png
This prevents filename collisions.
- Event Cover Images
- Team Member Photos
- Certificate Signatures
The error handler is registered after all routes.
app.use(errorHandler)
This ensures every application error is handled consistently.
The middleware:
- Handles custom API errors
- Handles Mongoose validation errors
- Converts unknown errors into API errors
- Sends consistent JSON responses
During development:
- Error stack traces are included
Example
{
"success": false,
"message": "Validation failed",
"stack": "..."
}In production:
- Stack traces are hidden
- Only safe error information is returned
Before the application starts serving requests:
- Environment variables are loaded.
- MongoDB connection is established.
- Default administrator is seeded.
- Express server starts listening.
- Global error handlers are registered.
The application listens for unexpected runtime errors.
Handles synchronous application crashes.
Example
ReferenceError
SyntaxError
Handles rejected Promises that were not caught.
Example
Database Connection Failure
API Failure
When detected, the server shuts down gracefully.
Helmet
│
Morgan
│
Rate Limiter
│
Compression
│
CORS
│
Body Parser
│
Cookie Parser
│
Static Files
│
Mongo Sanitize
│
API Routes
│
verifyJWT (Protected Routes Only)
│
Controller
│
Error Handler
│
Response
| Document | Description |
|---|---|
authentication.md |
Authentication and session flow |
api-reference.md |
Complete API documentation |
security.md |
Security features and protections |
database.md |
Database collections and models |
development-guide.md |
Backend development guidelines |