DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Memory Management in Couchbase’s Query Service
  • How to Build Slack App for Audit Requests
  • Optimizing Database Performance in Middleware Applications
  • Idempotency in Distributed Systems: When and Why It Matters

Trending

  • DGS GraphQL and Spring Boot
  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • The Role of AI in Identity and Access Management for Organizations
  • AI-Driven Test Automation Techniques for Multimodal Systems
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Understanding the Middleware Pattern in Express.js

Understanding the Middleware Pattern in Express.js

In this brief post, author Can Ho explains the middleware pattern in Express.js. Read on for more info.

By 
Can Ho user avatar
Can Ho
·
Updated Jun. 20, 16 · Analysis
Likes (14)
Comment
Save
Tweet
Share
49.5K Views

Join the DZone community and get the full member experience.

Join For Free

The term middleware (middle-ware, literally the software in the middle) may cause confusion for the inexperienced and especially those coming from the enterprise programming world. This is because, in enterprise architecture, middleware reminds of software suites that shield developers from having to deal with many of the low-level and difficult issues, allowing developers to concentrate on business logic.

In express.js, a middleware function is defined as:

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

A middleware function has the following signature:

function(req, res, next) { ... }


There is a special kind of middleware named error-handling. This kind of middleware is special because it takes four arguments instead of three allowing Express to recognize this middleware as error-handling:

function(err, req, res, next) {...}


Middleware functions can perform the following tasks:

  • Logging requests
  • Authenticating/authorizing requests
  • Parsing the body of requests
  • End a request – response lifecycle
  • Call the next middleware function in the stack.

These tasks are not core concerns (business logic) of an application. Instead, they are cross cutting concerns applicable throughout the application and affecting the entire application.

Request-response lifecycle through a middleware is as follows:

alt text





 

  1. The first middleware function (A) in the pipeline will be invoked to process the request
  2. Each middleware function may end the request by sending response to client or invoke the next middleware function (B) by calling next() or hand over the request to an error-handling middleware by calling next(err) with an error argument
  3. Each middleware function receives input as the result of previous middleware function
  4. If the request reaches the last middleware in the pipeline, we can assume a 404 error
app.use((req, res) => {
    res.writeHead(404, { 'Content-Type': 'text/html' });
    res.end("Cannot " + req.method.toUpperCase() + " " + req.url);
});


As we can see, the idea behind the middleware pattern is not new. We can consider middleware pattern in Express.js a variant of:

  • Intercepting Filter
  • Chain of Responsibility

This pattern has some benefits:

  • Avoid coupling the sender of a request to the receiver by giving more than one object a chance to handle the request. Both the receiver and the sender have no explicit knowledge of each other.
  • Flexibility in distributing responsibilities among objects. We add or change responsibilities for handling a request by adding to or changing the chain at run-time.

References

  • http://www.oracle.com/technetwork/java/interceptingfilter-142169.html
  • http://www.javaworld.com/article/2073684/java-web-development/follow-the-chain-of-responsibility.html
  • http://expressjs.com/en/guide/using-middleware.html

Update: A new post about design patterns in Express has been published. If you want to take a look, please follows this link

Middleware Express Requests

Published at DZone with permission of Can Ho, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Memory Management in Couchbase’s Query Service
  • How to Build Slack App for Audit Requests
  • Optimizing Database Performance in Middleware Applications
  • Idempotency in Distributed Systems: When and Why It Matters

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!