Built-In and Third-Party Middleware
Explore the power of built-in and third-party middleware to streamline your Express applications.
We'll cover the following...
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:
{
"name": "node-server",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js",
"test": "mocha"
},
"dependencies": {
"async": "^3.2.4",
"cors": "^2.8.5",
"express": "^4.18.2",
"lodash": "^4.17.21"
},
"devDependencies": {
"mocha": "^11.1.0",
"supertest": "^7.0.0"
}
}