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
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Client-Side Challenges in Developing Mobile Applications for Large User Bases
  • Next.js vs. Express.js: What Are the Differences?
  • Guide to E-Commerce Mobile App Development: Steps, Features, and Costs
  • Design Pattern: What You Need to Know to Improve Your Code Effectively

Trending

  • Your AI Agent Tests Are Passing, But Your Agent Is Still Broken
  • Why Stable RAG Answers Can Still Hide Unstable Evidence
  • Identity in Action
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  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.

By 
Can Ho user avatar
Can Ho
·
Jun. 23, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
50.9K 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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Client-Side Challenges in Developing Mobile Applications for Large User Bases
  • Next.js vs. Express.js: What Are the Differences?
  • Guide to E-Commerce Mobile App Development: Steps, Features, and Costs
  • Design Pattern: What You Need to Know to Improve Your Code Effectively

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook