Moving to Express 4

Overview

Express 4 is a breaking change from Express 3. That means an existing Express 3 app will not work if you update the Express version in its dependencies.

This article covers:

Changes in Express 4

There are several significant changes in Express 4:

See also:

Changes to Express core and middleware system

Express 4 no longer depends on Connect, and removes all built-in middleware from its core, except for the express.static function. This means that Express is now an independent routing and middleware web framework, and Express versioning and releases are not affected by middleware updates.

Without built-in middleware, you must explicitly add all the middleware that is required to run your app. Simply follow these steps:

  1. Install the module: npm install --save <module-name>
  2. In your app, require the module: require('module-name')
  3. Use the module according to its documentation: app.use( ... )

The following table lists Express 3 middleware and their counterparts in Express 4.

Express 3Express 4
express.bodyParser body-parser + multer
express.compress compression
express.cookieSession cookie-session
express.cookieParser cookie-parser
express.logger morgan
express.session express-session
express.favicon serve-favicon
express.responseTime response-time
express.errorHandler errorhandler
express.methodOverride method-override
express.timeout connect-timeout
express.vhost vhost
express.csrf csurf
express.directory serve-index
express.static serve-static

Here is the complete list of Express 4 middleware.

In most cases, you can simply replace the old version 3 middleware with its Express 4 counterpart. For details, see the module documentation in GitHub.

app.use accepts parameters

In version 4 you can use a variable parameter to define the path where middleware functions are loaded, then read the value of the parameter from the route handler. For example:

```js app.use(‘/book/:id’, (req, res, next) => { console.log(‘ID:’, req.params.id) next() })

Edit this page