• Summarizing the pros and cons of Express. Source: Kharchenko 2017.
    image
  • A typical HTTP request/response call flow with Node and Express. Source: Turing School 2019.
    image
  • Express enables a series of middleware calls. Source: Grewe 2019.
    image
  • Elements of an app-level middleware call. Source: Express 2018e.
    image
  • Folder structure created by express-generator. Source: Express 2018c.
    image

Express.js

userimg
arvindpdmn
964 DevCoins
1 author has contributed to this article
Last updated by arvindpdmn
on 2019-03-01 03:32:59
Created by arvindpdmn
on 2019-02-27 07:58:19
Improve this article. Show messages

Summary

 image
Summarizing the pros and cons of Express. Source: Kharchenko 2017.

Express is a minimalistic web framework based on Node.js. It's essentially a series of middleware function calls, each of which does something specific. Express in not opinionated, which is also why you're free to use it in different ways. For example, it doesn't enforce a particular design pattern or a folder structure.

Express is an open source project that's been managed by Node.js Foundation since 2016. Express has good adoption. It's part of the MEAN stack. It's also being used by many other web frameworks such as Kraken, LoopBack, Keystone and Sails. However, it's been said that Express is not suited for large projects/teams.

Milestones

2009

Ryan Dahl and others at Joyent develop Node.js with initial support for only Linux. The name Node is coined in March. Being open source, version 0.1.0 is released on GitHub in May. In November, Ryan Dahl presents Node.js at JSConf in Berlin.

Nov
2010

As a web development framework based on Node.js, v1.0.0 of Express.js is released. The development of Express can be traced to January 2010 when v0.1.0 was committed on GitHub.

2011

To manage packages for Node.js, Node Package Manager (NPM) is released. An early preview of NPM can be traced to 2009, by Isaac Z. Schlueter.

Apr
2013

Valeri Karpov at MongoDB proposes a full-stack solution that he terms the MEAN stack: MongoDB, Express, Angular and Node. Given that three of these are based on JavaScript, this promotes the demand for full-stack developers who can handle both frontend and backend code.

Jul
2014

StrongLoop acquires commercial rights to Express. StrongLoop itself offers an open source API framework called LoopBack on top of Node and Express. Some community folks criticize this "sponsorship" or "sale" of what was an open source project.

Feb
2015

Joyent, IBM, Microsoft, PayPal, Fidelity, SAP and The Linux Foundation come together to establish Node.js Foundation.

Sep
2015

IBM acquires StrongLoop, a company that specializes in Node.js, Express.js and API management. StrongLoop is said to offer "robust implementation, making Node.js enterprise-grade". This acquisition could mean better adoption of Node and Express in the corporate world.

Feb
2016

Doug Wilson, one of the main contributors to Express, decides to stop working on Express. This is mainly because what was once an open source project is now controlled by IBM/StrongLoop. Express community also state their unhappiness with the way the framework is managed. Meanwhile, in a move towards open governance, Express is handed over to Node.js Foundation as an incubation project.

Oct
2018

Version 4.16.4 of Express is released. The same month version 5.0.0-alpha.7 is released. Version 5.0.0-alpha.1 can be traced back to November 2014.

Discussion

  • Why should I use Express.js when there's already Node.js?
     image
    A typical HTTP request/response call flow with Node and Express. Source: Turing School 2019.

    While it's possible to build a web app or an API service with only Node.js, Express.js simplifies the development process. Express itself is based on Node. It's been said that Express...

    provides a thin layer of fundamental Web application features, without obscuring Node.js features that you know and love.

    For example, sending an image is complex in Node but easily done in Express. In Node, the route handler is a large monolith but Express enables more modular design and maintainable code.

    Node is a JavaScript runtime for server-side execution. Thus, Node can be used as the app server for your web application. Express is seen as a lightweight web framework. Express comes with a number of "middleware" software that implement out-of-the-box solutions for typical web app requirements. HTTP requests/responses are relayed by Node to Express, whose middleware then do the processing.

  • Could you explain the concept of middleware in Express.js?
     image
    Express enables a series of middleware calls. Source: Grewe 2019.

    When client requests are received, the server doesn't handle all of them alike. For example, submitting a form is handled differently from clicking a like button. Thus, each request has a well-defined handler, to which it must be properly routed.

    Middleware sits in the routing layer. Express is basically a routing layer composed of many modular processing units called middleware. Requests are processed by middleware functions before sent to the handlers.

    A request-response cycle can invoke a series of middleware functions. A middleware can access and modify the request and response objects. Once a middleware function has completed, it can either pass control to the next middleware function (by calling next()) or end the cycle by sending a response to the client. Since middleware can send responses, even the request handlers can be treated or implemented as middleware.

    Middleware can also be called after the request is processed and response is sent to the client. But in this case, middleware can't modify the request and response objects.

  • What are the different types of Express.js middleware?
     image
    Elements of an app-level middleware call. Source: Express 2018e.

    There are a few types of Express middleware:

    • Application-level: These are bound to an instance of the application object express(). They are called for every app request. The middleware signature is function (req, res, next).
    • Router-level: These are bound to an instance of the router express.Router(). Otherwise, they work similar to app-level middleware.
    • Error-handling: Any middleware can throw an error. These can be caught and handled by error-handling middleware. These middleware have an extra argument in their signature: function (err, req, res, next).
    • Built-in: These are built into default Express installation. These include express.static, express.json and express.urlencoded.
    • Third-party: Express has a rich ecosystem of third-party developers contributing useful middleware. Some of these are maintained by the Express team, while others come from the community. For an example list of some Express middleware, visit Express Resources Middleware page.
  • What are some useful or recommended middleware for Express.js?

    Without being exhaustive here are some useful middleware:

    • body-parser: To parse HTTP request body.
    • compression: Compresses HTTP responses.
    • cookie-parser: Parse cookie header.
    • cookie-session: Establish cookie-based sessions.
    • cors: Enable Cross-Origin Resource Sharing (CORS).
    • csrf: Protect from Cross-Site Request Forgery (CSRF) exploits.
    • errorhandler: Development error-handling/debugging.
    • morgan: HTTP request logger. Alternatives are winston and bunyan.
    • timeout: Set a timeout period for HTTP request processing.
    • helmet: Helps secure your apps by setting various HTTP headers.
    • passport: Authentication using OAuth, OpenID and many others.
    • express-async-handler: For Async/await support. An alternative is @awaitjs/express.
    • express-cluster: Run express on multiple processes.
  • As a beginner, how can I get started with Express.js?
     image
    Folder structure created by express-generator. Source: Express 2018c.

    A beginner should first learn the basics of JavaScript, Node.js and Express.js, in that order. Express website has useful tutorials. The routing guide is a good place to start. For in-depth understanding, or as a handy reference, use the API Reference.

    Install Node.js first. Then install Express.js: npm install express --save

    Since Express is unopinionated, your folder structure can be anything that suits your project. However, express-generator is a package that gives beginners a basic structure to start with. This installs the express command-line tool, which can be used to initialize your app. You get to choose your preferred templating engine (pug, ejs, handlebars) and styling support (less, stylus, compass, sass).

  • Where is Express.js not a suitable framework?

    Express is not recommended for large projects.

    Although Express is lightweight, for performance-critical apps such as highly scalable REST API services, prefer to use specialized Node frameworks such as fastify, restana, restify, koa, or polka.

  • What are some best practices when using Express.js?

    Adopt a modular structure to make your code more manageable.

    In production, log requests and API calls but minimize debug logs. A package such as debug might help in configuring the logging contexts. Pipe logs from console.log() or console.error() to another program since saving them to file or printing to console make the calls synchronous.

    In general, avoid synchronous calls. Use Node's command-line flag --trace-sync-io (during development only) to be warned when synchronous calls happen.

    For performance, use compression middleware. For security, use helmet. To run multiple instances on multicore systems, launch your app on a cluster of processes. The cluster can be frontended with a load balancer, which can be a reverse proxy such as Nginx or HAProxy.

    Handle errors using try-catch or promises. Don't listen for uncaughtException event to handle errors. This might be a way to prevent your app from crashing but a better way is to use a process manager (StrongLoop Process Manager, PM2, Forever) to restart the app automatically.

Sample Code

  • // -------------------------------------------------
    // Source: https://github.com/expressjs/express
    // Accessed: 2019-02-27
    // Simple Hello World example
     
    var express = require('express');
    var app = express();
     
    app.get('/', function (req, res) {
      res.send('Hello World')
    });
     
    app.listen(3000);
     
     
    // -------------------------------------------------
    // Source: https://expressjs.com/en/guide/routing.html
    // Accessed: 2019-03-01
    // Example of a chain of route handlers
     
    app.get('/example/b', function (req, res, next) {
      console.log('the response will be sent by the next function ...');
      next();
    }, function (req, res) {
      res.send('Hello from B!');
    });
     
    // Call multiple callbacks (assume cb0, cb1, cb2 are defined functions)
    app.get('/example/c', [cb0, cb1, cb2]);
     
     
    // -------------------------------------------------
    // Source: https://hackernoon.com/middleware-the-core-of-node-js-apps-ab01fee39200
    // Accessed: 2019-02-27
    // An example where we call handler only if user authentication is okay
    function userMiddleware (req, res, next) {
      getUserViaJWT(req.headers.authentication)
      .then(function(user) {
        req.user = user;
        next();
      })
      .catch(function (error) {
        res.status(401).end(); // replace with proper error handling
      });
    }
     
    app.use(userMiddleware);
     
    app.get('/someroute', handler);
     
     
    // Add middleware at the application level
    // They will be executed in that order: A, B
    app.use(middlewareA);
    app.use(middlewareB);
     
     
    // An alternative syntax to chain middlewares
    app.get('/', [middlewareC, middlewareD], handler);
     
     
    // Call middleware only for a particular URL path
    app.get('/data/:id', [dbMiddleware], handler);

References

  1. Agarwal, Rachit. 2014. "Why use ExpressJS over NodeJS for Server-Side Development?" Blog, Algoworks, August 22. Accessed 2019-02-27.
  2. Agoi, Abel. 2017. "A Simple Explanation Of Express Middleware." Medium, December 06. Accessed 2019-02-27.
  3. Brown, Duncan. 2016. "Node.js Foundation Acquires Express Framework From IBM—for Free!" DZone, February 15. Accessed 2019-02-27.
  4. Chauhan, Shailendra. 2015. "Brief history of node.js and io.js." DotNetTricks, December 31. Accessed 2018-10-27.
  5. Express. 2018a. "Frameworks built on Express." Express, November 06. Accessed 2019-02-27.
  6. Express. 2018b. "Express middleware." Express, November 04. Accessed 2019-02-27.
  7. Express. 2018c. "Express application generator." Express, August 10. Accessed 2019-02-27.
  8. Express. 2018d. "Production best practices: performance and reliability." Express, July 09. Accessed 2019-02-27.
  9. Express. 2018e. "Writing middleware for use in Express apps." Express, November 05. Accessed 2019-02-27.
  10. Express. 2019. "Using middleware." Express, January 12. Accessed 2019-02-27.
  11. Express GitHub. 2018. "expressjs/express." Express GitHub, October 11. Accessed 2019-02-27.
  12. Express Issues. 2016. "is express dying?" Issue #2844. Opened January 10. Accessed 2019-02-27.
  13. Flipboard GitHub. 2017. "Flipboard/express-cluster." GitHub, September 06. Accessed 2019-02-27.
  14. Grewe, Lynne. 2019. "Express: Middleware." CS6320: SW Engineering of Web Based Systems, Cal State East Bay. Accessed 2019-02-27.
  15. Harter, Marc. 2014. "Writing Modular Node.js Projects for Express and Beyond." StrongLoop, October 21. Accessed 2019-02-27.
  16. Holowaychuk, TJ. 2014. "StrongLoop & Express." Medium, July 30. Accessed 2019-02-27.
  17. JSConf. 2009. "The Speakers of 2009." The European JavaScript Conference, JSConf Berlin, November 7 & 8. Accessed 2018-10-27.
  18. Joyent. 2015. "Joyent Moves to Establish Node.js Foundation." Press Room, Joyent, February 10. Accessed 2018-10-27.
  19. Karpov, Valeri. 2013. "The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js." Blog, MongoDB, April 30. Accessed 2019-02-27.
  20. Karpov, Valeri. 2018. "Introducing Awaitjs-Express: Async Function Support for Express." The Code Barbarian, August 31. Accessed 2019-02-27.
  21. Kharchenko, Nataliia. 2017. "How to Choose the Best Node.js Framework: Express.js vs Koa.js vs Sails.js." Upwork, August 18. Updated 2018-09-25. Accessed 2019-02-27.
  22. MDN Web Docs. 2019. "Express Tutorial Part 7: Deploying to production." MDN Web Docs, Mozilla, February 17. Accessed 2019-02-27.
  23. Maso, Rolando Santamaria. 2018. "NO, you most probably don’t need Express in your Node.js REST API." Medium, June 10. Accessed 2019-02-27.
  24. Nemeth, Gergely. 2018. "History of Node.js on a Timeline." Blog, RisingStack, March 21. Accessed 2018-10-27.
  25. Node GitHub. 2018. "node-v0.x-archive: Releases." Accessed 2018-10-27.
  26. Ramel, David. 2016. "Express Web Server Advances in Node.js Ecosystem." ADTmag, February 11. Accessed 2019-02-27.
  27. Schlueter, Isaac. 2009. "Preview: npm, the node package manager." nodejs, Google Groups, October 01. Accessed 2018-10-27.
  28. Terdoslavich, William. 2015. "IBM Acquires StrongLoop, Boosting Node.js Support." InformationWeek, September 11. Accessed 2019-02-27.
  29. Turing School. 2019. "Introduction to Express JS." Module 3, Lessons, Front-End Engineering Program, Turing School of Software and Design. Accessed 2019-02-27.
  30. Tzur, Dor. 2016. "The Unbelievable History of the Express JavaScript Framework." The Full Stack, March 21. Accessed 2019-02-27.
  31. Yang, Chuoxian. 2016. "Express, Koa, Meteor, Sails.js: Four Frameworks Of The Apocalypse." TopTal, May. Accessed 2019-02-27.
  32. edWisor. 2018. "MEAN Stack Development: The Ideal Choice for Full-stack Developers." edWisor, on Medium, March 09. Accessed 2019-02-27.

Milestones

2009

Ryan Dahl and others at Joyent develop Node.js with initial support for only Linux. The name Node is coined in March. Being open source, version 0.1.0 is released on GitHub in May. In November, Ryan Dahl presents Node.js at JSConf in Berlin.

Nov
2010

As a web development framework based on Node.js, v1.0.0 of Express.js is released. The development of Express can be traced to January 2010 when v0.1.0 was committed on GitHub.

2011

To manage packages for Node.js, Node Package Manager (NPM) is released. An early preview of NPM can be traced to 2009, by Isaac Z. Schlueter.

Apr
2013

Valeri Karpov at MongoDB proposes a full-stack solution that he terms the MEAN stack: MongoDB, Express, Angular and Node. Given that three of these are based on JavaScript, this promotes the demand for full-stack developers who can handle both frontend and backend code.

Jul
2014

StrongLoop acquires commercial rights to Express. StrongLoop itself offers an open source API framework called LoopBack on top of Node and Express. Some community folks criticize this "sponsorship" or "sale" of what was an open source project.

Feb
2015

Joyent, IBM, Microsoft, PayPal, Fidelity, SAP and The Linux Foundation come together to establish Node.js Foundation.

Sep
2015

IBM acquires StrongLoop, a company that specializes in Node.js, Express.js and API management. StrongLoop is said to offer "robust implementation, making Node.js enterprise-grade". This acquisition could mean better adoption of Node and Express in the corporate world.

Feb
2016

Doug Wilson, one of the main contributors to Express, decides to stop working on Express. This is mainly because what was once an open source project is now controlled by IBM/StrongLoop. Express community also state their unhappiness with the way the framework is managed. Meanwhile, in a move towards open governance, Express is handed over to Node.js Foundation as an incubation project.

Oct
2018

Version 4.16.4 of Express is released. The same month version 5.0.0-alpha.7 is released. Version 5.0.0-alpha.1 can be traced back to November 2014.

Tags

See Also

  • MEAN Stack
  • Node Package Manager
  • Asynchronous Programming
  • Node.js Frameworks
  • Middleware
  • Express.js Deployment

Further Reading

  1. Berg, Leander. 2017. "Middleware: THE core of node.js backend apps." Hacker Noon, via Medium, March 26. Accessed 2019-02-27.
  2. Binariks. 2017. "Express.js Mobile App Development: Pros and Cons for Developers." Binariks, November 17. Accessed 2019-02-27.
  3. Tsonev, Krasimir. 2013. "Build a Complete MVC Website With ExpressJS." Code Envato Tuts+, August 15. Accessed 2019-02-27.
  4. Liew, Zell. 2016. "Building a Simple CRUD Application with Express and MongoDB." Zell Blog, January 22. Accessed 2019-02-27.
  5. Karpov, Valeri. 2013. "The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js." Blog, MongoDB, April 30. Accessed 2019-02-27.

Article Stats

Author-wise Stats for Article Edits

Author
No. of Edits
No. of Chats
DevCoins
3
0
964
1382
Words
0
Chats
3
Edits
2
Likes
409
Hits

Cite As

Devopedia. 2019. "Express.js." Version 3, March 1. Accessed 2019-05-24. https://devopedia.org/express-js