Alexander Mills
Alexander Mills

Reputation: 100010

Node.js Express middleware: app.param vs app.use

In the chain of calls inside Express middleware, do the app.param methods always get called before app.use?

Upvotes: 5

Views: 4726

Answers (2)

Peter Lyons
Peter Lyons

Reputation: 146014

I tested with this program changing the order of app.use vs app.param with express 4.10.2. The param always runs first, which makes sense because the route handler expects to be able to do req.params.foo and in order for that to work the param handlers need to have run.

var express = require('express');
var app = express();

app.use("/:file", function (req, res) {
  console.log("@bug route", req.params.file);
  res.send();
});

app.param("file", function (req, res, next, val) {
  console.log("@bug param", val);
  next();
});



app.listen(3003);

Run this and test with curl localhost:3003/foo and you get the output:

@bug param foo
@bug route foo

Upvotes: 5

Paul
Paul

Reputation: 36319

You can test it through logging, but I'm reasonably certain that in 4.0, everything is called in the order it's declared when you set up your app.

Upvotes: 2

Related Questions