How to get req.route.path in express middleware?

Viewed 92

I want to get the path(/entity/:view/:ver/) in the express middleware.

1 Answers

req.route is only present after express handles the request.
You can either access it in route-specific middleware, or if you need to access it globally and don't mind only having it after the request has been processed, you can wrap your code in res.on('finish'...

Example:

const loggingContextMiddleware: RequestHandler = (req, res, next) => {
  res.on('finish', () => {
    req.route // Is now present, and should contain what you need.
  });
  return next();
};
Related