loading...

Error when serving React app from sub-folder

sudiukil profile image Quentin Sonrel ・1 min read

Hello there!

I'm trying to serve a React application from a sub-folder. It's currently a very simple SPA running on the root URL (e.g. http://myserver:3000) and I'd like to serve it from a sub-folder (e.g. http://myserver:3000/newroot).

I've spent the day trying many things, most of them revolving around the use of a "homepage" variable in my package.json:

{
  "name": "cra_test",
  "version": "0.1.0",
  "private": true,
  "homepage": "/newroot",
...

I've found many people (and docs) reporting this as a (part of a) solution but when I do so and rebuild then rerun my app (npm run build and serve -s build) it yields nothing but a blank page with the following error in the browser console:

screenshot

Pardon the literal french on the first two warnings, it reads:

The script at [...] was loaded while it's MIME type (text/html) isn't a valid JavaScript MIME type

These two errors exclusively appear when I use "homepage" in my package.json. For testing purposes, I've reproduced all those steps on a freshly created (with create-react-app) app, the issue is the same, so it's most likely not due to coding errors.

After hours of trial and error, I'm basically clueless as to how to solve this.

I'd be grateful for any insight on the issue or for any alternative solution to the initial problem (serving the app from a sub-folder), thanks in advance!

Discussion

pic
Editor guide
Collapse
jbutz profile image
Jason Butz

I was able to replicate your issue. The problem is serve. When you run serve -s build it starts the HTTP server. When you go to http://localhost:5000 in your browser it sends an HTTP request for / to serve. It will respond with ./build/index.html, which references assets from /newroot/static/..... But, there is no newroot directory inside your build directory. So it responds with ./build/index.html due to the -s flag.

If you rename the build directory to newroot and run serve . then you will be able to load your application at localhost:5000/newroot but navigation may not work correctly depending on what you are doing.

If you are trying to test the production deployment of your application you should do so in a production-like environment, not locally.

Collapse
anpos231 profile image
anpos231

Keep in mind that "homepage" is only used in production build.
Development still serves the app from "localhost:3000/"

Collapse
sudiukil profile image
Quentin Sonrel Author

Sure but as you can see in my post I'm serving the app in production mode. And this is where the error happens, nothing changes in dev mode.