Proxy Errors with Create React App 2.0 & 3.0

Create React App 2.0 has changed how we will need to define our proxies. (This note and all steps and code contained also applies to the newly released v3.0)

To determine which version you are using, check your client side package.json:

Using CRA 2.0 or higher (x’s denote placeholder for minor release)

"react-scripts": "2.x.x",
"react-scripts": "3.x.x",

Using CRA 1.0:

"react-scripts": "1.x.x",

The error:

If using CRA 2.0 or 3.0, after making the changes in the upcoming lecture you will get the following error messages when starting the server:

[1] When specified, “proxy” in package.json must be a string.

[1] Instead, the type of “proxy” was “object”.

[1] Either remove “proxy” from package.json, or make it a string.

The fix:

1) In the client/ directory install this package:

npm install http-proxy-middleware –save

2) Create setupProxy.js file in client/src/ directory. There is no need to import this file anywhere, CRA looks for a file by this name and loads it.

3) Then add your proxies to the setupProxy.js file:

There are a few different ways to add proxies:

Method 1:

(Thanks to Torleif B. for finding this cleaner more efficient method)

const proxy = require('http-proxy-middleware')
module.exports = function(app) {
    app.use(proxy(['/api', '/auth/google'], { target: 'http://localhost:5000' }));

Method 2:

const proxy = require('http-proxy-middleware');
module.exports = function(app) {
    app.use(proxy('/auth/google', { target: 'http://localhost:5000' }));
    app.use(proxy('/api/**', { target: 'http://localhost:5000' }));

4) Remember to remove the old proxy scripts code from your client side package.json (or you will still get the same errors)

5) Restart start your servers with npm run dev and the proxies should now work as expected. Note – Anytime you make a change to the proxy or the Google Project’s URI or Origins settings you should restart the server.

Leave a Reply

Your email address will not be published. Required fields are marked *

sixteen − 8 =