Anvil routes redirect to a custom 404 page

What I’m trying to do:
Make my own app 404 page when a user puts in an invalid route.

What I’ve tried and what’s not working:
added a function with @anvil.server.route("*") and @anvil.server.route("/*") to the server code and when I went to paths that would trigger a 404 response, I didn’t get the content I returned. I only got the anvil 404 endpoint not found error.

My guess is that the correct answer is part of Meredydd’s Watch this space.

I haven’t seen the star syntax in the documentation and examples.
Have you tried with something like:

@anvil.server.route("/:x")
@anvil.server.route("/:x/:y")
@anvil.server.route("/:x/:y/:z")
def four_o_four(email, **p):
    return anvil.server.HttpResponse(404, "Oopsie")

Mmmh…
Now I’m wondering what happens if you have two conflicting routes?

2 Likes

Oooh, I didn’t think about stacking route decorators, that’s a good stop gap. though I really hope that something else is in the pipeline.

I just got the star syntax trying to match the way some JS routers handle it.

Whichever path is on top is checked first:
so if this is defined first

@anvil.server.route("/:first")
@anvil.server.route("/:first/:second")
@anvil.server.route("/:first/:second/:third")
@anvil.server.route("/:first/:second/:third/:fourth")
def test(**kwargs):
  return kwargs

and then this is defined

@anvil.server.route("/form1")
def form1():
    return anvil.server.FormResponse("Form1")

the form1 path never gets hit, but rather hits on the /:first default.

But if form1 is defined first, the exact match is hit correctly and then fallbacks hit otherwise.

tl;Dr: put the most exact match on top and most generic/fallbacks on bottom.

2 Likes

… and put all the route decorators in one module.

If you really want to sprinkle them across multiple modules, here is an unofficial trick to control the order modules are imported: In what order are server modules imported? - #2 by stefano.menci

1 Like

Oh absolutely, I can’t even imagine trying to handle routes across multiple files just for sanity’s sake. And it’s pretty much cross-language standard to do so anyways – or at least in react.