docs

Register a Server Middleware

Middlewares allow you to execute custom logic on incoming requests before they reach your defined routes. You can apply them globally, to specific routes, or to groups of routes based on a common path. Define your middlewares in app/middlewares/index.ts as shown below.

1. Apply Middleware to a Specific Route

To apply middleware to a single route, specify the path field. This example logs the request time for requests to /health:

export const middlewareList: MiddlewareType[] = [
  {
    function: (request, response, next) => {
      console.log("Request received at:", new Date().toISOString());
      next(); // Passes control to the next middleware or route handler
    },
    path: "/health", // Middleware applies only to "/health"
  },
];

2. Apply Middleware Globally

To apply middleware to all routes, leave the path field empty. This ensures the middleware executes on every incoming request:

export const middlewareList: MiddlewareType[] = [
  {
    function: (request, response, next) => {
      console.log("Global Middleware: Request received");
      next();
    },
    path: "", // Applies to all routes
  },
];

3. Apply Middleware to a Group of Routes

If you want middleware to apply to a group of routes under a shared path, such as /admin, define the path accordingly. This ensures the middleware runs for all /admin routes:

export const middlewareList: MiddlewareType[] = [
  {
    function: (request, response, next) => {
      console.log("Hello from Admin!", request.url);
      next();
    },
    path: "/admin", // Applies to all routes under "/admin"
  },
];

This approach ensures middleware execution on any request matching the /admin path and its subpaths.

Summary