Using Express Generator
Creating a Middleware in Express.js
In the previous lecture, we discussed what middleware is and how it enhances our server's capabilities by adding layers that perform operations before reaching our actions. In this tutorial, we will take a step further and learn how to create our own middleware in Express.js. This is a crucial part of understanding how to build custom behavior into your application, so let's dive in.
What is Middleware in Express.js?
Middleware is a function that sits between the request and the response cycle. It can modify the request, add new features, or perform specific actions before passing control to the next middleware or route handler.
A middleware function in Express is essentially a function that receives three arguments:
- Request (
req
) - The incoming request object. - Response (
res
) - The response object that will be sent. - Next (
next
) - A callback function that tells Express to move to the next middleware.
Creating a Custom Middleware
Let’s create a simple middleware that will handle 404 errors — situations where a requested page is not found.
-
Define the Middleware To create a middleware function, we need to use the
app.use()
method. We’ll define a middleware that will be executed at the end of the request cycle if no other route matches.app.use((req, res, next) => { res.status(404).send('Sorry, I cannot find this page'); });
This middleware will be triggered whenever no other routes match, indicating that a page or resource is not found.
-
Understanding the Middleware Flow The custom middleware function takes in three parameters:
req
(the request object)res
(the response object)next
(a callback function)
The
next
function is typically used to pass control to the next middleware in the stack. In this specific middleware, we do not callnext()
because this is the end of the route chain — we are sending a response directly indicating that the page is not found. -
Adding the Middleware to Handle All 404 Errors Place the following middleware at the very bottom of your routes, after all the route handlers:
app.use((req, res, next) => { res.status(404).send('Sorry, I cannot find this page'); });
By adding this middleware at the end of your route definitions, it ensures that any request that does not match an existing route will trigger this middleware and return a 404 response.
-
Testing the Middleware Start your server and attempt to access a non-existent route, such as
/fufu
or/random
. You should see the response:Sorry, I cannot find this page
Handling Errors with Custom Middleware
Middleware can also handle errors effectively by capturing any issues and responding appropriately. Here, we’re setting a custom 404 handler, which is a good starting point for managing more complex server behavior.
In scenarios where you might want to include logging, monitoring, or other kinds of tracking, you can easily extend your custom middleware to add these features.
Note on Express Updates
Note: The video was created in 2016. As of Express v4.x, creating error-handling middleware follows the same core structure. However, newer versions of JavaScript may make use of async
/await
to handle asynchronous operations more cleanly. Also, the body-parser
package is now integrated into Express, so there's no need to install it separately for JSON parsing.
Summary
Creating your own middleware in Express.js gives you significant power to control the request/response flow of your application. Whether it’s for handling errors, adding security layers, or providing specialized services, middleware is the heart of a flexible Express server. Try experimenting with different middleware scenarios to deepen your understanding of how they can be used effectively.