Middleware in Express is a function that executes during the request-response cycle. It can modify the request, response, or terminate the request-response cycle.
Node.js Middleware
1. Basic Middleware
Here's how you can create a basic middleware in Express:
const express = require('express');
const app = express();
// Simple middleware function
app.use((req, res, next) => {
console.log('Middleware executed');
next(); // Passes the request to the next middleware or route handler
});
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
This middleware logs a message to the console each time a request is made to the server.
2. Middleware for Specific Routes
You can also apply middleware to specific routes:
app.use('/user', (req, res, next) => {
console.log('Middleware for /user route');
next();
});
app.get('/user', (req, res) => {
res.send('User route');
});
This middleware will only be executed when accessing routes under `/user`.
3. Error Handling Middleware
Middleware can also handle errors. Here’s an example of an error-handling middleware:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
This middleware catches errors and responds with a message and status code 500.
4. Conclusion
Middleware is a powerful feature in Express that allows you to handle various tasks such as logging, authentication, and error handling. You can apply it globally or for specific routes depending on your needs.