# Express.js

## Summary


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 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?

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. 

## 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.