Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing an user in a single page application using the adress bar

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.

like image 267
lilezek Avatar asked Oct 25 '25 08:10

lilezek


1 Answers

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!

like image 158
William Martins Avatar answered Oct 26 '25 22:10

William Martins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!