Skip to content

Middleware runs according to path not router #580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 17, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions _includes/api/en/4x/router-use.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,26 @@ app.use(express.static(__dirname + '/uploads'));

The `router.use()` method also supports named parameters so that your mount points
for other routers can benefit from preloading using named parameters.

__NOTE__: Although these middleware functions are added via a particular router, _when_
they run is defined by the path they are attached to (not the router). Therefore a piece
of middleware added via one router may run for routes of other routers if its routes
match. For example, if two different routers are mounted on the same path:

{% highlight js %}
var authRouter = express.Router();
var openRouter = express.Router();

authRouter.use(require('./authenticate').basic(usersdb));

authRouter.get('/:user_id/edit', function(req, res, next) { ... edit user ui ... });
openRouter.get('/', function(req, res, next) { ... list users ... })
openRouter.get('/:user_id', function(req, res, next) { ... view user ... })

app.use('/users', authRouter);
app.use('/users', openRouter);
{% endhighlight %}

Even though the authentication middleware was added via the `authRouter` it will run on the routes defined by the `openRouter` as well since both routers were mounted on `/users`.

If this behavior is not desired then the paths must be different for each router.