Let's understand it in a short story, suppose you want to issue a book from a library then you have to go through some checkpoints, so consider those as middleware. First, you will be checked to know whether you are authenticated to access college premises, and then the librarian will check your authorization by your library card after that she will log your request and you will get your book, This is where the middleware plays an important role.
Middleware
Defining middleware is very easy in Express JS it takes three parameters req, res and next and only in error handling middleware we have one extra parameter that is err .
app.use((req, res, next) => { });
Types of middlewares
As per the above example we can say middleware has many purposes to serve, we can categorize it into four types, Application level, Route level, Error handling, Built-in, and Third-party middleware
Application level
As we have seen in the above example if you want to enter the college premises, you will need an ID card for authentication so we can use the application-level middleware to check for the authenticated requests.
const express = require('express');
const app = express();
app.use((req, res, next) => {
next()
});
Route level
In the library, some sections are reserved for the college staff, so some areas are inaccessible even if you have an ID card(Authenticated user). To achieve this in express Js we need to secure those routes from other users to achieve this we will use Route level middleware.
const express = require("express");
const router = express.Router();
router.use((req, res, next) => {
next()
});
There are a few more examples of route-level middleware that will help us
drill down to use middleware more effectively. We can say that we want to add a validation that a user can only issue a book of the course he/she has opted for to achieve this in express we will use the below code.
router.use('/books/stream/:streamName',(req, res, next) => {
next();
});
Error handling
Error-logging middleware can be easily identified by an extra parameter in the middleware function, it is one of the default features provided by Express Js. We can use this feature whenever we have to throw an error.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wron');
})
Built-in
Express provides several built-in middleware functions that help handle common tasks in web development, we will see a few examples of built-in middleware.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
Third-party
There are many library available to simplify web development, so we don’t have to write everything from scratch. Instead, we can use these features by simply installing them with npm. We will see to most common example of third-party middleware.
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('CORS is enabled for all origins!');
});
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Conclusion
In summary, middleware in Express.js acts like checkpoints in a library, performing various tasks to ensure smooth operations. From application-level checks like authentication to route-level validation and error handling, middleware helps manage requests and responses efficiently. Built-in middleware such as express.json() and express.static() streamline common tasks, while third-party middleware like cors and cookie-parser enhance functionality with minimal setup. By understanding and utilizing these middleware types, you can build robust, well-organized web applications that handle various scenarios seamlessly.