tic30
tic30

Reputation: 49

GitHub Page homepage subdomain throws 404

I deployed a React app to Github Page as homepage.

The problem is I cannot access /home or any subdomain directly, neither can I refresh the page on it. It throws 404. But redirecting inside the app works if you wait util the animation is finished on landing page, you can get to /home.

I checked, there is no other repository of mine which is registered under /home.

Can someone tell me why? And how should I solve this issue?

Update: The React, router is configured:

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Preloader from './components/Preloader';
import Home from './components/Home';
import './App.scss';

class App extends Component {
    render() {
        return (
            <Router>
                <React.Fragment>
                    <Switch>
                        <Route path="/" exact component={Preloader} />
                        <Route path="/home" component={Home} />
                    </Switch>
                </React.Fragment>
            </Router>
        );
    }
}

export default App;

Upvotes: 1

Views: 801

Answers (1)

mancristiana
mancristiana

Reputation: 2125

Solution 1

As demonstrated in this article Deploying A Create React App with Routing to Github Pages you should use a HashRouter to avoid getting a 404 error on your GitHub page when refreshing the page.

According to HashRouter documentation:

HashRouter

Router that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.

IMPORTANT NOTE: Hash history does not support location.key or location.state. In previous versions we attempted to shim the behavior but there were edge-cases we couldn’t solve. Any code or plugin that needs this behavior won’t work. As this technique is only intended to support legacy browsers, we encourage you to configure your server to work with instead.

Try updating your import statement with:

import { HashRouter as Router, Switch, Route } from "react-router-dom";

Solution 2

A better solution could be to configure your server to properly handle routing. Check out this guide showing how you could use express for this:

const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()

// serve static assets normally
app.use(express.static(__dirname + '/public'))

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})

app.listen(port)
console.log("server started on port " + port)

Upvotes: 2

Related Questions