I’m working on a couple of applications:
- A single page react app
- and a JSON API built using node express and mysql
When testing things locally, I use webpack dev-sever to serve the react app which makes network requests to the express app that is running on a separate port on my local computer.
Now I want to host the 2 apps on a AWS EC2 instance that has mysql + apache already installed.
I started by creating an apache vhost to serve the react front-end and that’s working fine. Then I uploaded the express app and started the server on port 3000. The react app makes request to the express app like this http://localhost:3000/api, however the requests resolve to the server in my local computer instead of the EC2 server. If I turn off my local server then the requests will fail.
In my mind, I don’t need to create a public endpoint to my express application because the requests made by the react app will be local to the server that is hosting the 2 apps, is this correct? Is it possible to tell the react app to call my express app without having to expose my API?
2
Answers
Your React SPA is meant to be executed on the visitor’s browser (the client), and send requests to your (publicly available) server.
During development, you serve your React Front-end with
webpack-dev-server
, which is meant only for this local development phase: it helps for live build and hot reload. But for production, you build plain static HTML/JS/CSS asset files, which are (most usually) hosted as-is so that your visitor’s browser can download them and execute them client-side.Within this client code (your React SPA), the URL to the API server must be hard-coded:
localhost
to send requests to a server on the same machine as the browser (that is what you experience)If you want to prevent requests from unidentified clients (i.e. not originating from your React SPA), the usual method involves authentication, or at least a form of API token. Obviously you can also implement other forms of protections, typically checking the origin and IP address (assuming you know where your visitors connect from). If your API must be really secrete, you can hide it in a private network and have your users connect through VPN for example.
You need to make the API calls using the public domain name of the API because the react application will be accessed publicly from any browser. You can only test the APIs on EC2 using localhost.