Moving to Express 4
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:
An example of migrating an Express 3 app to Express 4.
Changes in Express 4
There are several significant changes in Express 4:
Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
- Changes to the routing system.
- Various other changes.
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:
- Install the module:
npm install --save <module-name>
- In your app, require the module:
require('module-name')
- Use the module according to its documentation:
app.use( ... )
The following table lists Express 3 middleware and their counterparts in Express 4.
Express 3 | Express 4 |
---|---|
express.bodyParser | |
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:
The routing system
Apps now implicitly load routing middleware, so you no longer have to
worry about the order in which middleware is loaded with respect to
the router
middleware.
The way you define routes is unchanged, but the routing system has two new features to help organize your routes:
- A new method,
app.route()
, to create chainable route handlers for a route path. - A new class,
express.Router
, to create modular mountable route handlers.
app.route()
method
The new app.route()
method enables you to create chainable route handlers
for a route path. Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more
information about routes, see Router()
documentation.
Here is an example of chained route handlers that are defined by using the app.route()
function.
express.Router
class
The other feature that helps to organize routes is a new class,
express.Router
, that you can use to create modular mountable
route handlers. A Router
instance is a complete middleware and
routing system; for this reason it is often referred to as a “mini-app”.
The following example creates a router as a module, loads middleware in it, defines some routes, and mounts it on a path on the main app.
For example, create a router file named birds.js
in the app directory,
with the following content:
Then, load the router module in the app:
The app will now be able to handle requests to the /birds
and
/birds/about
paths, and will call the timeLog
middleware that is specific to the route.
Other changes
The following table lists other small but important changes in Express 4:
Object | Description |
---|---|
Node.js | Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
http.createServer() | The |
app.configure() | The |
json spaces | The |
req.accepted() | Use |
res.location() | No longer resolves relative URLs. |
req.params | Was an array; now an object. |
res.locals | Was a function; now an object. |
res.headerSent | Changed to res.headersSent . |
app.route | Now available as app.mountpath . |
res.on('header') | Removed. |
res.charset | Removed. |
res.setHeader('Set-Cookie', val) | Functionality is now limited to setting the basic cookie value. Use
|
Example app migration
Here is an example of migrating an Express 3 application to Express 4.
The files of interest are app.js
and package.json
.
Version 3 app
app.js
Consider an Express v.3 application with the following app.js
file:
package.json
The accompanying version 3 package.json
file might look
something like this:
Process
Begin the migration process by installing the required middleware for the Express 4 app and updating Express and Pug to their respective latest version with the following command:
Make the following changes to app.js
:
-
The built-in Express middleware functions
express.favicon
,express.logger
,express.methodOverride
,express.session
,express.bodyParser
andexpress.errorHandler
are no longer available on theexpress
object. You must install their alternatives manually and load them in the app. -
You no longer need to load the
app.router
function. It is not a valid Express 4 app object, so remove theapp.use(app.router);
code. -
Make sure that the middleware functions are loaded in the correct order - load
errorHandler
after loading the app routes.
Version 4 app
package.json
Running the above npm
command will update package.json
as follows:
app.js
Then, remove invalid code, load the required middleware, and make other
changes as necessary. The app.js
file will look like this:
Run the app
The migration process is complete, and the app is now an Express 4 app. To confirm, start the app by using the following command:
Load http://localhost:3000 and see the home page being rendered by Express 4.
Upgrading to the Express 4 app generator
The command-line tool to generate an Express app is still
express
, but to upgrade to the new version, you must uninstall
the Express 3 app generator and then install the new
express-generator
.
Installing
If you already have the Express 3 app generator installed on your system, you must uninstall it:
Depending on how your file and directory privileges are configured,
you might need to run this command with sudo
.
Now install the new generator:
Depending on how your file and directory privileges are configured,
you might need to run this command with sudo
.
Now the express
command on your system is updated to the
Express 4 generator.
Changes to the app generator
Command options and use largely remain the same, with the following exceptions:
- Removed the
--sessions
option. - Removed the
--jshtml
option. - Added the
--hogan
option to support Hogan.js.
Example
Execute the following command to create an Express 4 app:
If you look at the contents of the app4/app.js
file, you will notice
that all the middleware functions (except express.static
) that are required for
the app are loaded as independent modules, and the router
middleware
is no longer explicitly loaded in the app.
You will also notice that the app.js
file is now a Node.js module, in contrast to the standalone app that was generated by the old generator.
After installing the dependencies, start the app by using the following command:
If you look at the npm start
script in the package.json
file,
you will notice that the actual command that starts the app is
node ./bin/www
, which used to be node app.js
in Express 3.
Because the app.js
file that was generated by the Express 4 generator
is now a Node.js module, it can no longer be started independently as an app
(unless you modify the code). The module must be loaded in a Node.js file
and started via the Node.js file. The Node.js file is ./bin/www
in this case.
Neither the bin
directory nor the extensionless www
file is mandatory for creating an Express app or starting the app. They are
just suggestions made by the generator, so feel free to modify them to suit your
needs.
To get rid of the www
directory and keep things the “Express 3 way”,
delete the line that says module.exports = app;
at the end of the
app.js
file, then paste the following code in its place:
Ensure that you load the debug
module at the top of the app.js
file by using the following code:
Next, change "start": "node ./bin/www"
in the package.json
file to "start": "node app.js"
.
You have now moved the functionality of ./bin/www
back to
app.js
. This change is not recommended, but the exercise helps you
to understand how the ./bin/www
file works, and why the app.js
file
no longer starts on its own.