Middleware in a Node.js application is a way to execute code in a request-response cycle. It allows you to perform actions before or after the request is processed by the route handler. Middleware functions have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle (next
).
Here's a basic overview of how to use middleware in a Node.js application:
Middleware functions are simple functions that take three arguments: req
, res
, and next
. Here's an example of a basic middleware function:
javascript// Example middleware function
function myMiddleware(req, res, next) {
console.log('Middleware is executed!');
// Perform some actions or checks here
// Call next to pass control to the next middleware in the stack
next();
}
You can use middleware at the application level or for specific routes. To use middleware at the application level, use app.use()
:
javascriptconst express = require('express');
const app = express();
// Use middleware for all routes
app.use(myMiddleware);
// Define your routes
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
In this example, myMiddleware
will be executed for every incoming request, as it's added using app.use()
.
You can also use middleware for specific routes:
javascriptconst express = require('express');
const app = express();
// Middleware for specific route
app.get('/special', myMiddleware, (req, res) => {
res.send('Special route!');
});
// Regular route without middleware
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
In this case, myMiddleware
will only be executed for the /special
route.
The order in which you use middleware is important. Middleware functions are executed in the order they are added. Make sure to place middleware that needs to run before others at the top.
javascriptapp.use(middleware1);
app.use(middleware2);
app.use(middleware3);
Middleware functions can also handle errors. If a middleware function takes four arguments (err, req, res, next), it is treated as an error-handling middleware:
javascriptapp.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
This middleware will be called if an error occurs in the previous middleware or route handlers.
Middleware in Node.js, especially when using frameworks like Express, provides a flexible way to structure your application and add functionality to the request-response cycle.