Middleware in ExpressJS are functions that come into play after the server receives the request and before the response is processed by the route and sent to the client.
We can use middleware functions for different types of preprocessing tasks required for fulfilling the request like database querying, making API calls, preparing the response and also calling the next middleware function in the chain.
We call app.use() to add a middleware function to our Express application. Express executes middleware in the order they are added.
Difference between Controllers Vs. Middleware ?
Controllers - An entity that will actually respond to the requests.
Middleware - A step in progression towards actioning your request. Middleware are often reused more than once in multiple routes and often they do not respond to request(respond by returning to client with some data).
Middleware functions take three arguments:
the request object (request)
the response object (response)
optionally the next() middleware function.
An exception to this rule is error handling middleware which takes an error object as the fourth parameter. The next() function is a function in the Express router that, when invoked, executes the next middleware in the middleware stack. If next() is not called, the request will be left hanging.
In the below example, we are adding a middleware which will be called for all routes
In the below example,
We are attaching the express.json() middleware by calling the app.use() function. It parses incoming requests with JSON payloads and is based on body-parser. We have also configured a maximum size of 100 bytes for the JSON request.
This middleware function will be called only for this route /products.
You can make a POST request to http://localhost:3000/ with header set to content-type: application/json and body {“name”:“furniture”, “brand”:“century”, “price”:1067.67}
In the below example, the middleware checks if the request contains a json content
Another example, handle get request with 3 middleware functions
In the next example, we can see multiple middleware functions are added to a route to preprocess in multiple stages.
In the below example, we add middleware for error handling