#2739·express

Question: Is there a way to identify a route and create href link to it?

Author: fourpixelsCreated Aug 21, 2015Updated Jul 25, 2026
Labelsideasmodule:router

Hi there, I'm using Express for what I imagine to be a large project, and I have many href links inside my views. I do not want to hardcode them at all! Any time I change something I must go and search in the code in order to make it work.

Short story: how can I track back a route, so I can use this in views:

<a href="{{ url('route_id') }} /> <!-- // as you don't mind what the template engine is -->

Long one: I've searched for a day about routing in Express and I found a few "reverse" routing packages, ALL of them quite broken - they either don't work with Router() or they create new Router every time, etc. I got to know all the Layers and stacks that the Routing part creates. I understand that you guys want order in routes, as well as multiple handlers for the same path. I agree with all that.

But isn't there some easy way to add ids for those routes? I found that if I simply use

app.use('/path', function namedFunction(req, res, next) {});

I get namedFunction as a name of the Layer in the stack, which is great. But if I use router (like router.route('/path').get(...).post(...), then the Layer is named router and inner stack contains anonymous functions.

My idea here was that after I add all routes, I can browse app._router and it's stacks, getting names of routes, then using a function with name parameter so I can construct back a route.

Am I missing something, or there is no way to make this easy working? I can't imagine someone having 100+ routes in a project, that hardcodes their links inside it - I just refuse to think of it :)