Middleware & Express

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:08:00

What is Middleware in Express JS?

Middleware is a request handler that enables you to intercept and change requests and responses before they reach route handlers. These are the methods that the Express.js routing layer calls. This adaptable tool facilitates adding features to Express applications, including error handling, logging, and authentication. 

Middleware Types

There are different types of middleware available in Express JS:

  • Application-level Middleware
  • Router-level Middleware
  • Built-in Middleware
  • Third-party Middleware
  • Error-handling Middleware

Application-level Middleware

When using Express, application-level middleware binds to an instance of the app object. With the app, it is put into practice.Use() and app.METHOD() functions are used, where METHOD is a lowercase representation of HTTP methods such as GET, PUT, POST, and DELETE.

Router-level Middleware

Router-level middleware is attached to an instance of express.Router(). These middlewares are loaded with the router.use() and router.METHOD() operates, giving routing-specific functionalities to your application.

Built-in Middleware 

The main built-in middleware function is express.static, introduced in Express 4.x. It improves the serving capabilities of your Express application by providing static assets like HTML files and graphics.

Independent Middleware

With third-party middleware, your Express app's capabilities are increased. These can be added at the router or application level and are installed via NPM. Cookie-parser, body-parser, and express-session are a few examples.

Middleware for managing errors

Express's error-handling middleware is essential for managing exceptions and errors. For your application to have strong error handling, you must use this type of middleware, which always requires four arguments.

Functions of Middleware

The following are some common middleware functions in Express:

  • Logging: Every request that comes in, including its method, URL, and timestamp, can be recorded by middleware. For monitoring and debugging purposes, this is helpful.
  • Error handling: Errors that arise while processing a request can be handled via middleware. This could include recording the issue, responding to the client with a suitable error message, or executing other steps to properly manage the mistake.
  • Authentication: By looking for authentication tokens, session cookies, or other credentials, middleware can confirm that a request is coming from a user who has granted permission. In accordance, it can then permit or refuse access to protected routes.
  • Authorization: Middleware can determine if a user is authorized to utilize a certain resource or carry out a specific task. This could entail comparing the user's permissions and role against a list of access control guidelines.
  • Parsing request bodies: To retrieve client-sent data, such as form data or JSON payloads, middleware can parse the body of incoming requests. Route handlers or later middleware can then process this data.
  • Setting response headers: Middleware can add additional metadata to the response, allow Cross-Origin Resource Sharing (CORS), and regulate cache behavior by configuring the HTTP headers on the response object.
  • Compression: By reducing the volume of data sent over the network, middleware can compress outgoing answers, enhancing performance and using less bandwidth.
  • Request validation: Incoming request data can be checked by middleware to make sure it satisfies requirements or adheres to a set format. By doing this, security flaws are avoided and desired application behavior is guaranteed.
  • Rate-limiting: To stop misuse or server overload, middleware can impose rate limits on incoming requests. This could entail keeping tabs on how many requests each client makes and restricting or limiting those who send in more than a predetermined amount.
  • Response formatting: To provide uniformity between various application components, middleware might format outgoing responses. This might entail adding standardized error messages to error answers or transforming data objects into a certain format (like JSON).

Steps for Creating Middleware in Express.js

  • Define the middleware function: Create a function that accepts req, res, and next.
  • Apply the logic: Inside the function, specify the middleware's tasks, such as logging.
  • Call next(): If necessary, use next() to transfer control to the next middleware.
  • Use middleware: To deploy middleware either globally or to individual routes, call app.use().
  • Test: Ensure that the middleware performs as intended.

What is Middleware Chaining?

Middleware chaining in Express.js is the process of combining numerous middleware functions to form a chain in which each function performs a certain task sequentially before passing control to the next function. This enables modularization & separation of concerns when handling incoming requests.

What is the middleware module in Express.js?

Middleware modules in Express.js are functions or sets of functions that can access the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. These modules are capable of running code, modifying request and response objects, terminating the request-response cycle, and calling the next middleware function in the stack.

List of Express Middleware Modules

  • body-parser: A middleware that parses incoming request bodies in Express. It extracts the whole body of an incoming request stream and exposes it to the req.body.
  • compression: Middleware for compressing HTTP responses in Express. It compresses responses before transmitting them to the client.
  • connect-rid: Express middleware that generates unique request IDs. It assigns a unique identity to each incoming HTTP request to help with request tracking and debugging.
  • cookie-parser: Express middleware that parses cookies. It parses the Cookie header and adds an object to req.cookies with the cookie names as the key.
  • cookie-session: Middleware for managing cookie-based Express sessions. It supports sessions through the use of cookies, which store session data on the client.
  • cors: Express middleware that enables cross-origin resource sharing (CORS). It offers regulated access to resources that are situated outside of the server's original domain.
  • errorhandler: Express middleware that handles errors. In development mode, it offers a stack trace, but in production, it displays generic error messages.
  • method-override: An Express middleware that allows you to override HTTP methods. It enables clients to imitate DELETE and PUT requests via a query value or HTTP header.
  • morgan: Middleware for recording HTTP requests in Express. It records request information such as method, URL, status, response time, and more.
  • multer: Middleware for Express that handles multipart/form data. It enables file uploads by processing form data containing files from the request body.
  • response-time: Middleware that tracks Express response timings. It calculates the response time for requests and includes an X-Response-Time header in the response.
  • serve-favicon: Middleware for serving favicons in Express. It uses the specified favicon.ico file or a default favicon from the given directory.
  • serve-index: In Express, this is the middleware that serves directory listings. When the requested URL points to a directory that does not have an index file, it generates a directory listing.
  • serve-static: Express middleware that serves static files. It serves static assets from the provided directory, including HTML, CSS, and pictures.
  • session: Middleware for managing sessions in Express. It provides session support by saving session data on the server and keeping the session state for clients.
  • timeout: Middleware that handles Express request timeouts. It terminates queries that exceed a certain time limit.
  • vhost: Express virtual hosting middleware. It allows you to host many domains or subdomains within the same Express application.

Advantages of Middleware

  • Modularization: Middleware enables you to divide your application's logic into smaller, more reusable components. This enhances code organization and maintainability.
  • Flexibility: Middleware enables the Express.js application to handle requests and responses more flexibly. You can customize the request-response cycle by adding, removing, or reordering middleware.
  • Reusability: Middleware functions can be reused in several routes or applications, eliminating code duplication and encouraging a DRY (Don't Repeat Yourself) approach.
  • Enhanced Functionality: Middleware can be used to add new functionality to your application, like authentication, logging, error handling, request processing, and so on, without clogging the route handlers.
  • Error Handling: Middleware can be specifically developed to handle mistakes in a centralized manner, making error management easier throughout the application.

Disadvantages of Middleware

  • Complexity: As the number of middleware components grows, so does the application's complexity, particularly if the middleware stack becomes difficult to comprehend or maintain.
  • Order Dependency: Middleware functions are run in the order in which they are defined, which can result in unexpected behavior if not carefully controlled. This can be difficult to debug in large applications.
  • Performance Overhead: Each middleware function adds overhead to the request-response cycle, which can have an impact on application performance, particularly if inefficient or resource-intensive middleware is utilized.
  • Callback Hell: In some circumstances, significant use of middleware can result in "callback hell," which makes the code difficult to read and understand owing to deeply nested callback procedures.
  • Potential Security Risks: If middleware is not properly set up or maintained, it may create security vulnerabilities, particularly in the authentication and authorization areas.
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
Accept cookies & close this