02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoPrevious 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.

Starting up an Express.js server

Learn how to start up an Express.js server, including installation, basic setup, and creating a Hello World server.

08:08

Enabling static files

Learn how to enable static files in Express.js to serve HTML, CSS, JavaScript, and other assets in your web application.

04:47

Routing with Express

In this video, explore the basics of routing in Express.js and how to create dynamic content. Learn about GET, POST, PUT, DELETE, and how to handle different routes effectively.

09:08

Routing with Forms and Static Files in Express.js

Learn how to create dynamic routes with forms and static files using Express.js. This is essential for building interactive web applications.

06:14

Using Middleware in Express.js

Learn how to integrate third-party middleware in Express.js, specifically using body-parser, to handle form data and extend server functionality.

07:29

Creating a middleware in ExpressJS

Learn how to create your own middleware in ExpressJS to handle custom server-side logic and responses.

03:54

Using Express Generator

Learn how to quickly scaffold Express.js applications using the Express Generator tool. This tool helps automate server setup and structure, making development faster and easier.

04:34

Back to React

Learn about integrating Webpack and Babel with React to streamline full stack development.

18:16