# Middleware

# Introduction

Middleware provides a great way to inspect and filter HTTP requests entering your application. As an example, ExpressWebJs provides an auth middleware that verifies if the user of your application is authenticated. If the user is not authenticated, an error message with appropriate error code is sent.

Additional middleware can be written to perform a variety of tasks besides authentication. To work with middleware, your middleware class should extend MiddlewareHandler class.

The following are the two methods you should know about while working on middlewares −-

  • preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to continue execution to the next layer (controller).

  • postHandle() method − This is used to perform operations before sending the response to the client.

Observe the following code for a better understanding −

export class ProductServiceMiddleware extends MiddlewareHandler {
  override async preHandle(req: Request, res: Response): Promise<boolean> {
    return true;
  }

  override async postHandle(req: Request, res: Response): Promise<void> {
    //
  }
}

For example, a logging middleware might log all incoming requests to your application.

# Creating Middleware

To create a new middleware, use the make-middleware maker command:

ts-node maker make-middleware CheckHeader

App/Http/Middleware

import { Request, Response } from "Config/http";
import HttpResponse from "Elucidate/HttpContext/ResponseType";

export class CheckHeader extends MiddlewareHandler {
  override async preHandle(req: Request, res: Response): Promise<boolean> {
    if (req.header("appId") != "abcd") {
      HttpResponse.UNAUTHORIZED(res, { auth: false, message: result.msg, payload: result.payload });
      return false;
    }
    return true;
  }
}

# Registering Middleware

All middleware are registered inside the App/Http/kernel.ts file.

# Global Middleware

If you want a middleware to run during every HTTP request to your application, list the middleware class in the applicationLevelMiddleware property of your App/Http/Kernel.ts file.

App/Http/Kernel.ts

 applicationLevelMiddleware: [
    "App/Http/Middleware/CheckForMaintenanceMode",
    "App/Http/Middleware/ConvertEmptyStringsToNull",
  ],

# Assigning middleware to Route

If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's App/Http/Kernel.ts file in the routeMiddleware section.

App/Http/Kernel.ts

routeMiddleware:{
    auth:"/App/Http/Middleware/Auth",
    booking:"/App/Http/Middleware/Booking",
};

Once you have registered your middleware in the App/Http/Kernel.ts file, you can now use the middleware key to assign middleware to a route:

Route.get($uri, $callback, ["auth"]);

You may assign multiple middlewares to the route like so:

Route.get($uri, $callback, ["auth", "booking"]);

You can also assign middleware to route group like so:

Route.group({ middleware: ["auth", "booking"] }, () => {
  Route.get($uri, $callback);
});