Custom MiddlewareCustom 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:

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:

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/data route expects valid JSON data. If the custom middleware validates the data, the route handler receives it and sends a success response.
Code Description
Line 1: This line imports the Express.js framework, making it available for use in the application.
Line 2: There, we create an Express application instance by invoking the express() function. This app object is where we define routes, middleware, and handle HTTP requests.
Line 5: This line uses Express's built-in middleware express.json(). It enables the application to automatically parse incoming JSON data from HTTP request bodies. This middleware ensures that when you receive a request with a JSON body, it will be available as req.body in the route handlers.
Lines 8-18: This code defines custom middleware. Middleware functions in Express can be used to perform actions before processing the main route handler. In this middleware:
      - It checks if there is JSON data in the request body req.body.
      - If there is no JSON data or if the JSON object is empty, it sends a response with a 400 Bad Request status and a JSON error message.
      - If the JSON data is valid (not empty), it calls next() to proceed to the next middleware or route handler.
Lines 21-24: This defines a POST route at '/api/data'. It's an endpoint that expects JSON data to be sent in the request body. In the route handler:
      - It retrieves the JSON data from req.body.
      - It sends a response with a 200 OK status and a JSON message indicating that data has been received, along with the received data itself.
Lines 26-28: This line starts the Express application and listens on port 3000. When the server starts, it logs a message to the console.

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.

Everything was clear?

Section 3. Chapter 9