How to check in ExpressJS server if request path is nonexistent (404) or not?

32 views Asked by At

We get requests from random bots crawling over the internet from time to time spamming requests with random paths and we want to filter out 404 requests being logged on our server. Problem is, some of our request handlers intentionally set the response's status code to 404 when the parameters lead to a nonexistent resource even if the path exists, making it impossible for us to use the status codes as an indicator if the request's path is nonexistent in our middlewares. Is there a way to check if a request's path is indeed nonexistent without relying on the status code of the response?

app.use(
  morgan('combine', {
    skip(req, res) {
      if (res.statusCode == 404) return true; // any alternatives to this?
      if (res.statusCode < 400) return true;
      return false;
    }
  })
)
1

There are 1 answers

0
nermineslimane On

One alternative approach to filter out 404 requests without relying on the response's status code could be to use a separate middleware that checks if the requested path exists in your application.

app.use((req, res, next) => {
// match the path to your router
  const pathMatch = app._router.stack.find(layer => layer.regexp.test(req.path));
  if (pathMatch) {
    // If the requested path exists, continue with the request handling
    next();
  } else {
    // If the requested path does not exists
  }
});