The E-Commerce API follows a classic three-tier architecture pattern with Express.js, organizing code into distinct layers that separate concerns and promote maintainability.
The Express application is initialized in app.mjs with a carefully ordered middleware stack:
app.mjs
import express from "express";import db from "./config/db.mjs";import { adminKeyAuth } from "./middlewares/adminMiddleware.mjs";import { apiKeyAuth, authenticate } from "./middlewares/authMiddleware.mjs";import publicRoutes from "./routes/publicRoutes.mjs";import adminRoutes from "./routes/adminRoutes.mjs";import authenticateRoutes from "./routes/authenticateRoutes.mjs";import { logMiddleware } from "./middlewares/logMiddleware.mjs";import cors from "cors";const app = express();const PORT = process.env.PORT || 5000;// Middleware stack (order matters!)app.use(logMiddleware); // Logging and rate limitingapp.use(cors()); // CORS headersapp.use("/uploads", express.static("uploads")); // Static filesapp.use(express.json()); // JSON body parsing// Route mounting with middleware chainsapp.use("/api/admin", adminKeyAuth, adminRoutes);app.use("/api", apiKeyAuth, publicRoutes);app.use("/api", apiKeyAuth, authenticate, authenticateRoutes);
The order of middleware is critical. Global middleware like logMiddleware and cors() are applied first, followed by route-specific middleware chains.
Request is logged with timestamp, IP address, user agent, and query/body parameters. Rate limiting is applied (100 requests per minute). Blocked IPs are rejected.See log middleware for details.
2
CORS middleware
Cross-Origin Resource Sharing headers are added to enable browser-based API consumption.
3
JSON body parser
Request body is parsed from JSON format into JavaScript objects accessible via req.body.
4
Route-specific middleware
Depending on the route prefix, authentication middleware is applied:
/api/admin/* - Admin API key validation
/api/* (public) - Standard API key validation
/api/* (authenticated) - API key + JWT token validation
5
Controller execution
The matched route handler (controller function) executes business logic, interacts with the database, and returns a response.
6
Response sent
Standardized JSON response is returned with status code, message, and optional data payload.
All responses use standardized format via successResponse() and errorResponse() helper functions for consistency.
If the database connection fails, the application will still start but API requests will fail. Ensure your database is running and environment variables are configured correctly.
Swagger/OpenAPI documentation is automatically served:
app.mjs
import swaggerUi from "swagger-ui-express";import { swaggerDocs, swaggerUiOptions } from "./docs/swaggerDef.mjs";app.use("/docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs, swaggerUiOptions));console.log(`API Docs available at http://localhost:${PORT}/docs`);
Interactive API documentation is available at /docs endpoint when the server is running.