expressjs / expressjs/express

Params registered on app available in routers used by app

Open
#2,151 34 comments 0 reactions 0 assignees View on GitHub
4.x enhancement
Dominant language
JavaScript
Stars
69.5k
Forks
25k
Avg merge
4d 20h
Merged PRs (30d)
9

Description

I discovered today that it seems params registered on `app` are not respected in routes registered via a router (`express.Router()`). Perhaps I'm just missing something though!

While sectioning an application's routes via routers is super handy, having to re-register shared params on each of them is not.

A use case to consider: an application that has a page which renders user details in which the view needs the user data, and in addition the app exposes an API to get the raw JSON response for use by a client-side app, mobile app, or third party.

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

// Shared Params

app.param('user', function (req, res, next, id) {
req.user = { id: id, name: 'Fred' };
next();
});

// Website

app.get('/users/:user', function (req, res) {
res.render('user', req.user);
});

// Application API (JSON Responses)

var APIRouter = express.Router();

router.get('/users/:user', function (req, res) {
res.json(req.user); // req.user is undefined!
});

app.use('/api', APIRouter);

// App Start

app.listen(8000);
```

Seems that shared params across application "sections" when using routers would be a very common scenario.

---

Maybe this is going too far, but it'd make sense that any param registered on a parent router applied to its children, but possibly not visa-versa:

``` javascript
var parent = express.Router();
var child = express.Router();

parent.param('foo', function (req, res, next) {
req.foo = { ... };
next();
});

child.param('bar', function (req, res, next) {
req.bar = { ... };
next();
});

parent.get('/:foo/:bar', function (req, res) {
res.json({
foo: req.foo, // OK!
bar: req.bar // undefined
});
});

child.get('/:foo/:bar', function (req, res) {
res.json({
foo: req.foo, // OK!
bar: req.bar // OK!
});
});

parent.use(child);
```

Thoughts/advice appreciated!

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.