Dave Stein
Dave Stein

Reputation: 9326

Why would my express router middleware not have req.route defined?

I am trying to use router middleware to get the value of req.route. I have some simple code like this:

server.js

import api from './api';
// ...
app.use('/api/', api);

api/index.js

Object.keys(routes).forEach(key => {
  router.use(function(req, res, next) {
    console.log('++++++++++++++++++');
    console.log(req.route);
    console.log('++++++++++++++++++');

    next();
  });
  // so localhost:8080/api/currentkey works
  router.use(`/${key}`, routes[key]);
});

When I hit /api/currentkey, req.route is undefined. If I move the middleware after the route definition (instead of before), it doesn't seem to fire at all.

My router objects are all setup using a method like this:

import express from 'express';
import asyncify from 'express-asyncify';

export default function() {
  return asyncify(express.Router());
}

I saw a solution using events on Get route definition in middleware, but am wondering why that is required vs what I have done here. I'm also not sure the way it's written would make things accurate (such as changing a transaction name for new relic)

Upvotes: 3

Views: 1761

Answers (3)

Francesco Virga
Francesco Virga

Reputation: 316

Was having the same issue. Found that you can use app.all and will always have access to req.route this way.

Upvotes: 0

Shailesh Jha
Shailesh Jha

Reputation: 1202

You can do it like ::

It works perfectly in koa but not sure in express::

app.use(async (req, res, next)=> {
  // Do your work
  await next(); // This will work fine, wait for next route/middleware
});

app.get('/path', (req, res, next) => {
  res.send('hello');
  next() 
})

Upvotes: -1

1565986223
1565986223

Reputation: 6718

That's right. req.route is available only in your final route. From the docs:

Contains the currently-matched route, a string

Note the words in bold, Your middleware where you're logging req.route is not a route.

So it would be available to say:

app.get('/path', (req, res) => {
  console.log(req.route);
})

Since, req object is mutated while passing around middleware, you can access req.route for the last matched route. For example:

app.get('/path', (req, res, next) => {
  res.send('hello');
  next() // <-- calling next middleware
})

// middleware mounted after the above route
app.use((req, res, next) => {
  console.log(req.route) // outputs the last matched at /path route
})

Upvotes: 3

Related Questions