Middleware in Express
Middleware functions are a key part of Express. They provide a powerful way to handle various tasks in your application, such as logging, authentication, error handling, and more. In this section, we’ll explore how to create custom middleware, use third-party middleware, and handle errors.
Creating Custom Middleware
Custom middleware functions 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.
Example: Logging requests
// Importing the Express module
const express = require('express');
const app = express();
const port = 3000;
// Custom middleware to log request details
const requestLogger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Passing control to the next middleware function
};
// Using the custom middleware
app.use(requestLogger);
// Handling GET request at the root URL
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Using Third-Party Middleware
Express has a vast ecosystem of third-party middleware that you can use to add functionality to your applications.
Example: Using morgan
for logging
Add the morgan
package to your project:
npm install morgan
Then, use the morgan
middleware to log requests:
// Importing the Express module
const express = require('express');
const morgan = require('morgan');
const app = express();
const port = 3000;
// Using 'morgan' middleware for logging
app.use(morgan('dev'));
// Handling GET request at the root URL
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Error-Handling Middleware
Error-handling middleware is used to catch and handle errors in your application. It has the same signature as regular middleware, but with an additional err
parameter.
Example: Basic error-handling middleware
// Importing the Express module
const express = require('express');
const app = express();
const port = 3000;
// Middleware to simulate an error
app.use((req, res, next) => {
const error = new Error('Something went wrong!');
next(error); // Passing the error to the error-handling middleware
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.message); // Logging the error message
res.status(500).send('Internal Server Error'); // Sending a generic error response
});
// Handling GET request at the root URL
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Built-in Middleware
Express also comes with some built-in middleware functions that you can use.
express.static
: Serves static files (e.g., images, CSS, JavaScript)javascript // Serving static files from the 'public' directory app.use(express.static('public')); // Handling GET request at the root URL app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
express.json
andexpress.urlencoded
: Parses incoming request bodiesjavascript // Middleware to parse JSON request bodies app.use(express.json()); // Middleware to parse URL-encoded request bodies app.use(express.urlencoded({ extended: true })); // Handling POST request at the '/submit' URL app.post('/submit', (req, res) => { const { name, age } = req.body; res.send(`Name: ${name}, Age: ${age}`); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Summary
In this section, we explored the concept of middleware in Express. You learned how to create custom middleware, use third-party middleware, and handle errors. Middleware is a powerful tool in Express that allows you to manage the flow of requests and responses in your application efficiently.