Middleware functions play a crucial role in processing requests and responses in an Express application. They allow us to modify request data, enforce security rules, log activity, and handle errors—all before a response is sent. Express includes built-in middleware for common tasks, but we can add third-party middleware to extend functionality.

In this lesson, we’ll explore these two middleware categories, understand their significance, and see how they can be used effectively.

A quick recap of middleware:

Middleware functions are executed in sequence when a request is processed. They receive three arguments: the request object (req), the response object (res), and the next function, which passes control to the next middleware function in the stack.

Built-in middleware in Express

Express provides several built-in middleware functions that simplify request processing. These functions help with common tasks like parsing incoming JSON data, handling URL-encoded form data, and serving static assets. Let’s explore the most commonly used built-in middleware.

Parsing JSON request bodies

By default, Express does not parse JSON request bodies automatically. If a client sends JSON data in a request, req.body will be undefined unless the built-in express.json() middleware is explicitly used.

Adding this middleware ensures incoming JSON data is correctly parsed and made available within route handlers as a regular JavaScript object that can be accessed just like any other object in the code. We apply the express.json() middleware on line 4 below:

Get hands-on with 1400+ tech skills courses.