What is a Middleware?

According to wikipedia,

Middleware is a type of computer software that provides services to software applications beyond those available from the operating system. It can be described as “software glue”.

In our case, express js middleware is a functionality that runs between a request to the server and the response from the server.


Types of Express Middleware:

  • Express js Built-in Middleware.
  • Third Party Middleware.
  • Custom Middleware.

Express js Built-in Middleware:

  1. express.static: serves static assets such as HTML files, images, and so on.
  2. express.json: parses incoming requests with JSON payloads.
  3. express.urlencoded: parses incoming requests with URL-encoded payloads.

Third Party Middleware:

They are middleware installed via npm.

Some examples:

Cookie-parser, morgan, cors, and compression.

Custom Middleware:

They are middleware Created by you – the developer – for a project.


How To Apply Middleware?

You can apply middleware either at Application/Route level, or at Endpoint level:

Application/Route level:

const express = require('express');

//Start express app.
const app = expree();

//Apply a single middleware
app.use(middleware);

//Apply multiple middleware
app.use(middleware1, middleware2);

//Or via an array 
const middlewareArr = [middleware1, middleware2];
app.use(middlewareArr);

– Endpoint level:

const express = require('express');

//Start express app.
const app = expree();

//Apply a single middleware
app.get('/', middleware, (res, req) => {};

//Apply multiple middleware
app.get('/', middleware1, middleware2, (res, req) => {};

//Or via an array 
const middlewareArr = [middleware1, middleware2];
app.get('/', middlewareArr, (res, req) => {};