You are working on an Express API service that manages user profiles, admin operations, and order creation. The production application has several critical bugs where requests hang infinitely, incorrect status codes are returned, and server errors leak sensitive stack traces to users.
API Endpoints
GET /api/profile - Protected route (Requires valid Bearer token)
GET /api/admin/users - Admin-only route (Requires valid Bearer token + admin role)
POST /api/orders - Protected route with body validation (item string, quantity positive integer)
Current Issues & Bug Reports
- Hanging Requests: Certain valid endpoints never return a response to the client.
- Double Headers Sent Errors: Uncaught exceptions occur on bad requests in certain routes.
- Incorrect Authorization Codes: Unauthorized or forbidden requests respond with inappropriate HTTP status codes (e.g., 401 vs 403 confusion).
- Error Middleware Breakdown: Validation errors and standard server errors bypass the global error handler or do not receive the expected status code structure.
- Route-Level Order Issues: Protected endpoints allow unauthenticated access or invoke route handlers before running required middleware.
Tasks
Inspect src/middleware.js and src/app.js to identify and fix all middleware execution flow issues:
- Ensure all custom middleware functions correctly pass control using
next() or send responses without double-invoking handlers.
- Verify authentication and authorization middleware enforce strict status codes:
401 Unauthorized for missing or invalid tokens.
403 Forbidden for valid tokens without administrative privileges.
- Configure validation middleware to forward errors cleanly to the centralized error handler using
next(err).
- Ensure the centralized error-handling middleware uses the correct signature
(err, req, res, next) and handles both operational validation errors and unexpected internal server errors.
- Assemble the middleware chain in
src/app.js in the correct execution sequence.
Acceptance Criteria
GET /api/profile returns 200 OK for authenticated users and 401 Unauthorized without a valid token.
GET /api/admin/users returns 403 Forbidden when non-admin users attempt access.
POST /api/orders returns 400 Bad Request with an appropriate error payload when fields are missing or invalid.
- Centralized error handler formats errors as
{ error: message } with appropriate status codes (400 for validation, 500 for general errors).