Lets try the new Express 4.0 version

Express is a well-known library for building simple web applications. Also express is a really modular library you can easily add other modules and middlewares to make your life easier. With the new version, the structure is more modular and the core of the code is split into multiple modules.

Getting started, as you remember the old express version had express generator built-in which is now separated to `express-generator` module. To generate application boilerplate:

npm install -g express-generator
mkdir express4
cd express4
express
npm i

Now the express should be installed with the dependencies of other libraries. The server start is hidden in `bin/www` file, run it and open browser localhost:3000. The browser page should look like this:

2014-04-10-215445_542x263_scrot 

The changes that 4.0 bring are more like structural, all the previously included middlewares are now separated modules:

The use of the middleware is same with app.use, so the setup looks like this:

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Routes setup
app.use('/', routes);
app.use('/users', users);

The greatest change is the Router support, which allows to create sub-routes with separated middleware stack. Read more about the router usage in Express guide router. For example, in the project you have created users routes, which contains separate router instance with authentication middleware which is applied only for this router.

var express = require('express');
var router = express.Router();

router.use(function authenticationMiddleware (req, res, next) {

    if (new Date().getSeconds() % 2) {
        return next();
    }

    next(new Error('User not allowed to page'));
});

/* GET users listing. */
router.get('/', function(req, res) {
  res.send('respond with a resource');
});

module.exports = router;

If you are using the old version of express 3.5 and want to upgrade to express 4, make sure you have look through all the middleware changes. There are a lot of middlewares which might not be compatible with the new session middleware. But in overall there is not any big changes that breaks the compatibility and upgrading to newer version should be easy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s