DEV Community

Cover image for 69-Nodejs Course 2023: Global Middlewares: Introduction
Hasan Zohdy
Hasan Zohdy

Posted on

69-Nodejs Course 2023: Global Middlewares: Introduction

We have cut a good such an impressive progress in the Auth concept, now we want to head back again to middleware, we want to create Global Middlewares which will be applied to all the routes, or to specific routes.

Global Middlewares

Global middlewares concept is to apply one or more middlewares to all the routes, or to specific routes.

This will be very useful instead of adding same middleware to each route separately.

So let's see how this can be done.

How it works

We'll create a http.ts config file in our config directory, it will be of course an object, we'll define a middlewares property, and we'll set it to an array of middlewares.

// src/config/http.ts

const httpConfigurations = {
  middleware: [
    //
  ]
};

export default httpConfigurations;
Enter fullscreen mode Exit fullscreen mode

Let's not forget to import this file in our index.ts file.

// src/config/index.ts
import config from "@mongez/config";
import databaseConfigurations from "config/database";
import appConfigurations from "./app";
import authConfigurations from "./auth";
import httpConfigurations from "./http";
import validationConfigurations from "./validation";

config.set({
  database: databaseConfigurations,
  validation: validationConfigurations,
  app: appConfigurations,
  auth: authConfigurations,
  http: httpConfigurations,
});
Enter fullscreen mode Exit fullscreen mode

Now we're ready to the next step, registering the middlewares.

Registering the middlewares

We already have middlewares list for each route, now what we need to do is to merge the global middlewares with the route middlewares.

// src/core/http/request.ts
// ...
  /**
   * Execute middleware list of current route
   */
  protected async executeMiddleware() {
    if (!this.route.middleware || this.route.middleware.length === 0) return;

    // trigger the executingMiddleware event
    this.trigger("executingMiddleware", this.route.middleware, this.route);

    for (const middleware of this.route.middleware) {
      const output = await middleware(this, this.response);

      if (output !== undefined) {
        this.trigger("executedMiddleware");
        return output;
      }
    }

    // trigger the executedMiddleware event
    this.trigger("executedMiddleware", this.route.middleware, this.route);
  }
Enter fullscreen mode Exit fullscreen mode

Here where we're going to merge the global middlewares with the route middlewares.

// src/core/http/request.ts
import config from "@mongez/config";
// ...

  /**
   * Execute middleware list of current route
   */
  protected async executeMiddleware() {
    // get route middlewares
    const routeMiddlewares = this.route.middleware || [];
    // get global middlewares
    const globalMiddlewares = config.get("http.middleware", []);

    // merge global and route middlewares
    const middlewares = [...globalMiddlewares, ...routeMiddlewares];

    // check if there are no middlewares, then return
    if (middlewares.length === 0) return;

    // trigger the executingMiddleware event
    this.trigger("executingMiddleware", middlewares, this.route);

    for (const middleware of middlewares) {
      const output = await middleware(this, this.response);

      if (output !== undefined) {
        this.trigger("executedMiddleware");
        return output;
      }
    }

    // trigger the executedMiddleware event
    this.trigger("executedMiddleware", middlewares, this.route);
  }
Enter fullscreen mode Exit fullscreen mode

We defined here the route middlewares first, then the global ones, and then we merged them together.

If there are no middlewares, then we exit the function using return.

After that we w'll loop over merged middlewares, and execute them one by one.

🎨 Conclusion

We've learned how to create global middlewares, and how to merge them with the route middlewares.

In our next article, we'll improve the global middlewares concept, and we'll add more features to it, like adding exceptions for routes, using named routes and allowing middlewares for certain routes only.

☕♨️ Buy me a Coffee ♨️☕

If you enjoy my articles and see it useful to you, you may buy me a coffee, it will help me to keep going and keep creating more content.

🚀 Project Repository

You can find the latest updates of this project on Github

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on Youtube, the course is in Arabic language.

📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

Top comments (0)