69-Nodejs Course 2023: Global Middlewares: Introduction
Tags: node, typescript, mongodb, fastify
Published: 2022-11-21 11:33:53

---
title: 69-Nodejs Course 2023: Global Middlewares: Introduction
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bkvv3j07xit0jsvuchme.png
# Use a ratio of 100:42 for best results.
---

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.

```ts
// src/config/http.ts

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

export default httpConfigurations;
```

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

```ts
// 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,
});
```

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.

```ts
// 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);
  }
```

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

```ts
// 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);
  }
```

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](https://www.paypal.com/paypalme/hassanzohdy), 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](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) 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](https://www.youtube.com/playlist?list=PLGO8ntvxgiZMJc7RN2lIq9WmMOlWZGzmz), 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

- [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
- [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
- [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

- [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
- [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
- [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

- [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

- [OOP In JS And TS From The Very Beginning](https://dev.to/hassanzohdy/jsts-oop-course-1-introduction-2ld)
- [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
- [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)