Middleware functions in Express.js 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.
These functions can perform various tasks, modify the request and response objects, and terminate the request-response cycle by sending a response or passing control to the next middleware function.
Middleware functions allow us to break down our application into smaller, reusable components. Each middleware function can handle specific tasks like authentication, modify request and response objects, logging, error handling, and more.
Middleware functions can preprocess incoming client requests by performing tasks such as setting or modifying headers, validating data, parsing request bodies, and more.
Middleware functions approach makes our codebase cleaner, more maintainable, and easier to understand.
Here's an overview of using middleware in Express.js:
Express provides some built-in middleware functions that can be easily used in your application.
app.use(express.json()); app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
This serves static files from the 'public' directory.
We can create our own middleware functions and use them in your application.
// Example middleware function const myMiddleware = (req, res, next) => { // Do something before passing control to the next middleware console.log('Middleware executed!'); next(); // Pass control to the next middleware in the stack }; // Use the middleware for all routes app.use(myMiddleware); // Use the middleware for a specific route app.get('/special', myMiddleware, (req, res) => { res.send('This is a special route.'); });
// Error-handling middleware const errorHandler = (err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); }; // Use the error-handling middleware app.use(errorHandler); // Example route that triggers an error app.get('/error', (req, res, next) => { const err = new Error('Intentional error'); next(err); });
Middleware can also be used for error handling.
if an error is thrown or passed to "next" function, the error-handling middleware "errorHandler" will be invoked.
app.use((req, res, next) => { console.log('Middleware 1'); next(); }); app.use((req, res, next) => { console.log('Middleware 2'); next(); });
Middleware functions are executed in the order they are declared in the code.
const specialMiddleware = (req, res, next) => { console.log('Special Middleware'); next(); }; app.use('/special', specialMiddleware, (req, res) => { res.send('This route has special middleware.'); });
Use "next()" to pass control to the next middleware function in the sequence.
We can apply middleware to specific routes. use cases: It helps to access authorised requests only. unauthorized requests will not be entertained.
specialMiddleware is only applied to the '/special' route.