ValRob
ValRob

Reputation: 2682

Empty page with react router in github pages. Package.json home or .env PUBLIC_URL

The problem: When i go to any internal root, and press f5, it broke, givin 404. Like for example: https://josuevalrob.github.io/jeval-web/sign-in. But if I go to the root it works fine: https://josuevalrob.github.io/jeval-web

I don't know how to solve this problem. There is a bunch of documentation about this, and I cant handle it.

This is the github repo: https://github.com/josuevalrob/jeval-web

This is the github Page: https://josuevalrob.github.io/jeval-web

And you can see, the package json have the home key:

  "homepage": "https://josuevalrob.github.io/jeval-web",

Also the .env is currently empty, but i can add this:

PUBLIC_URL = "https://josuevalrob.github.io/jeval-web"

Nevertheless, it doesn't work.

I had added the homepage or the public_url, neither work.

Upvotes: 0

Views: 254

Answers (2)

Radisav Savkovic
Radisav Savkovic

Reputation: 23

I had a similar issue with react app. I fixed it by using HashRouter instead of BrowserRouter in App component

Upvotes: 0

Charlie Martin
Charlie Martin

Reputation: 8406

Github pages doesn't really support single page applications. Single page applications require a server that serves the same page at every url and then the client renders the appropriate content based on the url. Hence the "single page". Github does not allow you to run server side code, so you can't write a server to serve your index.html at every route.

There is, however, a hack you can use to make this work. When you navigate to a route other than the root url, Github will serve a 404 page as you can see. Github allows you to customize this 404 page. So, you can make the custom 404 page your single page application and then it will be served at every route as required.

This repo explains the required steps to serve your single page as a custom 404 page on Github pages.

Basically it amounts to...

  1. Copy this 404.html page to your repo as is
  2. Add this redirect script to your index.html page

The only drawback is that the url is forced to redirect and quickly flashes the incorrect URL before redirecting. You can see an example of this by refreshing this page. If you want to avoid this, you need to look for hosting somewhere else that allows you to edit server side code and serve your index.html at every route

Upvotes: 1

Related Questions