DEV Community

Cover image for EXPRESS JS MIDDLEWARE
Islam Sayed
Islam Sayed

Posted on

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);
Enter fullscreen mode Exit fullscreen mode
  • 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) => {};
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
vishalraj82 profile image
Vishal Raj

@islam It would be nice if you put this as a simple Node project. Use the middleware for says logging or authentication and put the code on github.

Collapse
 
islam profile image
Islam Sayed

Hi @vishalraj82
I just wanted to explain the concept in a minimal way.
But I think you are right also because people want to see code examples.
Thank you