In Express.js, middlewares are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middlewares can perform actions on the request and response objects, modify them, or end the request-response cycle.
In this tutorial, we will look at how to create and use middlewares in Express.js.
-
What is Middleware?
Middleware is a function that has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions can perform tasks like:- Executing any code.
- Making changes to the request or response objects.
- Ending the request-response cycle.
- Calling the next middleware function in the stack.
- Creating Middlewares
To create a middleware in Express.js, you simply define a function that takes three parameters: req, res, and next. Here’s an example of a simple middleware function that logs a message to the console:
const myMiddleware = (req, res, next) => {
console.log('Middleware function called');
next();
};
In this example, the middleware function logs a message to the console and then calls the next middleware function in the stack using the next()
function. If you don’t call next()
, the request-response cycle will end, and the client will never receive a response.
- Using Middlewares
To use a middleware in an Express.js application, you simply pass the middleware function as an argument to theapp.use()
method. Here’s an example that demonstrates how to use themyMiddleware
middleware function we defined earlier:
const express = require('express');
const app = express();
app.use(myMiddleware);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, we use the myMiddleware
middleware function by passing it as an argument to app.use()
. This means that every incoming request will pass through the myMiddleware
function before reaching the route handler.
- Chaining Middlewares
You can chain multiple middleware functions together by passing them as arguments to theapp.use()
method. Here’s an example that demonstrates how to chain multiple middleware functions:
const express = require('express');
const app = express();
const middleware1 = (req, res, next) => {
console.log('Middleware 1 called');
next();
};
const middleware2 = (req, res, next) => {
console.log('Middleware 2 called');
next();
};
app.use(middleware1, middleware2);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, we chain two middleware functions (middleware1
and middleware2
) together by passing them as arguments to app.use()
. The order in which you pass the middleware functions to app.use()
determines the order in which they will be executed.
- Error Handling Middleware
You can also create middleware functions to handle errors in your application. Error handling middleware functions take four arguments:err
,req
,res
, andnext
. Here’s an example of an error handling middleware function:
const errorMiddleware = (err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
};
app.use(errorMiddleware);
In this example, the errorMiddleware
function logs the error to the console and sends a 500 status code with a message to the client. You can call the errorMiddleware
function whenever an error occurs in your application.
- Conclusion
Middlewares are a powerful feature in Express.js that allow you to write modular and reusable code. They can be used to perform tasks like logging, authentication, error handling, and more. By understanding how to create and use middlewares in Express.js, you can improve the functionality and maintainability of your web applications.
5/5 stars explanation , tysm sir
Javascript OP
6:36 BEST THING I'VE SEEN TODAY 😆
6:46 🤣🤣
🔥🔥🔥🔥🔥
Javascript OP
Downfall of legend , Harry bhai ye kya horeha he , but I love your video
Harry bhai deserve not only 5 star He deserve more than star
harry bhai I am very much impressed with the performance of your windows PC/laptop . I am currently using MacBook pro m1… .Can you please tell me which system you're using ?
#javascriptOP
2:39 pr thoda dark ho gya
course bhi sigma or course kraane wala bhi sigma>>>
Java Script OP
Sigma batch op Harry bhai ✨✨🗿🗿🗿🗿🗿
#JavaScriptOP
#SigmaBatchOP
#HarryBhai
One day, coding will make me commit suicide.
20 min ki video ko dekhne me 1 ghanta lag gya
Nice explained
sigma op
5 out of 5