20 Express Middleware Routing
20 Express Middleware Routing
Overview
Express is the backbone of your WorkBuddy/LearnSphere APIs — understanding its middleware chain deeply
helps you debug request lifecycles and design clean, maintainable route structures.
Key Concepts
• Middleware Function Signature: A function (req, res, next) that can inspect/modify the request or
response, end the request-response cycle, or call next() to pass control to the next middleware in the stack.
• Application-Level vs Router-Level Middleware: Application-level middleware ([Link]) applies globally or
to specific paths; router-level middleware ([Link]()) scopes middleware and routes to a modular,
mountable router instance.
• Error-Handling Middleware: A special middleware with four parameters (err, req, res, next) that Express
recognizes as an error handler, typically placed last in the middleware stack to catch errors passed via
next(err).
• Route Parameters & Query Strings: Route params (/users/:id) capture dynamic path segments accessible
via [Link]; query strings (?sort=asc) are accessible via [Link] — both are commonly used for
filtering/identifying resources.
• Middleware Execution Order: Middleware executes in the exact order it's registered; a middleware that
doesn't call next() or send a response will hang the request indefinitely.
• Common Middleware: body-parser/[Link]() (parses JSON request bodies), cors (handles cross-origin
requests), helmet (sets security-related HTTP headers), morgan (request logging), and custom auth
middleware (verifying JWTs before protected routes).
• Async Error Handling: Express doesn't automatically catch errors thrown inside async route handlers (pre-
Express 5) — they must be caught explicitly and passed to next(err), often via a wrapper utility or try/catch.
• RESTful Route Structuring: Organizing routes by resource (e.g., /api/jobs, /api/jobs/:id) with appropriate
HTTP methods mapped to CRUD operations, kept modular via separate router files per resource.
Common Interview Questions
Q1. What happens if a middleware function doesn't call next() or send a response?
The request hangs indefinitely — the client will eventually time out since Express has no way to know the
middleware is 'done' without either next() (continue the chain) or a terminal response method like
[Link]()/[Link]().
Q2. Why does an error thrown inside an async Express route handler not get caught automatically (in Express
4)?
Express 4's middleware system wasn't designed to catch promise rejections — an unhandled rejection in an
async function doesn't propagate to Express's error handling unless you explicitly catch it and call next(err),
typically via a try/catch or an async-handler wrapper utility.
Q3. How would you structure middleware to protect certain routes with authentication?
Write an auth middleware that verifies the JWT/session from the request (e.g., Authorization header),
attaches the decoded user to [Link] if valid, and calls next() — or responds with 401 if invalid/missing.
Apply it selectively to protected routers/routes rather than globally, so public routes (like login/register)
remain accessible.
Q5. How does error-handling middleware differ from regular middleware in Express?
Express identifies error-handling middleware by its four-argument signature (err, req, res, next) rather than
three; it's skipped during normal request processing and only invoked when next(err) is called or a
synchronous error is thrown in a route handler, and it should be registered after all other
middleware/routes.