Today I Learned

hashrocket A Hashrocket project

Proxy Development Requests with Create-React-App

Create-React-App supports an optional proxy option in development, which can be added to your package.json. In my case, I was dealing with CORS issues locally because our frontend and backend run on the same server in production, but our development setup is different.

My backend was running on http://localhost:4000, and frontend on http://localhost:3000.

In my package.json, I specified that I wanted to proxy my requests to backend development server:

{
  ...
  "proxy": "http:localhost:4000"
  ...
}

Then I changed my fetch call to be a relative URL:

// Was fetch("http://localhost:4000/api/graph", ...params)
fetch("/api/graphql")

Create-react-app will recognize that this path is not a static asset and "will proxy the request (http://localhost:4000/api/graphql) as a fallback".

Create-React-App Docs - Proxying API Requests in Development

See More #react TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.