3
votes

I have a backend using express to serve a static directory, to the path /, in which is contained a single page frontend. This backend also serves an API REST.

The frontend is built in React, and uses react-router to route the user from the different views of the web application.

If my react-router have two entries, let say /app and /config,

how can I redirect the client to that view of the application, if the user enters directly the URL in the web browser's address bar?

Right now, if I do that, Express gets the request and obviously returns a 404 message, as the single page is served to / path.

1

1 Answers

2
votes

A simple way to resolve that is to always (even on 404s) send to user the index.html in your express route handlers.

See: https://stackoverflow.com/a/25499007/2624575

However, you need to take care of some things:

1) Your React Router code should start to handle 404s: https://stackoverflow.com/a/37491381/2624575

2) You need to handle correctly the path to your assets (icons, css, js, etc), otherwise you'll send the same index.html to those kind of resources (which will make your page render incorrectly)

3) Make sure that react-router is using browserHistory (the history that doesn't use hashes #), This way React will be able to render your routes correctly

Hope it helps!