Skip to content

How to get route name of parent route? #2879

@watson

Description

@watson

Goal

For each incoming request I'd like to log the name of the route that matches the request. So given the request GET /users/42 which matches the app.use('/users/:id', ...) route handler I'd like to get the name /users/:id.

Partial solution

I originally used the route property on the request object to extract the route name:

// given a request to `/users/42`, the routeName below would be `/users/:id`
var routeName = req.route.path || req.route.regexp && req.route.regexp.source

Problem

But the above solution doesn't work for nested routes, e.g:

// create sub-app
var admin = express.Router()
admin.get('/users/:id', require('./admin/user'))

// create main app
var app = express()
app.get('/users/:id', require('./user'))
app.use('/a(dmin)?', admin) // mount sub-app under "/admin" and "/a"

When mounting a route like in the above example, the req.route.path property will not contain the parent route. So if someone requests GET /admin/users/42 then req.route.path would just contain /users/:id and not /a(dmin)?/users/:id.

Is there any way inside a route handler to figure out that this was routed through a parent route with the name /a(dmin)??

I first thought to use req.baseUrl, but that will give me the "resolved" path, so I'd get either /a or /admin depending on which actual URL the user typed - I'd like to get the generic route name instead: /a(dmin)?

If this is not possible at all in v4, it would be cool if this could be supported in v5 😃

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions