02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Creating a middleware in ExpressJS

Creating a Middleware in Express.js

In the last lecture, we covered the concept of middleware in Express.js, and now we're ready to take it a step deeper by learning how to create our own middleware. Middleware is a powerful tool that allows you to add custom functionality to your server, such as error handling, request processing, or adding common behaviors to all routes. In this tutorial, we will explore how to create our own custom middleware that handles requests in a versatile way.

What is Middleware?

Middleware functions in Express.js are pieces of code that run between the request and response lifecycle, allowing you to modify requests, responses, or add custom logic before the final response is sent back to the client. Middleware can be used to handle errors, log requests, validate data, or even modify response headers.

Creating a Custom Middleware

Let's dive right in and create our own middleware function that handles "404 - Page Not Found" errors. Typically, when a user requests a URL that doesn't exist, you want to let them know with a custom error page or message. Express.js doesn't handle 404 errors by default, as it's an unopinionated framework that gives developers flexibility to define their own rules. That's where middleware comes into play.

Step 1: Setting Up the Middleware

The middleware function we're going to create will catch any request that wasn't handled by our route definitions. To do that, we will add our middleware to the very bottom of the route definitions, ensuring it only runs after all other routes have been evaluated.

Here's an example of what the middleware might look like:

// Custom 404 Middleware
app.use((req, res, next) => {
  // Set the status code to 404, indicating page not found
  res.status(404);
  // Send an error message to the client
  res.send('Sorry, I cannot find this page');
});

Step 2: Understanding the Middleware Structure

In the code above, the function has three parameters: req, res, and next.

  • req: The request object that contains information about the client's request, such as URL, headers, and body.
  • res: The response object that allows you to send back a response to the client.
  • next: A callback function that allows you to pass control to the next middleware in the stack, if any.

Since this middleware is designed to handle errors (specifically, "404 - Not Found" errors), there is no next() call in this example. Once the middleware is reached, it sets the status to 404 and sends a custom error message back to the client.

Step 3: Using Middleware in Express.js

Middleware can be placed anywhere in the request-response lifecycle, and their order is important. Here, we add our custom middleware at the very end, making sure it runs after all the defined routes:

// Other route handlers\...

// Custom 404 Middleware must be placed at the end\app.use((req, res) => {
  res.status(404).send('Sorry, I cannot find this page');
});

Advanced Middleware Concepts

Middlewares can be much more powerful when you need them to be. For example, you can use middleware to perform logging, check user authentication, or even add custom headers. You can also use the next() function to pass control to the next middleware if multiple middlewares need to run for the same request.

In this example, the next callback is used when middleware is not the endpoint of a request and other handlers need to be executed afterward. This approach is beneficial if you need to create reusable functions to enhance your application.

app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

Practical Usage

In our middleware example, we created a basic "404 - Not Found" handler. You could expand this handler to include more informative responses, such as a redirect to a help page or logging the error to a database.

The next() function becomes particularly useful when chaining multiple middleware functions. For example, you could use it to log requests before passing them on to your route handlers.

// Log request information middleware
app.use((req, res, next) => {
  console.log(`Request URL: ${req.url}`);
  console.log(`Request Method: ${req.method}`);
  next(); // Pass control to the next middleware or route handler
});

In a real-world application, you could add custom error pages, user-friendly messages, or even dynamic redirects based on user roles or permissions.

Updates Since 2016

Note: Since this video was created in 2016, some best practices around middleware have evolved.

  • Deprecation of Body Parser: In Express version 4.16.0+, body-parser has been added as part of the Express module itself. Instead of installing and using body-parser, you can now use express.json() and express.urlencoded().
  • Arrow Functions: This example uses modern JavaScript arrow functions, which may not have been common in 2016 but are widely adopted today for cleaner and more concise syntax.

Summary

In this tutorial, we learned how to create a custom middleware in Express.js to handle 404 errors. Middleware is a powerful tool that allows us to extend the functionality of our application, whether it's handling errors, logging, or other utilities. In the next lesson, we will explore automating the process of creating applications using the Express generator.

Video Transcript

00:01In the last lecture, we got familiar
00:02with the term middlewares.
00:04In this lecture we're gonna take it a step deeper
00:06by understanding how to create your own middleware.
00:09Really wrapping up one
00:11of the most important topics in express js.
00:14So let's jump right into it. Let's see.
00:15How do we actually create our own original middleware?
00:21Like we saw in the previous lecture, one
00:23of the core competencies
00:25of express js is the capability really to not be, um,
00:29you would say aware of how things are processed
00:32and leaving that to developers
00:34and the tools that you're gonna to be working with.
00:36Now, you're not always gonna want to use a third party tool
00:39to create a middleware or use a middleware, for example.
00:43In our case, we want to create now a middleware
00:45that will basically capture all situations
00:48where there's just nothing there,
00:51no page there in that situation.
00:53What I want to do, and by the way, uh,
00:55express JS has no such thing as an error there.
00:58It doesn't assume things and
00:59because it doesn't assume things,
01:00there is no such thing as an error.
01:02The way we create an error is
01:04after we've set all the different rules,
01:06after we've created all the different routes and,
01:09and getters and use and so on
01:11and so forth, in the bottom of it all, in the bottom
01:14of the stack, we're gonna add into our app use.
01:17Just like we created a use for our static
01:21public elements
01:23and how we use it for extending our caller
01:27whenever we were parsing something.
01:29What I want to do is also, I want to use it
01:31and I want to extend it.
01:33Adding here a middleware function that is gonna have your,
01:37oh, I don't even have to write function, right?
01:38'cause we're using the newest version of JavaScript.
01:41So I'm gonna have your request a response,
01:43but this time around I have a third one,
01:45which is gonna be next.
01:47Now, the next is a callback function
01:49that usually your middleware will trigger and call.
01:52In our case, what we're really trying
01:54to do is basically capture anything that wasn't captured yet
01:58and that's why we're putting it as the last thing.
02:00And our next is really not gonna call anything
02:03'cause there is no next to be executed.
02:05Once this happened, and in this situation,
02:07what I wanna do is I wanna use my response
02:09and I'm gonna set a status code of 4 0 4,
02:12which means page not found.
02:14And I'll send, I could send a file like we've done
02:17previously, but in this case, let me just send here, sorry,
02:20I can't find this page.
02:22So let me just turn this into a double quote
02:26and let me just put your semicolon, oopsie my,
02:30looks like our editor is about to crash, so let me just,
02:34hopefully it saved and let me just restart
02:37and hopefully if it did save,
02:38lemme just give it one more shot.
02:40There we go. Okay, so let me restart here
02:44and we're gonna go back into our server.
02:45And this time around, let's go to a page that doesn't exist,
02:48like fufu.
02:50Sorry, I cannot find this page,
02:51but if I go into our form, then bam, we'll find our form.
02:55If I go back to our root, we'll get to
02:57that HTML page that exists.
02:59Now the reason is, is literally
03:00because we've put it as the last thing,
03:02this is the last thing that will happen.
03:04Now, there's much more advanced things
03:06that you could do with your middlewares.
03:08That's why this callback next is,
03:10and that's in in situations
03:12where you want it to happen first.
03:13So in this case, we're making sure that this happens first.
03:16Before we call our rounds,
03:17before we do all other things, we are first checking to see
03:21that there's static images.
03:22If there's static, that's all we're doing, we're done.
03:24If there's something to parse,
03:26then we set it up and configure it.
03:27And in this function, if you look into the source of it,
03:30you'll see to the next call back
03:31and it's actually triggered sending that information
03:34with the request and response, which is
03:36what you would see in your post.
03:39In this lecture, we learned how to create a middleware,
03:42and with it we really wrapped up the last major topic in
03:46express js.
03:47In the next lecture, we're gonna take a look at
03:49how do we automate this process using the express generator.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!