Brendan Scarvell Brendan Scarvell - 1 year ago 100
Node.js Question

What is the parameter "next" used for in Express?

Suppose you have a simple block of code like this:

app.get('/', function(req, res){
res.send('Hello World');

This function has two parameters,
, which represent the request and response objects respectively.

On the other hand, there are other functions with a third parameter called
. For example, lets have a look at the following code:

app.get('/users/:id?', function(req, res, next){ // Why do we need next?
var id =;
if (id) {
// do something
} else {
next(); // What is this doing?

I can't understand what the point of
is or why its being used. In that example, if id doesn't exist, what is
actually doing?

Answer Source

It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id was given, and assign it to req.user.

Below, you could have a route like:

app.get('/users', function(req, res) {
  // check for and maybe do something with req.user

Since /users/123 will match the route in your example first, that will first check and find user 123; then /users can do something with the result of that.

Route middleware (note: link is to 2.x documentation, but this is tested as working on 3.x) is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users model with an async findOne():

function loadUser(req, res, next) {
  if (req.params.userId) {
    Users.findOne({ id: req.params.userId }, function(err, user) {
      if (err) {
        next(new Error("Couldn't find user: " + err));

      req.user = user;
  } else {

// ...

app.get('/user/:userId', loadUser, function(req, res) {
  // do something with req.user

app.get('/users/:userId?', loadUser, function(req, res) {
  // if req.user was set, it's because userId was specified (and we found the user).

// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {

Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:

 * Only allows the page to be accessed if the user is an admin.
 * Requires use of `loadUser` middleware.
function requireAdmin(req, res, next) {
  if (!req.user || !req.user.admin) {
    next(new Error("Permission denied."));


app.get('/top/secret', loadUser, requireAdmin, function(req, res) {

Hope this gave you some inspiration!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download