DEV Community

George K.
George K.

Posted on • Updated on

Publishing front-end app with React Router on Surge

Surge is a great platform offering easy publishing for the web clients, it's free, allows custom subdomains and has great CLI tools.

One issue you might find though is that when trying ti publish a project with react router the routes are not working if hit directly form the url.

After building an optimised build version with npm run build and publishing the build folder with surge command the homepage is displayed with no problems and if you have a navigation with routes it works as well.

But as soon as you want to go directly to a specific url, let's say you have "About us" page with /about route the server gives back 404 error since naturally a file about.html doesn't exist.

Here is an example of published simple client with navigation and the router. A you can see, clicking the nav items is working, bu if you try to go directly to let's say https://react-router-with-dynamic-route.surge.sh/about we can see a lovely 404.

In the same way any attempts to share any url different from home will send user to 404.

There is an easy fix though -- simply make a copy of index.html in the build folder and name it 200.html. After that publish on Surge normally and the problem would be fixed, your router is working properly.

Here is a working version. Now here we can go directly to any route like http://react-router-with-dynamic-route-with-fix.surge.sh/about and it will work just fine.

Being said that here is the list of step-by-step terminal command to publish your client project with router successfully. From the root folder of you project do:

npm run build
cd build
cp index.html 200.html
surge
Enter fullscreen mode Exit fullscreen mode

Success!

Top comments (0)