DEV Community

Cover image for 🛠️ How to fix Laravel 10 + Inertia + ReactJS getting 404 error page on browser refresh 🌐
Don Buddhi
Don Buddhi

Posted on • Updated on

🛠️ How to fix Laravel 10 + Inertia + ReactJS getting 404 error page on browser refresh 🌐

Inertia with Laravel is quite popular these days.

Therefore, I also tried to setup a fresh Laravel 10 installation + Inertia along with ReactJS.

Everything went well until I tried to refresh the page with browser refresh rather click on the links on the page.

error page screenshot

I got this 404 page.

Root cause

When I was digging into the issue realized that it caused by Laravel's default configuration for handling client-side routing.

Upon refreshing the page, the server attempts to locate a suitable route for the URL. However, since the URL now corresponds to a client-side route, the server encounters a 404 error indicating that the requested resource cannot be found.

Solution

To resolve this issue, it was necessary to configure Laravel in a way that it consistently returns the same view for any client-side route. This can be achieved by introducing a catch-all route to your web.php file.

Route::get('/{any}', function () {
return view('app');
})->where('any', '.*');

The purpose of this route is to handle any URL and render the "app" view, which serves as the container for your Inertia app. By implementing this route, you ensure that whenever the user refreshes the page, Laravel consistently displays the same view. From that point onwards, your client-side routing takes control.

And it needs to be ensure that you place this route after all your other routes in order to capture only those URLs that do not match any other existing route.

adding fix to the routes file

Additionally, it is essential to eliminate the "public" segment from your URL. You can accomplish this by configuring your web server to direct to the "public" directory of your Laravel project or by utilizing Laravel Valet or Homestead.

If you're using an Apache server, you can add the following code to the '.htaccess' file.

htaccess file

After implementing these modifications, your URLs will resemble the following format:

Moreover, after making these adjustments, refreshing the page should no longer lead to a 404 error.

Top comments (0)