1

I have a Single Page Application that uses React-Router and is served via Go backend. The pre-built static app is accessible at app.com which then uses app.com/api to load dynamic data.

If a user goes to app.com and clicks the /widget link everything works fine. However, because the routes all use browser-based routing, if a user tries to go directly to app.com/widget the Go backend doesn't have anything to serve since it knows nothing about the app itself and gives a 404 response. It only knows/cares about the static files to serve and the api.

My simple solution is that the server sets a cookie redirect=/widget for any route that should be there and then redirects to the index route where the app checks for a redirect value and sends to the user to that page if it's present. Circular but works.

The issue with this approach is that I don't want to manually add each new route the app uses to both the frontend and backend which leads me to this question.

My thought is to save all of the routes externally in a yaml or json file like:

routes:
  - url: "/"
    component: App
    redirect: false

  - url: "/widget"
    component: Widget
    redirect: true

The frontend app would import the file during the build and setup the routes/components accordingly while the backend would import it, check which had redirect set to true, and use a factory function to create handlers for redirection to each of those paths. A couple potential benefits seem like they would be easier configuration of the app routes at high-level and the ability to separate which widgets are accessible directly and which need to go through the main page/login but I feel like there may be negatives I'm not thinking of

General thoughts on this approach? I've tried searching for other similar solutions or best practices but feel like I'm missing the right terminology to even find anything and can't tell if I'm reinventing the wheel

1 Answer 1

2

You can use the anchor portion of the URL to hold client side routes, e.g. app.com/#/widget. This may or may not be an easy change to make.

The alternative is to return the same HTML document when going to app.com/widget as you would going to app.com. Then JavaScript can read the path portion of the URL and route accordingly. Basically this means a 404 Not Found from the server returns a web page that attempts to route the request client side using JavaScript. This also means JavaScript needs to handle URLs like app.com/non/existent/path and display a friendly 404 screen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.