0

How to implement routing in Quarkus if used with frontend frameworks like React, VueJS, Angular, etc?

For example, for any url "/xyz" the order of route evaluation should be:

  1. Static file named "xyz", if exists.
  2. Controller annotated with @Path("/xyz"), if exists.
  3. 404 -> serve "/index.html"
Suyash
  • 2,531
  • 2
  • 17
  • 29
  • 1
    Best practice for single page apps is to separate the SPA from the back-end, i.e. create a deployment artifact for the SPA consisting of the static files (Javascript, images, stylehssets etc.) and another artifact for the Quarkus backend (serving API requests only). – Codo Apr 06 '21 at 09:28
  • @Codo That's true, but if you want to use quarkus in a memory constrained environment like a raspberry pi then it doesn't make sense to run a separate service just for static files. It's better to do it in quarkus itself. – Suyash Apr 06 '21 at 10:10

1 Answers1

4

Quarkus already does 1 and 2 for you. For 3, you only need to implement a custom NotFoundExceptionMapper

@Provider
public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {
    @Override
    @Produces(MediaType.TEXT_HTML)
    public Response toResponse(NotFoundException exception) {
        InputStream resource = ClassLoader.getSystemResourceAsStream("META-INF/resources/index.html");
        return null == resource
                ? Response.status(NOT_FOUND).build()
                : Response.ok().entity(resource).build();
    }
}

Quarkus will use by order:

  1. File xyz, if exists in src/main/resources/META-INF/resources/
  2. Resource @Path("/xyz")
  3. Custom NotFoundExceptionMapper
Suyash
  • 2,531
  • 2
  • 17
  • 29
Edgar Domingues
  • 930
  • 1
  • 8
  • 17
  • This exception mapper will not work in quarkus dev mode because there is a built-in exception mapper which is preferred. See [this](https://stackoverflow.com/a/64517266/12034237) and this [bug report](https://github.com/quarkusio/quarkus/issues/7883) – Alex Jul 10 '22 at 11:14