Introduction to MiddleWare architecture of ExpressJS
The Express.js routing layer calls many types of Express.js Middleware functions before the actual request handler. Middleware, as its name suggests, sits between the initial request and the intended ultimate route. The sequence in which middleware functions are added determines how they are always called in the stack.
To carry out activities like body parsing for URL-encoded or JSON requests, cookie parsing for fundamental cookie handling, or even dynamically creating JavaScript modules, middleware architecture in the express is frequently utilised.
For running JavaScript code outside of a browser, Node.js is an open-source, cross-platform runtime environment. It is based on Chrome's V8 JavaScript engine. It's important to remember that NodeJS isn't a programming language or a framework.
Express.js is a routing and middleware framework that operates between the request and response cycle and can handle the various routes of a webpage. After the server receives the request, middleware is run before the controller sends the response. Before the server sends a response, middleware architecture in express can process the request with access to the request and response objects. A collection of middleware function calls make up an Express-based application.
ExpressJS is a popular web framework for Node.js that provides a simple and flexible middleware architecture to build web applications. Middleware is software that sits between an application's request and response and performs various functions such as parsing request data, handling cookies, logging, error handling, and more.
In the context of ExpressJS, middleware is a function that has access to the request and response objects and the next() function in the application's request-response cycle. The next() function is a callback function that passes control to the next middleware function in the stack.
The middleware functions can be organized in a sequence, forming a middleware chain, which can be mounted to a specific route or globally to the application. When a request is made to the server, the middleware chain is executed sequentially. Each middleware function has the option to modify the request and response objects or pass control to the next middleware function in the chain. Broadly we can say:
- Middleware is a request handler that has access to the request-response cycle of an application.
- It is a function that stores the middleware function, the response object, and the request object.
- The response may be sent to the server prior to the request using middleware architecture in express.
- A variable with the name next is frequently used to signify the next middleware function.
- Middleware is a function that can only be used with routes, to put it simply.
- Using middleware architecture in express, we may access and alter request and response data.
Advantages
Middleware is a key feature of the framework that provides several advantages. Here are some of the advantages of using middleware architecture in express:
- Reusability : Middleware functions can be reused across different routes and applications. This can help to reduce the amount of code duplication and simplify the development process.
- Improved modularity : middleware architecture in express allows you to break down your application into smaller, more manageable parts. This makes it easier to maintain and update your codebase over time.
- Customization : Middleware allows you to customize the behaviour of your application at different stages of the request-response cycle. For example, you can use middleware to add authentication or validation checks to specific routes.
- Error handling : middleware architecture in express can be used to handle errors and exceptions that occur during the request-response cycle. This can help to improve the overall reliability and stability of your application.
- Debugging : Middleware can be used to log information about incoming requests and outgoing responses. This can be helpful for debugging and troubleshooting issues with your application.
- Performance : middleware architecture in express can be used to optimize the performance of your application by caching data, compressing responses, or preloading data.
Overall, express middleware architecture is a powerful tool that can help to improve the reliability, modularity, and performance of your Express.js applications.
What is Middleware?
Express middleware architecture refers to a series of functions that are invoked by the framework in sequence for each incoming HTTP request before the final request handler is called. These functions have access to the request and response objects and can modify them or perform additional operations on them.
Middleware functions can perform a variety of tasks, such as parsing incoming request data, adding headers to responses, logging requests and responses, authentication and authorization, error handling, and more. They are often used to modularize the application logic and separate concerns, making it easier to maintain and extend the codebase.
Middleware can be added to an Express.js application using the app.use() method, which takes one or more middleware functions as arguments. They can also be added to specific routes using the router.use() method. Middleware functions can either call the next() function to pass control to the next middleware function in the sequence or end the request-response cycle by sending a response to the client using res.send() or res.end().
Use of Middleware
The request object (req), the response object (res), and the subsequent function in the application's request-response cycle are all accessible by middleware functions. The Express router's next function, when called, executes the middleware that comes after the one that is now running.
The following tasks can be carried out by middleware functions:
- run any programme.
- Make changes to the request and the response objects.
- Close the request-response loop.
- Invoke the following middleware in the stack.
The current middleware function must call next() in order to transfer control to the following middleware function if it does not stop the request-response cycle. If not, the request will be ignored. The following figure shows the elements of a middleware function call:
When they reject or throw an error, middleware methods that return a Promise will start calling next(value) with Express 5. either the rejected value or the Error that was thrown will be passed to next.
Here are some common use cases for express middleware architecture:
- Authentication : Middleware can be used to check if a user is authenticated before allowing access to certain routes or resources. For example, you might use middleware to check if a user has a valid session or token before allowing them to access protected data.
- Logging: Middleware can be used to log information about each request that comes into your application. This can be useful for debugging, monitoring performance, and tracking user behaviour.
- Error handling : Express middleware architecture can be used to handle errors that occur during the request-response cycle. For example, you might use middleware to catch and log errors or to return a custom error message to the client.
- Routing : Middleware can be used to handle routing logic for your application. For example, you might use middleware to map a URL to a specific controller function or to modify the request object before it is passed to the next middleware function.
- Compression : Express middleware architecture can be used to compress the response data that is sent to the client, which can improve performance by reducing the amount of data that needs to be transferred over the network.
Another important application of middleware in the express is middleware chaining
Middleware Chaining
Because middleware can be linked together, a chain of sequentially run functions can be created. The response is returned to the browser in the final function. Therefore, various middleware processes the request before returning the result to the browser.
If there is middleware, the next() method in the express package is responsible for calling it. Each middleware will have access to modified requests through the following function:
In the scenario mentioned above, numerous middlewares are used to modify the incoming request and carry out a number of activities. Middleware is chained using the next function. The response is returned to the browser by the router.
The following is the fundamental syntax for the middleware functions.
Three arguments are required for middleware functions: the request object, the response object, and the subsequent function in the request-response cycle of the application, or two objects and one function.
Middleware functions typically add information to the request or response objects and perform some code that may have unintended consequences for the application. They can also break the cycle by responding when a certain need is met. If they don't send a response when they're finished, they begin the stack's subsequent function's execution. This causes the third argument to be called next().
The middleware function is contained in the middle portion (req,res,next)=>(). Here, we typically carry out the tasks that must be completed before the user is permitted to view the webpage, access the data, and execute a variety of other tasks. So let's develop our own middleware and examine its applications.
Let's build our middleware and check how it functions.
Step 1 : To create a NodeJs project, navigate to your project directory and type the following command. Ensure that NodeJs is set up on your computer.
It'll build a package file in json.
Step 2 : Run the following command to install two dependencies.
Step 3 : Add the next line of code to the package.json file's scripts section.
Step 4 : In the directory, make an index.js file. Verify that it is not located in any of the directory's subdirectories where you are currently working.
Project Organization :
It will be like the image given below:
Our express app will now be configured, and a reply will be sent to our server.
Here is the index.js file's source code.
Enter the following command in the terminal to run the code.
Output :
Functions of Middleware
Here is an example of a simple “Hello World” Express application. The remainder of this article will define and add three middleware functions to the application: one called myLogger that prints a simple log message, one called requestTime that displays the timestamp of the HTTP request, and one called validateCookies that validates incoming cookies.
Middleware Function MyLogger
Here is a straightforward illustration of the "myLogger" middleware function. When a request is made to the app, this method simply prints "LOGGED" in response. MyLogger, a variable, is given the middleware function.
Notice the call above to next(). The next middleware function in the app is called when this one is called. The third argument supplied to the middleware function is the next() function, which is independent of the Node.js or Express APIs. The next() function's name is always "next," but it might have any other name by convention. Use this convention at all times to prevent confusion.
Call app.use() with the middleware function specified to load the middleware function. For instance, the code below loads the middleware function for myLogger before routing to the root path (/).
The software writes "LOGGED" to the console whenever it receives a request.
Middleware functions that are loaded first are also run first, therefore the order in which they are done is crucial. Because the route handler of the root path ends the request-response cycle, if myLogger is loaded after the route to it, the request never reaches it and the app doesn't print "LOGGED."
The role of middleware MyLogger only produces a message and then uses the next() function to forward the request to the following middleware function in the stack.
Middleware Function RequestTime
Next, we’ll create a middleware function called “requestTime” and add a property called requestTime to the request object.
The requestTime middleware feature is now utilised by the app. Additionally, the root path route's callback function makes use of the property that the middleware function adds to req (the request object).
The app now shows the timestamp of your request in the browser when you send a request to the app's root.
Middleware Function ValidateCookies
The last step is to build a middleware function that verifies incoming cookies and returns a 400 error code if they are invalid.
Here is an illustration of a function that verifies cookies using an outside async service.
The last step is to build a middleware function that verifies incoming cookies and returns a 400 error code if they are invalid.
Here is an illustration of a function that verifies cookies using an outside async service.
Take note of how await cookieValidator(req.cookies) is called before next(). This guarantees that the subsequent middleware in the stack will be called if cookieValidator resolves. Express considers the current request to be an error and skips any remaining middleware and routing methods that don't handle errors if you send anything to the next() function (other than the string "route" or "router").
The possibilities with middleware functions are unlimited because you have access to the request object, the response object, the subsequent middleware function in the stack, and the entire Node.js API.
Configurable Middleware
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
File: my-middleware.js
As demonstrated below, the middleware can now be used.
Creating Middleware
Middleware in Express.js refers to a group of operations that are carried out during the request-response phase of an HTTP request. Before handing up control to the following middleware in the chain, middleware functions have access to the request and response objects and can modify them as needed.
In Express.js, you may utilise the use method of an instance of the express module to create a middleware. Here's an illustration:
In this example, the myMiddleware function is defined as a middleware function that simply logs a message to the console. The app.use method is then used to apply the middleware to all routes in the application.
When a request is made to any route in the application, the middleware function will be executed first. It will log a message to the console and then pass control to the next middleware in the chain, which in this case is the route handler function for the / route.
This is just a basic example, but middleware functions can be used for a wide variety of purposes, such as authentication, logging, error handling, and more. By creating custom middleware functions, you can add additional functionality to your Express.js applications and improve the overall user experience.
Conclusion
- Express middleware architecture is a powerful feature that allows developers to add functionality to an application's request/response cycle.
- Middleware functions are essentially just functions that have access to the request and response objects and the next function in the cycle.
- Middleware can be used for a wide range of purposes, such as handling authentication, logging, error handling, and request/response processing.
- Middleware functions can be chained together to create a pipeline that processes requests in a specific order.
- Express.js provides a number of built-in middleware functions, such as the static file server and body-parser, which can be used to handle common tasks.
- Developers can also create their own middleware functions to handle custom logic and integrate with third-party libraries.
- Middleware functions can be added to the entire application or to specific routes or groups of routes.
- Care should be taken when adding middleware functions to ensure that they are added in the correct order and that they do not interfere with each other.
- Express.js also provides a mechanism for error-handling middleware, which can be used to handle errors that occur during the request/response cycle.
- Overall, middleware is a key feature of Express.js that allows developers to create flexible and powerful web applications.