Exercises — Middleware
Covers: middleware vs guards/interceptors decision matrix, class (NestMiddleware, DI) vs functional middleware, RequestLogger with request-ID correlation + res.on('finish') + status-based log levels, CORS via enableCors, Helmet via app.use(), hand-rolled in-memory rate limiter (429, window reset), configure(consumer) / MiddlewareConsumer API (forRoutes, exclude, method filtering, chaining), app.use() vs module registration rule of thumb, the 17-step full trace, error-path visibility.
Part A — Concept Checks (closed book)
- What can guards do that middleware cannot, and what is middleware's compensating advantage (position/knowledge trade-off)?
- Class vs functional middleware — the single deciding factor for choosing between them?
- Why does the app need a RequestLogger middleware when a LoggingInterceptor already exists? Name the exact blind spot.
res.on('finish')— when does it fire, and why does logging there capture more than the interceptor's timing?- Recite the request-ID pattern: where does the ID come from (2 sources), where is it attached (2 places), and why both?
- Which log level for 5xx, 4xx, 2xx/3xx — and the reasoning per level?
- Why is rate limiting middleware rather than a guard, according to the lesson? What computation is wasted if it's a guard?
- In the rate limiter, what does not calling
next()accomplish? What must you do instead? - The rule of thumb: which middleware goes in
main.tsviaapp.use()and which goes inconfigure()? - Write from memory: applying
RequestLoggerMiddlewareto all routes exceptGET /healthusingMiddlewareConsumer. - In the 17-step full trace, list steps 1–4 (the middleware) in order.
- On a 401-rejected request, why does the request logger still produce a log line while the LoggingInterceptor stays silent?
Part B — Guided Exercises
B1. RequestLoggerMiddleware
- Implement as class middleware: request-ID (reuse
x-request-idheader orrandomUUID()), attach toreq['requestId']and set response header, capturemethod/originalUrl/ip/user-agent, log inres.on('finish')with duration and status-based levels. - Register via
configure()in AppModule with.forRoutes('*'). - Verify: a 200, a 404, and a 401 all appear in logs with correct levels; the client sees
x-request-idin response headers; sending your ownx-request-id: my-trace-123echoes back.
B2. Rate limiter
- Implement the functional middleware:
Map<ip, {count, resetTime}>, 60s window. Set the limit to 5 so you can actually test it by hand. - Reject with the full standard envelope (429 + retry seconds) — match your filter's shape manually since filters don't run for middleware-issued responses.
- Register after the logger. Hammer an endpoint 6× and confirm the 6th gets 429 and still appears in the request logger output.
- Restore limit to 100.
B3. Helmet + CORS
npm i helmet,app.use(helmet())in main.ts. Verify viacurl -ithatX-Content-Type-Options,X-Frame-Optionsetc. appear.enableCorsallowing onlyhttp://localhost:3001with credentials. Test: from a quick HTML page (orcurl -H "Origin: http://evil.com" -i) observe the missingAccess-Control-Allow-Originheader for disallowed origins.
B4. Consumer API drills
Using only configure(), set up: - Rate limiter on POST /tasks and DELETE /tasks/:id only (RequestMethod filtering). - Logger everywhere except GET /health (create a tiny @Public() health route if you haven't). - A chained pair FirstMw, SecondMw (two 1-line console middlewares) proving execution order = apply order.
Part C — Independent Challenges
C1. Maintenance mode
MaintenanceMiddleware (class, DI): injects ConfigService; when MAINTENANCE=true, every route returns 503 { success:false, message: "Down for maintenance" } — except GET /health. Decide: exclusion via consumer .exclude() or an in-middleware path check? Try both, note which felt cleaner and why.
C2. Request body size sentinel
Functional middleware that rejects requests whose content-length exceeds 100KB with 413, before body parsing effort. Compare with what Express's body-parser limit option does — write 3 sentences on which you'd use in production.
C3. IP allowlist for admin routes
Middleware applied only to paths matching admin/*: allow a hardcoded IP list, 403 otherwise. Then answer: the lesson would arguably call role-checks guard territory — defend why IP filtering still belongs in middleware using the decision matrix.
C4. Correlated logging end-to-end
Thread requestId through the entire stack: exception filter includes it in error envelopes; the interceptor includes it in success envelopes; the logger prints it. One request, one ID, visible in every log line and in the client response. This is the Module 03 F1 stretch goal completed properly.
Part D — Debug Drills
D1
use(req: Request, res: Response, next: NextFunction) {
const requestId = randomUUID();
req['requestId'] = requestId;
res.setHeader('x-request-id', requestId);
// ...
}Symptom: every request hangs forever; client times out. The one-line omission?
D2
res.on('finish', () => { ... });
this.logger.log(`${method} ${originalUrl} → ${res.statusCode} (${Date.now() - startTime}ms)`);
next();Symptom: the log line always says status 200 and ~0ms even for slow 404s. Why is logging outside the callback wrong on both counts?
D3
if (record.count > MAX_REQUESTS) {
res.status(429).json({ ... });
}
next();Symptom: server crashes intermittently with ERR_HTTP_HEADERS_SENT under load. Explain the double-response bug.
D4
consumer.apply(RequestLoggerMiddleware).forRoutes('tasks');Symptom: /auth/login requests (Module 07) never show in logs; team assumed "全部" coverage. Fix + explain the path-matching scope.
D5
export function rateLimiterMiddleware(req, res, next) {
const requestCounts = new Map();
// ... same logic as lesson
}Symptom: nobody ever gets rate limited, no matter how hard you hammer. What moved, and why does it break the algorithm?
D6
@Injectable()
export class MaintenanceMiddleware implements NestMiddleware {
constructor(private config: ConfigService) {}
use(req, res, next) { ... }
}
// main.ts
app.use(new MaintenanceMiddleware(???));Why is app.use the wrong registration for this middleware, and what's the right home?
Part E — Prediction Drills
Full stack now: helmet → cors → logger → rate limiter → AuthGuard → RolesGuard → interceptors → pipe → controller.
DELETE /tasks/1, no token. List every layer that executes, in order, and the two log lines you'll see (or won't).- Rate limit exceeded on
POST /taskswith a valid token — does AuthGuard run? Does the request logger log it? What status? OPTIONS /taskspreflight from an allowed origin — does your controller run? Which layer answered?- A request with header
x-request-id: abcthat then 500s — where doesabcappear (client response headers? error body if you did C4? server logs?). GET /health(excluded from logger,@Public()): which of your custom layers touch it at all?
Part F — Stretch Goals
- Replace the hand-rolled limiter with
@nestjs/throttler; configure 10 req/min globally and@SkipThrottle()on health. Compare DX with your version. - Per-user (not per-IP) rate limiting: why is this suddenly guard/interceptor territory in the decision matrix? Implement it as a guard reading
request['user']. - Research
AsyncLocalStorage(ornestjs-cls) for request-ID propagation into services without passingreqaround.
Self-Assessment Checklist
- I can pick middleware vs guard vs interceptor vs pipe vs filter instantly via the matrix
- My logger captures EVERY request — including guard-rejected ones — with correlation IDs
- I can use every MiddlewareConsumer feature: forRoutes, exclude, method filters, chaining
- I know the app.use() vs configure() rule and have used both appropriately
- My rate limiter returns proper 429 envelopes and I understand its per-instance memory limits
- I can narrate the 17-step trace of a fully-armed request without notes
Answers & Hints
A1: Guards know the resolved controller/handler and can read decorator metadata via ExecutionContext. Middleware's advantage: it runs first (position zero) on raw req/res, stopping bad traffic before ANY NestJS processing — cheapest rejection point.
A2: Need DI (inject services)? → class. Self-contained? → functional.
A3: The interceptor runs after guards; guard-rejected (401/403) and rate-limited requests are invisible to it. Middleware + res.on('finish') sees literally every request/outcome.
A4: After the response is fully sent to the client — total wall time across all layers incl. serialization, vs the interceptor's controller+service slice.
A5: From incoming x-request-id header (gateway/client-supplied) or freshly generated UUID. Attached to req['requestId'] (downstream code access) and the response header (client can cite it in bug reports).
A6: 5xx → error (your bugs, alert-worthy); 4xx → warn (client mistakes/abuse monitoring); rest → log (normal traffic).
A7: It cares only about IP + count — no route/decorator context needed; as a guard, NestJS would already have parsed the body and resolved the route before rejecting. Wasted computation.
A8: The request stops dead — nothing downstream runs. You must send the response yourself (res.status(429).json(...)) and return.
A9: Third-party Express middleware applying to everything → app.use() in main.ts. Custom middleware needing route filtering or DI → module configure().
A10:
consumer.apply(RequestLoggerMiddleware)
.exclude({ path: 'health', method: RequestMethod.GET })
.forRoutes('*');A11: ① Helmet ② CORS ③ RequestLogger ④ RateLimiter.
A12: res.on('finish') fires on any completed response including errors; the interceptor's tap is skipped because the guard threw before interceptors even started.
D1: next() was never called — the chain stalls and no handler ever runs.
D2: Outside the callback, the log executes immediately during the request phase: statusCode still defaults to 200 (nothing sent yet) and elapsed ≈ 0. Both values are only correct after the response finishes.
D3: Missing return (and next() outside an else): the middleware sends the 429 AND calls next(), letting the pipeline also send a response — second write triggers headers-already-sent.
D4: forRoutes('tasks') scopes to the tasks path only. Use forRoutes('*') (or add the other controllers) for global coverage.
D5: The Map moved inside the function — recreated per request, so every request looks like the first in its window. Store must outlive requests (module scope; Redis in production).
D6: new MaintenanceMiddleware(???) can't get ConfigService — no DI in main.ts. Class middleware with dependencies must be registered in configure() so the container constructs it.
E1: helmet → cors → logger (registers finish callback) → rate limiter → AuthGuard throws → exception filter → 401 sent → logger finish callback logs [id] DELETE /tasks/1 → 401 (...) at warn. LoggingInterceptor: NO lines (never reached).
E2: No — middleware runs before guards, the limiter responds 429 directly; AuthGuard never executes. Logger still logs it (finish fires). Note: the filter/interceptors also never run — your middleware built the envelope manually.
E3: No controller — the CORS layer answers preflight with the Access-Control headers itself.
E4: Response header x-request-id: abc (set by middleware regardless of outcome); server logs [abc] ... → 500; error body includes it only if you wired C4.
E5: Helmet and CORS still apply (app.use = no exclusions), rate limiter (unless excluded), AuthGuard runs but returns true at the @Public check, interceptors + pipe wrap it — only the request logger skips it.
