Middleware in Nodejs

Learn via video courses
Topics Covered

Overview

We see a web server as a function that takes in a request object and outputs a response. Middleware is anything that is placed in between the request-response cycle. Thus we can say that middleware is a function used in connecting a bunch of isolated systems to interact and perform certain tasks.

Pre-requisites

You will need the following pre-requisite to follow along with the article :

  • Node js must be locally installed in your system.
  • A broad understanding of Node js is recommended but not needed.
  • Basic knowledge of javascript functions and express server.
  • Basic knowledge of the request and response cycles and how to use req and res objects.

What is Middleware in Node Js?

When an HTTP request is received by the web server, express gives an object that contains details about the data, requested resource, IP address of the client, and some browser information. This object is the request object (req). Similarly, a response object (res) is also provided by express. The response object can also be modified before being sent to the user.

What is Middleware in Node js

Middleware functions provide access to the request (req) and response (res) objects. They are the perfect way to modify the req and res objects. For example, we can fetch user details after the user has logged in and save these details in the request object.

Syntax of a Middleware:

Some properties about the middlewares :

  • Middleware functions have three parameters: request object, response object, and next() function.
  • The request and response objects are unique for each request.
  • Generally a chain of middleware is used where after one middleware is executed the next is called. The last middleware function passes the request to the web server. After that, the response is sent back to the browser.
  • The request and response objects passed to a middleware function will have the changes done by the predecessor middleware functions.
  • If a middleware does not have the next function called, it will result in a connection timeout.

Advantages of Using Middleware

Here are some common advantages of using middleware:

  • Middleware allows the flow of real-time data access among the systems in a network.
  • Middleware has access to the request object and can manipulate the request object before reaching the server.
  • Middleware is used for authentication purposes and some logging functionality.
  • Middleware helps with optimization and increased performance.
  • Middleware can be used for specifying some HTTP headers.
  • Middleware enhances client-side rendering performance.
  • In industry, middleware helps simplify processes and enhances performance in terms of organization.

How Does Node.js Middleware Pattern Work?

Middleware is an intermediate part of the request - response cycle of the node.js execution. It has access to both the request and response objects and the next middleware function. The tasks performed by the middleware are not core concerns of the application. They are cross-cutting concerns, that is, they affect other concerns.

The middleware functions can perform several tasks, such as follows:

  • Quickly change the request and response objects
  • Call the next function in the middleware chain
  • Execute any code effectively.
  • End the request-response cycle.
  • Logging requests
  • Authorizing requests.

The request-response cycle along with middleware can be represented as shown,

How Does Node.js Middleware Pattern Work

When the current middleware does not stop the request-response cycle, the next() function is called, and the control gets passed to the next middleware function. A 404 error is assumed if the request reaches the last middleware in the chain.

What is next() ?

Next() is a function that calls the next middleware function in the chain of middleware after the operations of the current middleware have been performed. It is called the end of the middleware’s body. As with the functionality of route handlers, a middleware will ensure the receipt of the request and response objects effortlessly.

We refer to the request object as req and the response object as res. The next parameter is the next function. It plays an important role in building the request-response cycle of the application.

Some of the essential tasks performed by the middleware function:

  • Building the request and response cycle.
  • Executing the code in its body.
  • Calling the next middleware method in the chain.
  • Manipulating the request and response objects.

When there is no automated end to the request-response cycle of the current middleware, no requests should be left in the request queue.

What is Express Middleware?

Express.js middleware is various functions invoked by the express.js routing layer before the last request handler. Express middleware functions are compiled during the lifecycle of the Express server. As the name indicates, Middleware appears between the initial request and the final intended route. In stack, middleware methods are always invoked in the hierarchy to which they are added.

What is Express Middleware

Middleware is generally used to perform tasks like cookie parsing for basic cookie handling or for body parsing for URL encoded or JSON requests. Moreover, Middleware will allow you to categorize the code and generate reusable Middleware, just like chaining.

List of commonly used express middlewares:

Middleware ModuleDescription
body-parserParse HTTP request body. See also: body, co-body, and raw-body.
compressionCompress HTTP responses.
connect-ridGenerate unique request ID.
corsEnable cross-origin resource sharing (CORS) with various options.
csurfProtect from CSRF exploits.
cookie-parserParse cookie header and populate req.cookies. See also cookies and keygrip.
cookie-sessionEstablish cookie-based sessions.
errorhandlerDevelopment error-handling/debugging.
morganHTTP requests logger.
multerHandle multi-part form data.
response-timeRecord HTTP response time.
timeoutSet a timeout period for HTTP request processing.
vhostCreate virtual domains.
sessionEstablish server-based sessions (development only).
serve-indexServe directory listing for a given path.
method-overrideOverride HTTP methods using a header.
serve-faviconServe a favicon.

Types of Middleware in Node.js

1. Application-level Middleware :

In this type of middleware, we mainly focus on the creation and use of the authentication middleware. This type of middleware is required when there are some private routes ( GET or POST ) in your application that can only be accessed by authenticated users.

When your application receives the authentication request, the authentication middleware will receive the request object and will start the process of the code execution present in the authentication function of the application. After successful authentication, the next() function is called, which passes the control to the next middleware or the next route. However, if the authentication is not successful, the private routes will not be accessible, and errors will be displayed by the middleware.

2. Router-level Middleware :

Router-level middleware can be loaded by making use of the methods like router.METHOD() and router.use(). Router-level middleware is the second type under middleware in Nodejs and works exactly like the application-level middleware, which is defined above. Router-level middleware has the power of limiting the instances and also generate instances using the Express.Router() method.

3. Build-in Middleware :

The built-in middleware does not rely on the Connect method, and unlike the previous 4.X version types, Express now acts as a module.

Typically, under the Express types of middleware, you can use the middleware functions listed below,

  • static - a function that acts as a static asset to the application.
  • json - a function that computes the incoming request by adding JSON payloads.

4. Error-handling Middleware :

Expess.js framework is capable of handling any default errors and can also define error-handling middleware methods. The major difference from other middleware types is error handling techniques.

5. Third-party Middleware :

Third-party middleware is used when we need to have some additional functionalities in the backend of our app. We can install any Node js module using npm (Node package manager) or yarn (Yet Another Resource Negotiator) and then integrate that module into our application on the router or application level.

Middleware Chaining

Generally, a set of middlewares are chained to form a set of functions that execute one after the other in order. The next() function is called at the end of every middleware to pass the control to the next middleware. The last middleware function sends back the response to the client. Hence, different middleware process the request before the response is sent back.

The modified request and response variables are passed in the next middleware function when the next() function is called.

Middleware Chaining

In the above diagram, the request is modified by several middlewares, chained in the middleware stack using the next() function. The router sends the response back to the client after the processing is done.

Middleware Syntax

The syntax of the middleware functions is as follows –

The second parameter or the middle part represents the middleware.

The first parameter is the request object. It contains the details about the request sent like the request body, baseURL, path, route, etc. These details can be used to fetch user information.

The second parameter is the response object which has the details of the response that is sent back. The response object facilitates the setting of cookies in the user's browser.

New properties can be defined in the req and res objects. Changes made in the current middleware will be reflected in the request and response objects in the next middleware function.

The body of the middleware has all the operations performed by the middleware before it sends the control to the next middleware function by calling the next(). The next function sends the control to the successor middleware function in the middleware chain.

Middleware Syntax

Creating a Middleware

The following steps will show how we can create middleware :

Step 1: Open your project directory and make sure that Node.js is installed on your system. Initialize your project by running the following command in the terminal:

This will ask a set of questions and then create a package.json file.

Step 2: Install the following dependencies using the below command.

Step 3: Add the following line in the scripts section of the package.json file. "start": "node server.js",

Step 4: Create a server.js file in the project directory. Now your project structure will look like the following :

Creating a Middleware

Step 5: Now we will create our express app to handle requests and send back a response to the client. Write the below code in the server.js file:

Now, Run the express application as follows,

Output:

Output

Step 6: Now to create a middleware modify the code in server.js as follows and restart the server.

Output:

Conclusion

  • Middleware is an intermediate part of the request - response cycle of the node.js execution.
  • Middleware functions provide access to the request (req) and response (res) objects and hence can manipulate both of the objects.
  • Middleware functions have three parameters: request object, response object, and next() function.
  • Middleware increases client-side rendering performance and provides logging functionality.
  • If a middleware does not have the next function called, it will result in a connection timeout.
  • Next() is a function that calls the next middleware function in the chain of middleware after the operations of the current middleware have been performed.
  • There are five types of middleware in Node js - Application-level, Router-level, Third-party, Build-in type, and Error-handling middleware.
  • In middleware chaining a set of middlewares is chained to form a set of functions that execute one after the other in order.