Learn about ExpressJS middleware


NodeJS is a server-side platform built on Google Engine V8, with the ability to help implement implementers of the backend of a web application system with Javascript.


However, the feature of NodeJS is to use event-driven programming models, non-I / O blocking (Non-blocking I / O) in order to provide a compact and efficient platform, suitable for real-time web-apps, along with the choice of the Javascript language as the foundation, leaving many libraries and practical utilities for web programming yet, or not enough to satisfy current needs.

So when working with NodeJS, in addition to being familiar with programming thinking not following a fixed flow (event, callback, …), sometimes we will have to go a little deeper to handle the basics. server side. If you've ever worked with some frameworks like PHP's Laravel or Rails, you won't encounter those problems, but it's quite interesting and worth a try.

In today's post, I will tell you about a problem with web programming with NodeJS, about Middleware and its effects and how to use them in backend web development.

Definition of Middleware

Middleware in general

Middleware in the software industry is defined as a bridge-to-bridge software, providing services from the operating system to applications, enabling applications to interact with components. the part allowed by the operating system. Middleware is considered to be a link between software (reference: Wikipedia ).


As you can see in the figure, for an operating system (eg Linux), Middleware will act as software between applications that interact directly with the user and the kernel – the operating system kernel. It can be OpenGL image processing library, hardware / soft device drivers , speech / writing recognition software … All these software if you have ever used a computer or have installed Win, playing games, there must have been one time you heard them. However, an interesting feature is that we will probably need to install these software by hand but … never run them directly, but will use them through games, image and video processing applications , Browser.

Middleware in the Web

With the general idea of ​​a bridge between the interaction of users and the system's core, in Web programming, Middleware will act as an intermediary between request / response (user interaction) and internal logic processing web server.

Therefore, Middleware in Web frameworks (Django, Rails, ExpressJS), will be the functions used to preprocess, filter the request before putting it into processing logic or adjust the response before sending it to the person. use.

In today's article, we will learn how ExpressJS uses Middleware to handle user access.


The figure above shows the 3 middleware included in ExpressJS. A request sent to Express will be handled through 5 steps as follows:

  1. Find the route corresponding to the request
  2. Use CORS Middleware to check the cross-origin Resource sharing of the request
  3. Use CRSF Middleware to authenticate CSRF of request, anti-fake request
  4. Use Auth Middleware to verify if the request is accessed
  5. Handling jobs requested by the request (Main Task)

Any step in steps 2,3,4 if an error occurs will return a notification response to the user, which can be a CORS error, a CSRF error or an auth error depending on which request was stopped at which step.

So you understand Middleware and how they work in Web Application. In the next section, I will discuss in detail how to use these Middleware in Web development using ExpressJS

Middleware in ExpressJS

ExpressJS when running, will basically be a series of Middleware functions that are executed consecutively. Once set up, requests from users when sent to ExpressJS will take turns through Middleware functions until they return the response to the user. These functions will have access to representative objects for Request – req , Response – res , next Middleware functions – next , and error – err objects if needed.

A Middleware function after the operation is complete, if it is not the last in the sequence of functions to be executed, will need to call the next () command to move on to the next function, otherwise processing will be suspended at that function.

The functions that middleware can perform in ExpressJS will include:

  • Do any code
  • Change request and response objects
  • End a request-response process
  • Call the next middleware function on the stack

In Express, there are five types of middleware that can be used:

  • Application-level middleware (application middleware)
  • Router-level middleware (middlware level navigation – router)
  • Error-handling middleware (error handling middleware)
  • Built-in middleware (available middleware)
  • Third-party middleware (third party middleware)

Application-level middleware

When creating a Web Application with ExpressJS, we will have an object that represents that Web App, usually assigned to the app variable . This object can declare middleware through the functions: app.use () or app.METHOD (where METHOD will be the type of HTTP Method supported by ExpressJS, in the form of a lowercase name, eg app.get () , app.post () ).

The example below describes a function that does not declare a specific path, so it will be executed each time the request:

The following example uses the use function to the path / user /: id . This function will be executed each time the request to the path / user /: id regardless of the method (GET, POST, …):

Next is an example of a function that is executed every time you access the path / user /: id by the GET method:

When we want to call a series of middleware functions for a specific path, we can do the following example, by declaring the parameters as functions after the path parameter:

Or we have the tag separated into two app.use declarations , called multiple routes, but in the previous functions we need to call the next () function at the end of each function, if not the example below, the second route 2 will never be executed because the second function in the first route does not call the next () function :

When you want to skip the next middleware function, you will use the next ('route') command , but this only works with middleware functions loaded through the app.METHOD function or router.METHOD .

The following example describes a middleware function that will end immediately when the parameter id = 0 :

Router-level middleware

These middleware are no different from the above application-level middlewware, but instead of using an app variable that can be confusing to the settings, the router part may be unclear and difficult to distinguish, ExpressJS provides. a specialized router object to declare a route by calling the following function:

The following code describes a way to use the router to set the routes needed for a resource named user :

Error-handling middleware

These are middleware for error handling. One note is that the functions for this always take four parameters ( err, req, res, next ). When you want to declare a middlware for error handling, you need to create a function with 4 input parameters. Although you may not need to use the next object, the function still needs to format with four such parameters. Otherwise ExpressJS will not be able to determine if it is an error handling function, and will not run when an error occurs, only works like other middlware functions.

The following code describes an error handling function that transmits to the client 500 errors when an error occurs from the server:

Built-in middleware

Since version 4.x , ExpressJS is no longer dependent on Connect library. In addition to express.static middleware , all other middleware functions have been separated into separate modules. This provides a way to optimize and customize the ExpressJS application in the most flexible way, helping you create a Web Application application that suits your needs, without the unnecessary redundancies. You can refer to the disassembled middlware modules here

Only one Built-in middlware left in ExpressJS is express.static , based on the serve-static library, used to provide static content in Web pages, such as static HTML pages, image files photos, css, js, …

The following paragraph describes using express.static to create a directory named public , users can access html and htm files in this folder:

Also you can declare multiple static directories in a web, the following code will create 3 static directories:

Third-party middleware

Using Third-party will help us add functions to our Web App without losing much implementations.

We will need to install the module via npm , then declare the use in the app object if used at Application-level, or through the router object if used at Router-level.

The code will install and use a middlware named cookie-parser to read cookies of the request:

You can see a list of frequently used Third-party middleware here


So I have covered the nature of Middleware and how ExpressJS uses them in creating a Web Application application. Hopefully the article will help you have an overview and better understand how ExpressJS works, which will make it easier to familiarize and use.

ITZone via Viblo

Share the news now