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

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:

  1. Request (req) - The incoming request object.
  2. Response (res) - The response object that will be sent.
  3. 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.

  1. 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.

  2. 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 call next() because this is the end of the route chain — we are sending a response directly indicating that the page is not found.

  3. 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.

  4. 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.

Video Transcript

00:00Congratulations, you completed the last complicated topic
00:04in express js
00:05and with it almost completed this chapter,
00:08there's only one more thing I wanted to talk about
00:10with is U, which is using express generator.
00:13It is incredibly easy to use, so let's jump right into it
00:15and let's learn how to use express generator
00:19to automate different processes through a template.
00:22And we're gonna do that using the express generator,
00:25which is a global package.
00:27Let's jump right into it. Let's see it in action.
00:30So this chapter was relatively long, but very important
00:33because this is the core of your server.
00:35And I just wanted to talk about one last thing
00:37and that is the express generator, which enables you
00:40to do things quickly by the encouragement of Express J of
00:45how they think you should be building it.
00:47But you don't have to. I wanna show you how to do that.
00:49And basically what I'm gonna do is I'm gonna type NPM
00:52install express generator,
00:56and I'm gonna install it into the global space.
00:58Remember how we with our express,
01:00we didn't put it in the global space.
01:02Instead of that, we put it directly in the folder.
01:04In this case, the reason why we're doing that,
01:06because we want to add a command for our command line.
01:09Once we set up and we install into the global space,
01:12the express generator, literally,
01:14and I'm gonna go ahead here and just move back one folder.
01:18And what I want to do is I'm gonna create a new express
01:21by typing express now once it's installed
01:24and type a name of the folder.
01:25So for example, I'm gonna create a project called Ex Sample
01:29with Express and Express will basically build up
01:31for me a node express package ready
01:35for consumption ready for us to work with.
01:37So step one is we're gonna go ahead
01:38and create the, the building blocks for our application.
01:42And what it did is it created all the folder structures
01:45that, and the package j json file
01:48with all the included elements that we want to have.
01:52Last but not least, what we want, well two things
01:54that are left, as you could see in the description here,
01:56we wanna go into that folder.
01:58And in that folder we're gonna go ahead
01:59and install all the different plugins,
02:02all the different modules more accurately that know
02:05that express needs, including express itself, it that the,
02:09this generator created.
02:11You know, we saw natively throughout this chapter
02:13that we could do with really limited resources,
02:15which personally is my favorite,
02:17where I only add resources based on what I need.
02:19But that's just my style.
02:21And if your style is you want to get something quick up
02:23and ready, this could be a very good solution.
02:25And if we type this, it's gonna go through
02:26and install all the different packages
02:29that it has pre-configured with your installer.
02:33And by the way, you probably want to keep up
02:34with keeping the versions up to date, updating o
02:37to your version of Express generator, making sure
02:39that you'll get the latest and greatest.
02:43Last but not least, what we wanna do is start up our server.
02:45And this time around the way we're gonna do it is
02:47a little bit different.
02:48We wanna also debug things.
02:50So I'm gonna type your debug Sam debug sample,
02:55that's the name of our folder, name of our project really.
02:58And I'm gonna go ahead here and, uh, put their A star
03:01and I'm gonna tape their NPM start.
03:05Now once I've done this
03:07and I click on enter,
03:08what's gonna happen is it's gonna start our server
03:11and it's also gonna listen to any errors and any issues.
03:13It's gonna sit there and listen
03:14and debug just like we we've had previously.
03:17But this is the style that is recommended
03:19by the express generator documentation.
03:22If I go ahead into my server directly
03:24and just click here on refresh, you'll see
03:25that our express generator, we have your, uh, default page
03:28that's already sitting here and configured.
03:30And if I go into my source files, you'll see
03:32that we have a new sample folder
03:34and it has a lot of different files
03:36and it's already pre-baked with all these different goodies
03:39that you could look into from the package through module,
03:42all the modules which were installed and a lot more.
03:45And you, what you could do, even if you're not planning
03:47to use this as your base project is installed this once,
03:51play around with the configurations
03:52and see how it's set up,
03:54how they recommend to set things up.
03:56And then you could choose based on that, what you want
03:58to implement and whatnot
03:59and create your own basically template
04:02and work with your own template in, in the future.
04:05'cause all you really need from your template is
04:06that JSON file
04:07and maybe a couple of folders structures
04:09that you have pre-configured.
04:12We now know everything
04:14or almost everything that we really need to know
04:16to run a great Express server, express node JS server.
04:21But before we wrap up this topic, I want
04:23to end up this section with one more lecture,
04:26which we'll go back to React.
04:28And through it we're gonna learn a few more things about
04:30things that you could do and configure on the server.
04:34I.

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!