Practice & Assessment
Test your understanding of Advanced Middleware Patterns
Multiple Choice Questions
5Why should in-memory rate limiting not be used in a multi-process production environment?
What is the correct Multer configuration option to restrict upload file size?
Which types of routes should NEVER be cached by response caching middleware?
Why should `app` and `server.listen()` be in separate files (app.js vs server.js)?
What does `body('field').trim().escape()` do in express-validator?
Coding Challenges
1Rate-Limited File Upload Endpoint
Build an Express endpoint POST /upload/avatar that accepts a single image file (JPEG/PNG/WebP only, max 2MB) using Multer with diskStorage saving to an uploads/ folder. Apply a rate limiter allowing max 5 uploads per minute per IP, returning 429 with Retry-After. Apply input sanitization to a required req.body.userId field (must be present, numeric). Return { filename, path, size, userId } on success. Return appropriate error messages for: wrong file type, oversized file, missing userId, rate limit exceeded. Inputs: multipart/form-data with file and userId. Time estimate: 25-30 minutes.
Mini Project
Production-Ready Middleware Stack
Scaffold a complete middleware-first Express application with the following structure: src/middleware/ (auth.js, validate.js, rateLimiter.js, cache.js, errorHandler.js, index.js barrel), src/routes/ (products.js, users.js), src/utils/ (asyncHandler.js, response.js), app.js, server.js. Implement: rate limiter (50 req/min global, 5 req/min on POST /auth/*), response cache on GET /products (2-min TTL), input sanitization on all POST/PUT routes, JWT auth on protected routes, global error handler. Routes: GET /products (public, cached), POST /products (authenticated admin only), POST /auth/login (rate limited), GET /users/me (authenticated). All middleware imported from the barrel file.
