Well-structured backends separate concerns: routers define URLs, controllers translate HTTP to application calls, services own data access, and middleware handles cross-cutting behavior (validation, 404, errors). Study these patterns to keep files small, testable, and aligned with REST conventions.
Router-level middleware
Matches Router-level middleware: validation and scoped CORS on specific routers.
Scope CORS to specific routers when only some paths need cross-origin access.
Learn: Router-scoped CORS limits cross-origin access to specific path prefixes—useful when only public API routes need browser access while admin routes stay same-origin only.
Run validation middleware before handlers so invalid body or params are rejected early.
Learn: Validate before controllers run so bad input never reaches the database. Return 400 with a clear message. Chain validators, then a small middleware that checks `validationResult` and stops the request.