Cookies Psst! Do you accept cookies?

We use cookies to enhance and personalise your experience.
Please accept our cookies. Checkout our Cookie Policy for more information.

Handling 404 Error in SPA Deployed on GitHub Pages

If you deployed a SPA - Single Page Application - with Github pages. It may work well when you open your app from the root path, which is /.

But you will see the 404 error page when you open the other path even though it should be handled by the router library you use, in my case, the React Router library.

It is because once you open the root path, the javascript code of the app is downloaded on your web browser and when the location is changed, it will be handled by javascript code, which means it does not request a file to the server.

However, if you start by opening the other root, which is not '/', it throws the 404 error as it couldn't find an HTML file corresponding to the route you entered. You will see only one HTML file in the deployed directory, index.html.

dist

If you build a React app using Vite, the built files will be located in the dist directory like the image.

Then, how could we show our app to display the 404 page?
We can solve this problem by simply creating the 404.html file under the root directory.
The 404.html file located in the root directory will be sent when users open the app with a non-root path, which is not '/'.

  "scripts": {
    "dev": "vite --host 0.0.0.0",
    "build": "tsc && vite build --mode production && cp ./dist/index.html ./dist/404.html",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "test": "vitest run",
    "test:coverage": "vitest run --coverage",
    "test:watch": "vitest"
  },

I added the copy command after the build command.

Note: The script may be different if you're working with a framework other than React with Vite. The point is to create the 404.html file under the build folder by copying your main file.

tsc && vite build --mode production && cp ./dist/index.html ./dist/404.html

Then you will see the 404.html file is created by copying the index.html file.
Your build directory may look like this.

dist directory with the 404.html file

Now, let's start the app with a non-root path.

handled 404 page

It didn't find the file corresponding to the path and sent the 404.html file located in the root directory, which we created by copying the index.html.

As a result, all the path is handled by our javascript code. The only problem is that it responds with the status code 404.

I hope you found it helpful!
Happy Coding!

Last Stories

What's your thoughts?

Please Register or Login to your account to be able to submit your comment.