Middleware in Express.js
Express.js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle.
Middleware are functions that came into play after the server receives the request and before the response is sent to the client. Middleware has the access to the request object, responses object, and next, it can process the request before the server send a response.
Middleware functions share the same arguments as a Route callback function and also have a third argument called next which is responsible for passing execution to the next callback. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
Middleware functions can perform the following tasks:
- Make changes to the request and the response objects.
- End the request cycle by sending back a response to the client.
- Call the next middleware function in the stack.
- It can be used to add logging and authentication functionality.
- It can be used for error handling and parsing the request data.
- It helps for Optimization and better performance.
An Express application can use the following types of middleware:
- Application-level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- Third-party middleware
Application-level middleware:-
Application-level middleware in Express.js refers to middleware functions that are applied to the entire application rather than being tied to a specific route. These middleware functions are executed for every incoming request, regardless of the specific route being accessed. They are set up using the app.use() method.
const express = require('express')
const app = express()
// App level middleware
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})Router-level middleware:-
Router-level middleware in Express.js refers to middleware functions that are bound to a specific instance of the Express Router. Unlike application-level middleware, which is applied globally to the entire application, router-level middleware is specific to a particular set of routes defined by an instance of the Router.
const router = express.Router();
// Router-level middleware
router.use((req, res, next) => {
console.log('This middleware runs for routes defined by the router.');
next(); // Pass control to the next middleware or route handler
});
// Mount the router at a specific path
app.use('/myapp', router);In this example, the router-level middleware is applied to all routes defined within the router instance. The app.use(‘/myapp’, router) line specifies that the router is mounted at the path ‘/myapp’, so the middleware and routes defined within the router will only be active for requests that start with ‘/myapp’.
Error-handling middleware:-
Error handling middleware refers to a type of middleware that is specifically designed to handle errors that occur during the processing of a request. When an error occurs in an Express application, it can be caught by an error handling middleware, allowing you to handle and respond to the error in a centralized and organized way.
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something went wrong!')
})Error-handling middleware always takes four arguments.
err: The error object.
req: The request object.
res: The response object.
next: The next middleware function.
You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.
Built-in middleware:-
Built-in middleware are middleware functions that are included with the Express framework by default. These middleware functions provide common and essential functionalities that can be used in web applications. Express.js simplifies the development process by using these built-in middleware, making it easy for developers to handle common tasks without having to implement everything from scratch.
Get Ritesh Aldak’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are some examples of built-in middleware in Express.js:
1. express.json():
This middleware parses incoming JSON data from the request body and makes it available in req.body.
2. express.urlencoded():
This middleware parses incoming URL-encoded form data from the request body and makes it available in req.body.
3. express.static():
This middleware serves static files (e.g., images, CSS, JavaScript) from a specified directory.
Third-party middleware:-
Third-party middleware are middleware functions that are not part of the core Express framework but are created by external developers or third-party libraries. These middleware functions add additional features, functionalities, or integrations to an Express application, allowing developers to extend the capabilities of their applications by using existing third-party solutions.
Here are a few examples of popular third-party middleware in Express.js:
1. cookie-parser:
Middleware for parsing cookies attached to incoming requests and making the parsed data available in req.cookies.
2. body-parser:
A middleware that parses incoming request bodies in different formats, such as JSON and URL-encoded data, and makes the parsed data available in req.body.
3. express-session:
Middleware for handling user sessions, allowing you to store and retrieve data associated with a user across multiple requests.
4.multer:
Middleware for handling multipart/form-data, commonly used for file uploads.
5.passport:
Middleware for validating and sanitizing input data in request bodies, query parameters, and headers.
Remember to install these third-party middleware packages using npm before using them in your Express application.









