expressjs / expressjs/express

Feature request: Add a custom event `render` (due `req.route` & routing middleware nature)

Open
#2,474 7 comments 0 reactions 0 assignees View on GitHub
discuss ideas
Dominant language
JavaScript
Stars
69.5k
Forks
25k
Avg merge
4d 20h
Merged PRs (30d)
9

Description

**Related links**

https://github.com/strongloop/express/issues/2093
http://stackoverflow.com/a/19460598/881286

A practical and real application of `req.route` would be one that you have
- a dynamic route like `/user/:id`
- a navbar and want to activate an item depending on the route (adding a CSS class),

At the view, it would be nice to do a conditional on a route definition instead of the actual url path.

To acomplish that right now it is needed to add a local variable in each route middleware definition, whis is a cumbersome task:

``` js
router.route('/users/:id').get(function (req, res) {
res.locals.route = req.route;
res.render('users', {});
});
```

**Real deal**

A nice way to overcome this would be having a general middleware that do it in a single place, but the issue is that `req.route` only gets filled when the routing middleware gets executed, so there is no way to code a separated middleware that gets executed AFTER `req.route` is defined and BEFORE the `render` method.

**Conclusion**

If an Expressjs custom event existed, that gets executed just after the `render` method gets executed, it could be used to overcome this issue:

``` js
app.use(function (req, res, next) {
res.on('render', function(){
res.locals.route = req.route;
});
next();
});
```

Thanks

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.