In Express.js, middleware functions 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. These functions can modify the request and response objects, end the request-response cycle, or call the next middleware function in the stack.
To create and use middleware in Express.js, you can follow these steps:
Create a Middleware Function: Middleware functions are created using the following syntax:
javascriptfunction myMiddleware(req, res, next) {
// Do something with the request or response
console.log('Middleware executed');
// Call the next middleware in the stack
next();
}
Here, next
is a function that, when invoked, passes control to the next middleware function in the stack.
Use Middleware in Your Application:
You can use middleware globally for all routes or selectively for specific routes. To use middleware globally, use app.use()
:
javascriptconst express = require('express');
const app = express();
// Global middleware
app.use(myMiddleware);
// Your routes go here
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
To use middleware selectively, use app.use()
for specific routes:
javascriptconst express = require('express');
const app = express();
// Global middleware
app.use(myMiddleware);
// Route-specific middleware
app.get('/special-route', myMiddleware, (req, res) => {
res.send('Special Route');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Middleware Order Matters: The order in which middleware functions are declared is crucial. They are executed in the order they are defined. Ensure that you place your middleware in the correct order based on the logic you want to implement.
javascriptapp.use(middleware1);
app.use(middleware2);
app.use(middleware3);
Error Handling Middleware: You can create error-handling middleware by defining a middleware function with four parameters (err, req, res, next). Express recognizes it as an error-handling middleware.
javascriptfunction errorHandler(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something went wrong!');
}
app.use(errorHandler);
Make sure to place error-handling middleware after other middleware and routes, so it can catch errors that occur during request processing.
That's a basic overview of creating and using middleware in Express.js. Middleware is a powerful concept in Express, allowing you to modularize and reuse code across your application.