How to Use Express JS Middleware for All Routes
3 min readAug 3, 2023
Hi friends, In this tutorial I will discuss how to use express js middleware for all routes with an example. So, let us discuss a little bit about middleware.
Also read, How to install Express js in vs code with an example
What is middleware
- Middleware is a function in express js that consists of three parameters: request, response, and next.
Syntex:-
const name_of_middleware = (req, resp, next)=>{
//validate the request if needed
next();
}
- The objective of creating middleware is to accept or handle the request and return the response back to the client.
- It also validates the request and returns the response based on the successful validation and callback to the next() method.
- The middleware will not complete the request and response cycle until the next() method is called.
Example of express js middleware
Step 1:- First, initialize the packages and modules of the express js framework with the help of require() method as shown below.
const express = require('express');