Creating Custom Middleware
Swipe to show menu
In Express.js, we can create custom middleware functions using the app.use() method. These functions take three parameters: req (the request object), res (the response object), and next (a function to pass control to the next middleware in the chain). Custom middleware can be applied globally to all routes or specific routes by specifying a route path.
Creating Custom Middleware
Here's a basic example of a custom middleware function that logs the timestamp and URL of every incoming request:
app.use((req, res, next) => {
const timestamp = new Date().toISOString();
const url = req.url;
console.log(`[${timestamp}] ${url}`);
next(); // Pass control to the next middleware.
});
In this example, the custom middleware logs the timestamp and URL of each incoming request to the console. The next() function is called to pass control to the next middleware in the pipeline.
Real-World Example: Combining Built-in and Custom Middleware
Here's a practical example where we use an Express built-in middleware to parse JSON data and then create a custom middleware to validate that data before proceeding:
const express = require('express');
const app = express();
// Use built-in middleware to parse JSON data.
app.use(express.json());
// Custom middleware to validate JSON data.
app.use((req, res, next) => {
const jsonData = req.body;
if (!jsonData || Object.keys(jsonData).length === 0) {
// If the JSON data is missing or empty, send an error response.
return res.status(400).json({ error: 'Invalid JSON data' });
}
// Data is valid; proceed to the next middleware or route.
next();
});
// Route that expects valid JSON data.
app.post('/api/data', (req, res) => {
const jsonData = req.body;
res.status(200).json({ message: 'Data received', data: jsonData });
});
app.listen(3000, () => {
console.log('Server is running on port 3000.');
});
In this example:
- We use the built-in middleware
express.json()to parse incoming JSON data; - We create a custom middleware that checks if the parsed JSON data is missing or empty. If it is, it sends a 400 Bad Request response with an error message. If the data is valid, it calls
next()to proceed to the route; - The
/api/dataroute expects valid JSON data. If the custom middleware validates the data, the route handler receives it and sends a success response.
-
Line 1: imports the Express.js framework;
-
Line 2: creates an Express application instance by calling
express(). The resultingappobject is used to define routes, middleware, and handle HTTP requests; -
Line 5: enables the built-in
express.json()middleware. This middleware automatically parses incoming JSON request bodies and makes the data available throughreq.body; -
Lines 8-18: define custom middleware used to validate incoming JSON data;
- check whether
req.bodycontains data; - return a
400 Bad Requestresponse if the request body is missing or empty; - call
next()if the JSON data is valid and continue to the next middleware or route handler;
- check whether
-
Lines 21-24: define a
POSTroute at/api/data;- retrieve the submitted JSON data from
req.body; - return a
200 OKresponse containing a confirmation message and the received data;
- retrieve the submitted JSON data from
-
Lines 26-28: start the Express application and begin listening for requests on port
3000.
This example demonstrates how we can use both built-in and custom middleware to validate data before it reaches our route handlers, ensuring the data is in the expected format before processing it further.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Creating Custom Middleware
In Express.js, we can create custom middleware functions using the app.use() method. These functions take three parameters: req (the request object), res (the response object), and next (a function to pass control to the next middleware in the chain). Custom middleware can be applied globally to all routes or specific routes by specifying a route path.
Creating Custom Middleware
Here's a basic example of a custom middleware function that logs the timestamp and URL of every incoming request:
app.use((req, res, next) => {
const timestamp = new Date().toISOString();
const url = req.url;
console.log(`[${timestamp}] ${url}`);
next(); // Pass control to the next middleware.
});
In this example, the custom middleware logs the timestamp and URL of each incoming request to the console. The next() function is called to pass control to the next middleware in the pipeline.
Real-World Example: Combining Built-in and Custom Middleware
Here's a practical example where we use an Express built-in middleware to parse JSON data and then create a custom middleware to validate that data before proceeding:
const express = require('express');
const app = express();
// Use built-in middleware to parse JSON data.
app.use(express.json());
// Custom middleware to validate JSON data.
app.use((req, res, next) => {
const jsonData = req.body;
if (!jsonData || Object.keys(jsonData).length === 0) {
// If the JSON data is missing or empty, send an error response.
return res.status(400).json({ error: 'Invalid JSON data' });
}
// Data is valid; proceed to the next middleware or route.
next();
});
// Route that expects valid JSON data.
app.post('/api/data', (req, res) => {
const jsonData = req.body;
res.status(200).json({ message: 'Data received', data: jsonData });
});
app.listen(3000, () => {
console.log('Server is running on port 3000.');
});
In this example:
- We use the built-in middleware
express.json()to parse incoming JSON data; - We create a custom middleware that checks if the parsed JSON data is missing or empty. If it is, it sends a 400 Bad Request response with an error message. If the data is valid, it calls
next()to proceed to the route; - The
/api/dataroute expects valid JSON data. If the custom middleware validates the data, the route handler receives it and sends a success response.
-
Line 1: imports the Express.js framework;
-
Line 2: creates an Express application instance by calling
express(). The resultingappobject is used to define routes, middleware, and handle HTTP requests; -
Line 5: enables the built-in
express.json()middleware. This middleware automatically parses incoming JSON request bodies and makes the data available throughreq.body; -
Lines 8-18: define custom middleware used to validate incoming JSON data;
- check whether
req.bodycontains data; - return a
400 Bad Requestresponse if the request body is missing or empty; - call
next()if the JSON data is valid and continue to the next middleware or route handler;
- check whether
-
Lines 21-24: define a
POSTroute at/api/data;- retrieve the submitted JSON data from
req.body; - return a
200 OKresponse containing a confirmation message and the received data;
- retrieve the submitted JSON data from
-
Lines 26-28: start the Express application and begin listening for requests on port
3000.
This example demonstrates how we can use both built-in and custom middleware to validate data before it reaches our route handlers, ensuring the data is in the expected format before processing it further.
Thanks for your feedback!