Opposing Corners: How Create React App and Java Spring Security can talk through a Proxy
When you start Create React App, it creates and runs code in memory. It’s not until you run yarn build that it creates the static assets folder and writes the files to disk.
The react app will be running from a node server in your browser at localhost:3000. If you need to talk to a Java server running on a different port like localhost:9080 that has also spring security enabled, how can one open the ports and make requests between front and backend?
When you’re ready to go to production, you no longer require the node server and everything can live within Java. This is the only time when a final bundle should be necessary. In our app, my bundle takes a minute or so to compile and then I use gulp to move the entire static folder into the java app under webapp > main. It would really bog down development if I had to compile it each time to test the API.
The first thing you have to do is log into your application from localhost:9080. This is only part that requires being on 9080 to set the session cookie. Once you’ve authenticated, you will be able to hit the API urls. You can test one by dropping it your address bar and see the json results. Better yet, install json view in your Chrome to get pretty results.
The Java app will need to enable Cors. Our app is Java 7 and we easily found a cors solution and that’s beyond the scope of this piece.
I played around a bit with a python proxy then looked a php proxy — finally looked at the create-react-app readme and discovered this note about a proxy!
Once your package.json has the proxy added, restart your react app and it should now be able to hit your Java API as along as you’re authenticated. Then, after you’ve completed a feature against the authenticated API, you can run yarn build to create the static assets. I included a gulp command to the build which simply copies the static folder into the Java project. Then I’ll commit and push the entire project to Git which our Java dev will pull and build the war file that now contains the new React UI to deploy to the cloud.
Ideally, I would prefer to run my frontend code from a node/express server that can talk to other backends whether it be Java, Python, or Firebase. But if you work for a company that restricts to you only a Java server, then hopefully this article can help you continue to use Create React App to build your glorious frontend and reap the benefits of HMR and Babel.