Middleware functions in the E-Commerce API handle cross-cutting concerns like authentication, logging, rate limiting, and file uploads. They execute in a specific order, forming a pipeline that processes requests before reaching route handlers.
The order of middleware registration determines execution order:
1
Log middleware
First in the chain - logs all requests, checks blocked IPs, and enforces rate limits
2
CORS middleware
Adds Cross-Origin Resource Sharing headers for browser requests
3
Static file middleware
Serves uploaded files from the /uploads directory
4
JSON body parser
Parses incoming JSON request bodies
5
Route-specific middleware
Authentication and authorization middleware applied per route group
Middleware order is critical. For example, logMiddleware must come before route handlers to capture all requests, and express.json() must come before routes that read req.body.
import { upload } from "../middlewares/fileUpload.mjs";import { uploadErrorHandler } from "../handler/responseHandler.mjs";router.post("/category", upload.single("image"), // Handles single file with field name "image" addCategory, // Controller function uploadErrorHandler // Error handler);
router.post("/product", upload.array("images"), // Handles multiple files with field name "images" addProduct, uploadErrorHandler);
Access uploaded files in controller:
productController.mjs
export const addProduct = async (req, res) => { if (!req.files || req.files.length === 0) { return errorResponse({ res, statusCode: 400, message: "At least one image file is required", }); } const imgUrls = req.files.map((file) => file.path.replaceAll("\\", "/")); // Store in database as JSON await db.execute( "INSERT INTO products (img_urls) VALUES (?)", [JSON.stringify(imgUrls)] );};
Why normalize file paths?
Windows uses backslashes (\) in file paths while URLs use forward slashes (/). The .replaceAll("\\", "/") call normalizes paths for consistent URL generation:
// Admin routes: Admin key onlyapp.use("/api/admin", adminKeyAuth, adminRoutes);// Public routes: API key onlyapp.use("/api", apiKeyAuth, publicRoutes);// Authenticated routes: API key + JWT tokenapp.use("/api", apiKeyAuth, authenticate, authenticateRoutes);
Each middleware calls next() to pass control to the next middleware or route handler. If any middleware sends a response or throws an error, the chain stops.
Order matters in middleware chains. Place authentication before authorization, and validation before business logic.