Search code examples
reactjshateoas

How should a React app (or any SPA) interact with a HATEOAS back-end?


The basic question is if there should be one HATEOAS entry point per page or one entry point for the entire app?

Most examples I have seen implement a single page with a HATEOAS backend, e.g. a list that is paginated using prev and next links. But what happens when the app navigates to a different page that has completely different capabilities and needs a different entry point? How does one organize such an app?

Concrete example: We have an app with tab navigation. The home tab shows a product catalog so the entry point is /products which returns page 1 of products along with pagination links. However, now I click on the orders tab which must show a list of past orders. This page needs a completely different entry point /orders which the home tab knows nothing about. In fact, user can directly navigate to the orders tab using a deep link.

How to think about this problem? Are there any examples illustrating an approach?


Solution

  • There's a few different ways to solve this. Here's two:

    1. The SPA takes context from the uri (such as an id), and uses it to search on the API. The API can describe templated links/actions to search for resources by their id.
    2. Instead of doing client-side routing, let the server decide what to render.

    We're going more towards #2. If we have a uri such as:

    https://spa.example/https://api.example/foo/bar
    

    We take the path part of this uri and hit the API. Based on what the API responds with, we decide what to render. This means that most of the routing for these kinds of endpoints is delegated to the server, which feels more in line with HATEOAS.

    The path part in this case is an entire absolute URI, but we also support relative uris and have a default base uri. So in practice these two uris are equivalent (for our SPA):

    https://spa.example/https://api.example/foo/bar
    https://spa.example/foo/bar
    

    We develop & use ketting / react-ketting to do most of the heavy lifting