create-react-app npm run build command

Paulos3000 picture Paulos3000 · Sep 30, 2016 · Viewed 52.9k times · Source

I have a built a small React application with create-react-app, and it runs fine from the local server after running npm start. OK so far.

However, when I run npm run build, the process appears to execute correctly (creates build folder, which contains the bundled js file and the index.html file), but when I open index.html in my browser it renders nothing. What am I missing?


Aside: I also tried uploading it to a remote server and when I went to the URL the browser came back with...

Forbidden: You don't have permission to access / on this server.

...if anyone has any idea how to resolve this I'd also appreciate it.

Answer

Dan Abramov picture Dan Abramov · Sep 30, 2016

However, when I run npm run build, the process appears to execute correctly (creates build folder, which contains the bundled js file and the html.index file), but when I open index.html in my browser it renders nothing. What am I missing?

When you run npm run build, it prints the relevant instructions:

enter image description here

You can’t just open index.html because it is supposed to be served with a static file server.
This is because most React apps use client-side routing, and you can’t do that with file:// URLs.

In production, you can use Nginx, Apache, Node (e.g. Express), or any other server to serve static assets. Just make sure that if you use client-side routing, you serve index.html for any unknown request, like /*, and not just for /.

In development, you can use pushstate-server for this. It works with client-side routing well. This is exactly what the printed instructions suggest you to do.

I also tried uploading it to a remote server and when I went to the URL the browser came back with Forbidden: You don't have permission to access / on this server.

You need to upload the contents of the build folder, not the build folder itself. Otherwise the server can’t find your index.html because it is inside build/index.html, and so it fails. If your server doesn’t detect a top-level index.html, please refer to your server’s documentation on configuring files served by default.