AAAAAAAAAAAAAAAAAAAAA

We pray to code / Est. 2015

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 nom 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 http://like-pig.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://callous-toad.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

Success!

Back to posts