0

I have a react site serving over: https://aero.mysite.com/profile, and I use router and history.push/replace in my react app, making it possible to have pathname such as https://aero.mysite.com/profile/path?query=number. However, say if someone copy and paste this url to another person, he or she would get 404 because https://aero.mysite.com/profile/path doesn't actually exist over the static server... (I am using koa + file serving middleware I made). What are the solutions to this challenge?

Aero Wang
  • 8,382
  • 14
  • 63
  • 99
  • 1
    Try using `HashRouter`. You will need to change your routing scheme to fix the issue with this https://reacttraining.com/react-router/web/api/HashRouter – UjinT34 Mar 20 '19 at 15:32
  • I don't want to use hashrouter because it is adding unwanted hash to my routes. I am looking for the server side solution for this challenge. – Aero Wang Mar 21 '19 at 03:01
  • Related: https://stackoverflow.com/questions/55670845/how-to-use-react-router-browserrouter-in-a-static-index-html-file – Mostafa Farzán Aug 10 '21 at 17:35

1 Answers1

2

If you are using BrowserRouter or something similar, replace it with hash router which adds a "#" between the web server path and frontend route

Browser router looks like this http://example.com/about

while the hash router looks like this http://example.com/#/about

This will prevent the UI routing from being processed by the web server

For more info read this article

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

import App from './components/App';
import Home from './components/Home';
import About from './components/About';
import Services from './components/Services';

render((
  <Router>
    <div>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/courses" component={Services} />
    </div>
  </Router>
), document.getElementById('root'));
Akshay R
  • 166
  • 1
  • 6
  • I don't want to use hashrouter because it is adding unwanted hash to my routes. I am looking for the server side solution for this challenge. – Aero Wang Mar 21 '19 at 03:02
  • In that case, try using next.js. It's the server side rendering solution for React. You can use "Link" component from "next/link" to handle server side routing. – Akshay R Mar 21 '19 at 04:14