middleware.ts
Overview
The [middleware.ts](/projects/291/69100) file provides a collection of middleware functions designed for use within an Express.js server application. These middleware functions primarily focus on:
Error handling and response formatting for various error types including validation errors, API errors, syntax errors, and generic server errors.
Request logging with conditional filtering based on request path and response status.
HTTP request metrics collection and monitoring integration using Prometheus.
Common middleware stack aggregation that includes compression, body-parsing, CORS, logging, and optionally metrics.
This file acts as a centralized hub for reusable middleware components that improve API robustness, observability, and standardization across the application.
Classes, Functions, and Methods
errorHandler
errorHandler(err: Error, req: Request, res: Response, next: NextFunction): Response | void
Description
Handles errors thrown in the request pipeline and sends appropriate HTTP responses based on the error type.
Parameters
err: Error— The error object caught by Express.req: Request— The current Express request object.res: Response— The Express response object used to send back the error response.next: NextFunction— The next middleware function in the stack.
Behavior
If the error is an instance of
ValidateError(fromtsoa), returns 422 Unprocessable Entity with validation error details.If the error is an
ApiError(custom error type), returns the specified status code or 500 with the error message.If the error is a
SyntaxError(e.g., malformed JSON), returns 400 Bad Request with the syntax error message.For other generic errors, returns 500 Internal Server Error with a generic message.
If none of these match, calls
next()to propagate the error.
Usage Example
app.use(errorHandler);
notFoundHandler
notFoundHandler(_req: Request, res: Response): void
Description
Handles requests for routes that do not exist, responding with a 404 status and a "Not Found" message.
Parameters
_req: Request— The HTTP request (unused in this handler).res: Response— The HTTP response object.
Behavior
Sends a **404 Not Found** response with a JSON payload:
{
"message": "Not Found"
}
Usage Example
app.use(notFoundHandler);
requestLogger
const requestLogger: morgan.Morgan = morgan('short', {
skip: (req, res) => !req.url?.startsWith('/api/v1') || res.statusCode === 404,
});
Description
A logging middleware using `morgan` that logs HTTP requests in a concise 'short' format.
Behavior
Logs all requests starting with
/api/v1except those resulting in 404 responses.Skips logging for other routes or 404 responses to reduce noise.
Usage Example
app.use(requestLogger);
metrics
metrics(prometheus: Prometheus): (req: Request, res: Response, next: NextFunction) => void
Description
Creates middleware for collecting HTTP request duration and count metrics via a Prometheus client.
Parameters
prometheus: Prometheus— An instance of a Prometheus metrics collector wrapping the necessary metrics.
Returns
Middleware function
(req, res, next)that starts a timer for request duration and increments counters on request completion.
Behavior
Starts a histogram timer at request start.
On response finish, increments a counter with labels (
method,route,statusCode) if the request URL starts with/api/v1/and status is not 404.Observes the duration of the HTTP request.
Usage Example
app.use(metrics(prometheusInstance));
common
common(prometheus?: Prometheus): Array<import('express').RequestHandler>
Description
Generates a common array of middleware for typical API needs including compression, JSON and URL-encoded parsing, CORS, logging, and optionally metrics.
Parameters
prometheus?: Prometheus— Optional Prometheus instance to include metrics middleware.
Returns
An array of Express middleware functions.
Behavior
Always includes:
compression()— GZIP compression for responses.json()— JSON body parsing.urlencoded({ extended: false })— URL-encoded body parsing.cors()— Cross-Origin Resource Sharing enabled.requestLogger— Request logging middleware.
If a
prometheusinstance is provided, appends themetricsmiddleware.
Usage Example
const middlewares = common(prometheusInstance);
app.use(middlewares);
Implementation Details and Algorithms
Error Handling: The
errorHandlerfunction distinguishes error types primarily byinstanceofand constructor name checks to ensure correct semantic HTTP responses. This approach enables precise feedback for client errors (validation, syntax) vs server errors, improving API usability.Conditional Logging: The
requestLoggermiddleware uses askipfunction to exclude non-API or 404 requests from logging to keep logs relevant and concise.Prometheus Metrics: The
metricsmiddleware leverages Prometheus histograms and counters to monitor request latencies and counts, filtering on API route prefixes and excluding 404s to focus on successful or meaningful requests.Middleware Composition: The
commonfunction centralizes typical middleware setup, providing a standardized stack that can be reused across different Express apps or instances with optional observability enhancement.
Interaction with Other System Components
Express Application: This file exports middleware functions that are consumed by the Express.js app to handle errors, log requests, collect metrics, and parse requests.
Custom Errors: It depends on custom error classes
ApiErrorandNotFoundError(imported from the local project) to provide structured error responses.Prometheus Metrics Module: Integrates tightly with a
Prometheusclass (imported from./prometheus) to enable metrics instrumentation.Tsoa Validation: Uses
ValidateErrorfromtsoafor handling validation errors generated by API schema validation.Other Middleware Libraries: Utilizes popular middleware packages like
compression,morgan,cors, and Express's built-injsonandurlencodedparsers.
This file acts as middleware glue, enhancing express routes with cross-cutting concerns like error handling, logging, and observability.
Diagram: Middleware Function Structure and Relationships
classDiagram
class errorHandler {
+errorHandler(err: Error, req: Request, res: Response, next: NextFunction): Response | void
}
class notFoundHandler {
+notFoundHandler(_req: Request, res: Response): void
}
class requestLogger {
<<morgan middleware>>
}
class metrics {
+metrics(prometheus: Prometheus): MiddlewareFunction
}
class common {
+common(prometheus?: Prometheus): MiddlewareFunction[]
}
errorHandler ..> ValidateError : uses
errorHandler ..> ApiError : uses
errorHandler ..> SyntaxError : uses
metrics ..> Prometheus : uses
common ..> compression : includes
common ..> json : includes
common ..> urlencoded : includes
common ..> cors : includes
common ..> requestLogger : includes
common ..> metrics : optionally includes
Summary
The [middleware.ts](/projects/291/69100) file centralizes critical middleware for API error handling, request logging, and metrics collection with Express.js. Its modular functions can be composed flexibly to create a robust, observable, and developer-friendly API server environment. The file’s integration with Prometheus monitoring and TSOA validation makes it suitable for production-grade TypeScript REST APIs.