Express.js
- Summary
-
Discussion
- Why should I use Express.js when there's already Node.js?
- Could you explain the concept of middleware in Express.js?
- What are the different types of Express.js middleware?
- What are some useful or recommended middleware for Express.js?
- As a beginner, how can I get started with Express.js?
- Where is Express.js not a suitable framework?
- What are some best practices when using Express.js?
- Milestones
- Sample Code
- References
- Further Reading
- Article Stats
- Cite As
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.
Discussion
-
Why should I use Express.js when there's already Node.js? 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? 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? 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 isfunction (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
andexpress.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.
- Application-level: These are bound to an instance of the application object
-
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? 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()
orconsole.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.
Milestones
2010
2013
2014
2015
2015
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.
Sample Code
References
- Agarwal, Rachit. 2014. "Why use ExpressJS over NodeJS for Server-Side Development?" Blog, Algoworks, August 22. Accessed 2019-02-27.
- Agoi, Abel. 2017. "A Simple Explanation Of Express Middleware." Medium, December 06. Accessed 2019-02-27.
- Brown, Duncan. 2016. "Node.js Foundation Acquires Express Framework From IBM—for Free!" DZone, February 15. Accessed 2019-02-27.
- Chauhan, Shailendra. 2015. "Brief history of node.js and io.js." DotNetTricks, December 31. Accessed 2018-10-27.
- Express. 2018a. "Frameworks built on Express." Express, November 06. Accessed 2019-02-27.
- Express. 2018b. "Express middleware." Express, November 04. Accessed 2019-02-27.
- Express. 2018c. "Express application generator." Express, August 10. Accessed 2019-02-27.
- Express. 2018d. "Production best practices: performance and reliability." Express, July 09. Accessed 2019-02-27.
- Express. 2018e. "Writing middleware for use in Express apps." Express, November 05. Accessed 2019-02-27.
- Express. 2019. "Using middleware." Express, January 12. Accessed 2019-02-27.
- Express GitHub. 2018. "expressjs/express." Express GitHub, October 11. Accessed 2019-02-27.
- Express Issues. 2016. "is express dying?" Issue #2844. Opened January 10. Accessed 2019-02-27.
- Flipboard GitHub. 2017. "Flipboard/express-cluster." GitHub, September 06. Accessed 2019-02-27.
- Grewe, Lynne. 2019. "Express: Middleware." CS6320: SW Engineering of Web Based Systems, Cal State East Bay. Accessed 2019-02-27.
- Harter, Marc. 2014. "Writing Modular Node.js Projects for Express and Beyond." StrongLoop, October 21. Accessed 2019-02-27.
- Holowaychuk, TJ. 2014. "StrongLoop & Express." Medium, July 30. Accessed 2019-02-27.
- JSConf. 2009. "The Speakers of 2009." The European JavaScript Conference, JSConf Berlin, November 7 & 8. Accessed 2018-10-27.
- Joyent. 2015. "Joyent Moves to Establish Node.js Foundation." Press Room, Joyent, February 10. Accessed 2018-10-27.
- Karpov, Valeri. 2013. "The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js." Blog, MongoDB, April 30. Accessed 2019-02-27.
- Karpov, Valeri. 2018. "Introducing Awaitjs-Express: Async Function Support for Express." The Code Barbarian, August 31. Accessed 2019-02-27.
- 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.
- MDN Web Docs. 2019. "Express Tutorial Part 7: Deploying to production." MDN Web Docs, Mozilla, February 17. Accessed 2019-02-27.
- 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.
- Nemeth, Gergely. 2018. "History of Node.js on a Timeline." Blog, RisingStack, March 21. Accessed 2018-10-27.
- Node GitHub. 2018. "node-v0.x-archive: Releases." Accessed 2018-10-27.
- Ramel, David. 2016. "Express Web Server Advances in Node.js Ecosystem." ADTmag, February 11. Accessed 2019-02-27.
- Schlueter, Isaac. 2009. "Preview: npm, the node package manager." nodejs, Google Groups, October 01. Accessed 2018-10-27.
- Terdoslavich, William. 2015. "IBM Acquires StrongLoop, Boosting Node.js Support." InformationWeek, September 11. Accessed 2019-02-27.
- Turing School. 2019. "Introduction to Express JS." Module 3, Lessons, Front-End Engineering Program, Turing School of Software and Design. Accessed 2019-02-27.
- Tzur, Dor. 2016. "The Unbelievable History of the Express JavaScript Framework." The Full Stack, March 21. Accessed 2019-02-27.
- Yang, Chuoxian. 2016. "Express, Koa, Meteor, Sails.js: Four Frameworks Of The Apocalypse." TopTal, May. Accessed 2019-02-27.
- edWisor. 2018. "MEAN Stack Development: The Ideal Choice for Full-stack Developers." edWisor, on Medium, March 09. Accessed 2019-02-27.
Further Reading
- Berg, Leander. 2017. "Middleware: THE core of node.js backend apps." Hacker Noon, via Medium, March 26. Accessed 2019-02-27.
- Binariks. 2017. "Express.js Mobile App Development: Pros and Cons for Developers." Binariks, November 17. Accessed 2019-02-27.
- Tsonev, Krasimir. 2013. "Build a Complete MVC Website With ExpressJS." Code Envato Tuts+, August 15. Accessed 2019-02-27.
- Liew, Zell. 2016. "Building a Simple CRUD Application with Express and MongoDB." Zell Blog, January 22. Accessed 2019-02-27.
- Karpov, Valeri. 2013. "The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js." Blog, MongoDB, April 30. Accessed 2019-02-27.