1

I have a web server with routes such as:

router.get("/inicio", async (req, res) => {
  // logic ...
  return res.render("template");
}

and a route for everything else:

app.get("*", async (req, res) => {
  await authentication.getLocalInfo(req);
  return res.redirect("/404");
});

When I share my website on WhatsApp with `https://emocoes.org/inicio", the server logs the following requests in quick succession, with about 70 MB of text in the server logs for this near-infinite loop:

2022-03-06T10:26:16.176Z - //inicio 
2022-03-06T10:26:16.334Z - //inicio/404 
2022-03-06T10:26:16.492Z - //inicio/404/404 
2022-03-06T10:26:16.652Z - //inicio/404/404/404 
2022-03-06T10:26:16.801Z - //inicio/404/404/404/404 
2022-03-06T10:26:17.027Z - //inicio/404/404/404/404/404 
2022-03-06T10:26:17.191Z - //inicio/404/404/404/404/404/404 
2022-03-06T10:26:17.329Z - //inicio/404/404/404/404/404/404/404 
2022-03-06T10:26:17.520Z - //inicio/404/404/404/404/404/404/404/404 
2022-03-06T10:26:17.789Z - //inicio/404/404/404/404/404/404/404/404/404 
2022-03-06T10:26:17.955Z - //inicio/404/404/404/404/404/404/404/404/404/404 
2022-03-06T10:26:18.093Z - //inicio/404/404/404/404/404/404/404/404/404/404/404 
...

Another example: /diadopai should redirect to /registo but instead redirects to /diadopai/registo, which does not exist, and so on.

How can I make WhatsApp request the right route, or avoid this near-infinite loop?

miguelmorin
  • 5,025
  • 4
  • 29
  • 64
  • 1
    It looks like your second routes overwrite your first one, did you try to exclude /inicio ? [like this ?](https://stackoverflow.com/a/19315674/5391965) – Reynadan Mar 22 '22 at 17:02
  • I'm positive that the second catch-all route does not overwrite the first one, since that page renders on a normal browser. – miguelmorin Mar 23 '22 at 18:47
  • 1
    Have you tried `res.redirect("https://emocoes.org/404")` as a workaround? – BurningKarl Mar 25 '22 at 20:09

1 Answers1

4

Your redirects are not absolute, and are using the current path as the base. Try this instead:

return res.redirect(req.protocol + "://" + req.headers.host + "/404");

Also, you should create a route to handle /404 otherwise it will infinetly loop back on itself. This should display an error page etc and should not redirect anywhere new.

miguelmorin
  • 5,025
  • 4
  • 29
  • 64
Nick Lauder
  • 371
  • 2
  • 5
  • Nice way to solve this thorny issue, and it works. Can you say more about redirects not being absolute? I believe they are on browsers, since they start with a slash and they work for human users. – miguelmorin Mar 27 '22 at 08:29
  • 2
    Redirects not being absolute is just when `/404` just gets appended to the current URL. In order to determine the new path, you need to include the whole (absolute) path to redirect to, including protocol, domain, and new path. – Nick Lauder Mar 27 '22 at 10:26