3

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.

lilezek
  • 6,976
  • 1
  • 27
  • 45

1 Answers1

2

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!

William Martins
  • 1,969
  • 1
  • 18
  • 22
  • So, just to clarify: Do I have to get rid of express static serving, and check at the frontend the path of the request? – lilezek Aug 30 '17 at 19:51
  • @lilezek you still need to have express static serving (because all your assets need to be served by express). You just need to add a rule to always serve `index.html`, even on 404s. You problem now is that express is treating "/app" and "/config" as 404s, but you needed `index.html` instead. Do you understand? – William Martins Aug 30 '17 at 19:54
  • Yes, I understood that part but, do react-router will route the user to the application view from the address bar after giving the `index.html`? Do I have to do something additionally in the frontend? – lilezek Aug 30 '17 at 19:57
  • Sure! Once it has loaded your javascript, `React Router` will look to your url (in this case, `/app` and `/config`) and will check if your routes match the given url. If it matches, it will render your route. Just make sure you're using `browserHistory` (updated my answer with that). – William Martins Aug 30 '17 at 20:03