CRA 2.0 How to setup proxy in React?
Asked Answered
B

1

9

In CRA 2.0 proxy property on the package.json does not work. After some research, I came across an article suggesting to use http-proxy-middleware. I created an setupProxy.js in the src of my client folder(React side). That contains the following code

const proxy = require("http-proxy-middleware");
module.exports = function(app) {
  console.log("Setup proxy is ever called");
  app.use(proxy("/api/auth/google", { target: "http://localhost:5000/" }));
};

What am I supposed to do after this. Where should I import the setupProxy.js file. From where it is gonna receive app.

Buckinghamshire answered 24/11, 2018 at 6:51 Comment(0)
P
11

The proxy value in package.json does still work in CRA 2, but it now only accepts a string, more complicated proxy options have to be put in src/setupProxy.js as you are doing. But be careful, if you leave the proxy property in package.json CRA will use that and ignore your setupProxy.js file.

You don't need to import setupProxy.js anywhere, CRA will find it as long as it's in src.

Don't worry about where app comes from, that variable will be provided at runtime.

Your example will work, I've tried it (as long as you remove the old proxy string from package.json). But the console.log will not be logged to the terminal (I'm not sure why).

Further reading, the PR where this change was introduced: https://github.com/facebook/create-react-app/pull/5073

Pellicle answered 28/11, 2018 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.