Proxy API Requests in Create React App

I've been working with Create React App ever since it was first released. I found it to be a straightforward means of scaffolding a React app without the pains of digging into the configuration of Webpack, eslint, Jest and other commonly used tools.

I've been working with Create React App ever since it was first released.  I found it to be a straightforward means of scaffolding a React app without the pains of digging into the configuration of Webpack, eslint, Jest and other commonly used tools.  In the past I would copy-paste those configurations as part of initial commit, which meant carrying a lot of dated baggage from project to project.  But now, I could run npx create-react-app my-app and be off to the races.  Plus, there was the added luxury of npm run eject to eject the application and modify the internals.

A common issue I've run into across many projects is how to best manage API connections and configurations.  Sometimes the API has a unique hostname, in which case a environment variable is sufficient.  Other times I will load a small JSON object when the application binds that acts as and application config.  However, a recent configuration challenged my prior experience.

This application was using NGINX to serve the application bundle and acting as a proxy, reserving the path /api for forwarding requests from the UI to the API.  The setup is lightweight and serves our needs as we prototype.  We can write fetch('/api/data')  to make requests in production, but the local development environment does not support this.

Fortunately, Create React App has a proxy option for local development.  In the package.json add an entry `"proxy": "http://localhost:4000"`.  The proxy is CORS-enabled and will allow you to quickly integrate the API for local development without adding any headaches to your production deployments.