page doesn't load on refresh - react-router-dom

The reason why http://localhost:1234/#/profile works is because # doesn't reload the page. It behaves the same as an anchor tag in HTML where you stay on the same page but scroll to a specific section of it. For example, the below scrolls you to the portfolio section of the page.

<a href="www.page.com/#portfolio">Portfolio</a>

If you omit the #, this is different. This tells your server to reload the page and visit that location. In your case http://localhost:1234/profile is unknown by the server as you have not specified it on the server side. In these cases, you need to either create the route or proxy the request when the route is not found.

As you are using react-router which is a client-side router, the same file needs to be served by the server and therefore you should go with the proxy option.

When using http-server the docs say you can add the -P or --proxy flag to specify it.

-P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com

In your case update the below in your package.json.

"open": "concurrently \"http-server -a localhost -p 1234 -P http://localhost:1234\" \"open http://localhost:1234\""

An alternative is to use webpack-dev-server for development. It'll improve your developers experience a lot as it supports hot reloading when a component changes.

install it using npm install --save-dev webpack-dev-server

Add the below to your webpack config.

devServer: {
  contentBase: __dirname + '/dist',
  compress: false,
  port: 1234,
  historyApiFallback: {
    index: 'index.html' // assuming this is your entry point file that loads your bundle.
  }
},

Then in your package.json add a script for it and run it using npm run watch

"watch": "webpack-dev-server --hot --progress --mode development",

NOTE: Make sure that in your dist folder index.html is present. If it isn't you will run into issues.

I've created a basic project on GitHub so you have a working example.