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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Guide to E-Commerce Mobile App Development: Steps, Features, and Costs
  • Design Pattern: What You Need to Know to Improve Your Code Effectively
  • The Art of App Development: Tips for Building a Successful Mobile App
  • Accessibility Testing for Digital Products

Trending

  • Message Construction: Enhancing Enterprise Integration Patterns
  • How To Aim for High GC Throughput
  • Agile Estimation: Techniques and Tips for Success
  • A Complete Guide to Open-Source LLMs
  1. DZone
  2. Coding
  3. JavaScript
  4. Design Patterns in Express.js

Design Patterns in Express.js

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Let's check out the different design patterns that we might see when working with Express.js.

Can Ho user avatar by
Can Ho
·
Jun. 23, 16 · Tutorial
Like (3)
Save
Tweet
Share
44.74K Views

Join the DZone community and get the full member experience.

Join For Free

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Below are some design patterns that we might see when working with Express.js...

Factory

This is a simple and common design pattern in JavaScript. Factory is a creational design pattern allowing us to abstract away object creation implementation details from the outside world. Express does this by only exporting the factory.

/**
 * Expose `createApplication()`.
 */

exports = module.exports = createApplication;

function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };
  ...
  return app;
}

And, using the factory to create an express application is as simple as this:

import express from 'express';
..
const app = express();

Middleware

Middleware is the term popularized by Express.js.

In fact, we can consider this design pattern a variant of Intercepting Filter and Chain of Responsibility

Image title

You may want to know more about this pattern—click here.

Decorator

The Decorator pattern extends (decorates) an object’s behavior dynamically. It's different from classical inheritance because new behavior is added at run time and only add to objects (not classes) that are decorated.

Image title


An easy example for this pattern is the req and the resp. In Node, the request and response objects have very limited APIs. Express enhances these objects by decorating them with a lot of new features.

Below is the function that takes request (req) and response (resp) objects and decorate them:

///lib/middleware/init.js
exports.init = function(app){
  return function expressInit(req, res, next){
    if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express');
    req.res = res;
    res.req = req;
    req.next = next;

    req.__proto__ = app.request;
    res.__proto__ = app.response;

    res.locals = res.locals || Object.create(null);

    next();
  };
};

Strategy

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Image title

It allows a strategy (algorithm) to be swapped out at runtime by any strategy without the client realizing it.

In Express, the Strategy pattern can be seen in the way Express supports various different template engines such as Pug, Mustache, EJS, swig, etc.. Take a look at here for the full list of supported engines

import express from 'express';
import exphbs from 'express-handlebars';
...
const app = express();
app.engine('.html', exphbs({...}));
app.engine('jade', require('jade').__express);

//Select the strategy '.html'
app.set('view engine', '.html');

Another example is the way Express supports "Content Negotiation"

Proxy

This is a design pattern that provide an object called proxy (or surrogate) that controls access to another object called subject. The proxy and the subject have the same interface. The proxy sits between the client and the subject intercepting all or some requests and forwarding them to the subject.

Image title


In Express, there're two types of middleware:

  • Application-level middleware

  • Router-level middleware

Apart from the fact that application level middleware bound to an application object and that router level middleware bound to a router instance, they are same. So, how does Express archive this ? By composition! The express application object holds an internal reference to a Router instance object.

this._router = new Router({
      caseSensitive: this.enabled('case sensitive routing'),
      strict: this.enabled('strict routing')
});

this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));

With each supported API, the application object will do some logic checking and validation before forwarding requests to the internal router instance.


Note: There're more patterns that I don't list here such as: Singleton, Lazy Initialization, Event Emitter, etc.

Express Design Object (computer science) mobile app

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

Opinions expressed by DZone contributors are their own.

Related

  • Guide to E-Commerce Mobile App Development: Steps, Features, and Costs
  • Design Pattern: What You Need to Know to Improve Your Code Effectively
  • The Art of App Development: Tips for Building a Successful Mobile App
  • Accessibility Testing for Digital Products

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: