EXPRESS JS MIDDLEWARE

What is a Middleware?:

According to wikiperdia,

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:

  • 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:

Middleware installed via npm

  • Custom Middleware:

Created by you - the developer - for a project.

How To Apply Middleware?:

  • Application or 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:
//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) => {};

22