Search code examples
reactjscreate-react-appreact-scripts

Proxying Multiple API requests with Create React App with React-Scripts version 3.4.1


I am currently using the older version of React Script version 1.5.1. I want to upgrade my react app(react-scripts v 3.4.1) but in doing so I break the proxy structure defined in my package.json.

My current JSON has

"proxy": {
  "/ossapi": {
    "target": "http://localhost:8002"
  },
  "/pcp": {
    "target": "http://test.corp.test.com:8004"
  },
  "/ossOps": {
    "target": "http://test.corp.test.com:8085"
  },
  "/ems": {
    "target": "http://test.corp.test.com:8001"
  }
}

I want a similar setup for my app even after I upgrade to new React-scripts version 3.4.1 as I have done lots of development and don't want to restart from scratch again. when I change the react-scripts version to the latest stable 3.4.1, it keeps on throwing failed to parse json error.

Please advise.

The following is the error I get:

npm ERR! code EJSONPARSE
npm ERR! file /Users/dhrumit.sheth/Documents/Dev/stash/console-app/package.json
npm ERR! JSON.parse Failed to parse json
npm ERR! JSON.parse Unexpected token } in JSON at position 1438 while parsing near '...git push --tags",
npm ERR! JSON.parse   },
npm ERR! JSON.parse "proxy": [
npm ERR! JSON.parse   "/os...'
npm ERR! JSON.parse Failed to parse package.json data.
npm ERR! JSON.parse package.json must be actual JSON, not just JavaScript.

Solution

  • "proxy" in package.json works for single endpoint I believe. For more advanced configuration you need to create setpProxy.js file in project root folder, install http-proxy-middleware and put your configurations there. Code will look like this.

    module.exports = function(app) {
      app.use(
        '/ossapi',
        createProxyMiddleware({
          target: 'http://localhost:8002',
          changeOrigin: true,
        })
      );
      app.use(
        '/pcp',
        createProxyMiddleware({
          target: 'http://test.corp.test.com:8004',
          changeOrigin: true,
        })
      );
    };
    

    And rest same. documentation here.