Skip to content

How to detect whether a request will be handled by a route later in the stack? #5066

Answered by ViniciusMarchi
markcellus asked this question in Q&A
Discussion options

You must be logged in to vote

Hi. I don't know if there are better ways to do this, but here's one that might help you. You can iterate over app._router.stack property. This property stores a list of all routes registered in your app. Here is a example:

const express = require('express')
const app = express();

app.use((req, res, next) => {
  let hasRouteToHandle = false;
  app._router.stack.forEach((stackItem) => {
    // check if current rout path matches route request path
    if (stackItem.route?.path === req.path) {
      hasRouteToHandle = true;
    }
  });


  if (hasRouteToHandle) {
    console.log('Request will be handled by a route later in the stack')
  } else {
    // No matching route for this request
    c…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@markcellus
Comment options

@ViniciusMarchi
Comment options

@markcellus
Comment options

Answer selected by markcellus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants