Expressjs 4.x, Whats Changed and Whats New?

Expressjs has finally made a shift, with newer version (v 4.0) comes alot of good changes i would say. We will go through the new features breifly in this post so that you know what you need to change before you make the call to move to Express 4.0.

Major Changes


Expressjs 4.X doesn't have connect as a dependency, which means no ugly connect.multipart() ... warnings anymore.

But this also removes all of the middlewares (except the static middleware) that came with connect, for example the bodyParser middleware. Each one of them have been detached to be a module of their own, so that they can recieve constant fixes and get upgraded without being a hindrance in the expressjs release cycles.

Along with that, app.configure() and app.router() have also been removed. Routing has received an overhaul of a kind, giving developers an ability to modularize their app routes.

As app.configure has been removed, so anything that you need to do based on the environment will need to be done using if/else statements or some other module if its worth it.

New Things


Routing in Express 4.0

Routing has been changed completely, no more app.use(app.router). Instead we will need to directly place our routes at the place we use to write the above line of code. Routes will now be added in the order they have been placed.

app.get('/', users.get);
app.use('/users', users.list);
app.post('/users', users.new);
app.put('/users/:id', users.update);
app.use('/users/:id', users.getUser);   //app.use now supports :params

Now router in express 4.0 gives us a cool new way to define routes, lets see how in the code block below:

app.route('/users')
.get(function(req, res, next){})
.post(function(req, res, next){})
.put(function(req, res, next){})
.delete(function(req, res, next){})

Route instance also provides a shorthand method .all(), which handles all the HTTP verbs for the path provided. A route instance can also have middlewares specific to it, a route can also be a seperate module in itself. Lets see an example below:

//users.js in /routes/ directory
var users = express.Router();
users.use(function(){});
users.get('/', function(){});
-------
-------

module.exports.users = users;

//Now the above route instance can be used/mounted as below

app.user('/users', require('./routes/users.js').users);

Some other changes

  • req.params is now an object instead of being an array, though req['dasda'] will continue to work.
  • req.locals has been changed to object, previously being a function.
  • Will need to use res.set or res.type to set headers, a default charset will not be added.
  • Use express() instead of express.createServer() which i assume most of you are already doing as the later was deprecated long back.

So this was a complete quick look at the changes and new things that has become a part of expressjs 4.0. For more info have a look at offical wiki.

comments powered by Disqus