How To Properly Serve The Create-react-app Index From The Server?
Solution 1:
When you run npm start
, you are telling CRA to make a development build using webpack. Webpack does all of the processing you see like injecting scripts and replacing %PUBLIC_URL%
. You don't want your backend to serve the index.html
in the public
folder because that file hasn't been processed by webpack. Instead you need the backend to serve webpack's build output.
The npm start
configuration is a development build, which is good for development but not production. (Also it doesn't save its output to the file system, so you couldn't even serve it from your backend if you wanted to. See CRA issue #1070). If you run npm run build
, you get a production build in the build
folder, which you should serve from your backend (and then you can make whatever injections you need).
The downside of this is that it takes longer to build, it doesn't rebuild automatically when you change your frontend files, and I'm not sure if the errors it gives are as useful as npm start
. Thus you might want to use npm start
when developing the frontend and npm run build
when testing your backend. There are also certain projects like patch-package that would allow you to make npm start
's build output stay in the file system so you can serve it, but I haven't tried any of them.
BTW - be careful with injecting scripts into the html from your backend. Consider something like setting cookies in your backend and reading those cookies in your frontend instead. This is safer, easier to debug, etc.
Post a Comment for "How To Properly Serve The Create-react-app Index From The Server?"