Andrey Kon Andrey Kon - 1 month ago 7
Node.js Question

How can I obtain matched route pattern in express JS?

I want my logger middleware to log each matched route when response is sent. But there may be any number of nested subroutes. Let's suppose I have this:

var app = express();
var router = express.Router();

app.use(function myLogger(req, res, next)
{
res.send = function()
{
//Here I want to get matched route like this: '/router/smth/:id'
//How can I do this?
});
}

app.use('/router', router);

router.get('/smth/:id', function(req, res, next)
{
res.send(response);
});


Is it possible?

Answer

Because app level middleware had no knowledge of routes, this is impossible. However, if you use your logger middleware as route middleware like:

router.get('/smith/:id', logger, function (req, res) { ... });

You can use a combination of two parameters on the request object:

req.route.path => '/smth/:id'
req.originalurl => '/router/smth/123'

I'll leave it up to you how you want to combine both into one string.