Set up proxy to work with multiple APIs in create react app

Node v8.12.0, create-react-app v2.1.5

Pavan
2 min readJan 11, 2019

Create react app is a wonderful utility to quickly start a react project. You don’t need to worry about Webpack configurations as create-react-app (also popularly known as CRA) gives most of the things out of the box. Web app generated with CRA runs on localhost:3000 by default. It gives you everything you needed to start your development. If your web app is trying to consume any API running on different host and port, you will get CORS (Cross Origin Resource Sharing) error in browser.

CORS error is only thrown by browser so to get rid of this error, we make call to our local server and server will forward the call to API server. Now since the API call has been made by server not the browser, browser won’t report any error. Create-react-app has out of the box configuration to handle this. We only need to make proxy entry in package.json and everything starts working.

Handle single api in package.json

package.json works perfectly if your web app is consuming one API server. But there could be case when your web application has to interact with multiple API servers which are hosted at different domains. In that case, create-react-app has a different way to make everything work. To handle multiple API, we need to install a NPM package “http-proxy-middleware” as dev dependency, create a file with name setupProxy.js and keep it in src folder. Then put following code in setupProxy.js

Handle multiple api in CRA setupProxy.js file

Above code means that if your are making call to /api/ then call will forward to http://api.xyz.com/api/ end point. Whatever key you specify in app.use method, the call will be forwarded to <domain>/<key>/<rest_path>.

--

--