Express is a popular web application framework for Node.js, known for its simplicity and flexibility. One of the most powerful features of Express is middleware, which allows you to run code before handling the actual request. Middleware functions can be used to handle tasks such as authentication, logging, error handling, and more.
In this tutorial, we will cover the basics of Express middleware and show you how to create and use middleware in your Express application.
What is Middleware?
Middleware functions in Express are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. Middleware functions can perform tasks such as:
- Execute any code.
- Modify the request and response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
Middleware functions can be added to an Express application using the app.use() method. Middleware functions are executed sequentially, in the order they are added to the application.
Creating Middleware
Creating middleware in Express is quite simple. Middleware functions are just regular JavaScript functions that take three parameters – req, res, and next.
Here is an example of a very basic middleware function that logs the request method and URL to the console:
const logRequest = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
};
app.use(logRequest);
In this example, the logRequest middleware function logs the request method and URL to the console, and then calls the next() function to pass the request to the next middleware function in the stack.
Using Middleware
Middleware functions can be added to an Express application using the app.use() method. Middleware functions can be added globally to all routes, or to specific routes using app.use() with a path argument.
Here is an example of adding a global middleware function to an Express application:
app.use((req, res, next) => {
console.log('This is a global middleware function');
next();
});
In this example, the middleware function is added globally to the application and will be executed for all incoming requests.
To add middleware to a specific route, you can use the app.use() method with a path argument. Here is an example:
app.use('/api/users', (req, res, next) => {
console.log('This is middleware for /api/users');
next();
});
In this example, the middleware function is only executed for requests to the /api/users route.
Order of Middleware
Middleware functions are executed sequentially, in the order they are added to the application. The order of middleware functions is important, as they are executed in the order they are added to the application.
For example, if you have two middleware functions A and B, and you add them to the application in the order A, B, the request will first pass through function A, then through function B.
Error Handling Middleware
Express also allows you to create error handling middleware functions that can handle errors that occur during the request processing. Error handling middleware functions should be defined with four parameters – err, req, res, and next.
Here is an example of an error handling middleware function:
app.use((err, req, res, next) => {
console.error(err);
res.status(500).send('Internal Server Error');
});
In this example, the error handling middleware function logs the error to the console and sends a 500 Internal Server Error response to the client.
Conclusion
Express middleware is a powerful feature that allows you to run code before handling the actual request. Middleware functions can be used to perform a wide range of tasks, such as authentication, logging, error handling, and more.
In this tutorial, we covered the basics of Express middleware, including how to create and use middleware in your Express application. We also discussed the order of middleware functions and error handling middleware.
I hope this tutorial has been helpful in understanding Express middleware and how to use it in your applications. Express middleware is a powerful tool that can help you build robust and efficient web applications.
Please create ORM , NODEJS
Brother you worked Great!… Love from Pakistan. Mujhy nahi lagta kai YT pai node js pai itne detailed, well explained series hoga.
Bro last request hai kindly 1 playlist banao mern stack walo kai liyai jisme aap beginner to advanced level projects banao. takai jinho ne aapki videos se react, node, and MongoDB seekhi hai wo is playlist ko follow karke confidential Developer ban jaye. Currently YT pai hindi mai aese playlist nahi ha…
Thanks piyush bhai, Saalo seh use kar rha hu but aaj achhe seh samajh aaya middleware. Dil seh Shukriya 🙏🙏
ek no1 yar mzaa a gya
nice
Thank you very much, sir.
Thankyou Sir
Thank you
The best video on middleware so far🤯
Video is Useful
great teaching brother … thank you for this masterpiece playlist ….
2 monts se middleware smj nhi arha tha ab 10 min m agya, Thanks bro
Great and thanks 😊
Bhaiya, your series is killer. Best series ever.
Best explanation ❤ of middleware
ty sir
BEST EXPLANATION!!!! 🫡
Brother not able to do delete method please help me 🙏🏼🙏🏼 I am stucked please bhai help me
Youtube can disable dislike button from this channel as it has no uses.
best channel on whole youtube to learn backend so polite but very high knowledge i am from tier 1 cse and i am learning backend from here