Search code examples
reactjsproxylocal-storagecreate-react-app

Serve react project on dev througth proxy


I've split my react application in 3 different projects, using CRA for all of them, auth, X and Y. User is first sent to auth, then I redirect him to either X or Y based on some info.

It works perfectly on PRODUCTION environment (because they run on the same domain), but on dev, X and Y failed to authenticate the user, because they run on different ports (different domains) the data in local storage is not shared between auth, X and Y.

I've tried to find a way to use a reverse proxy (http-proxy) to host the React dev servers on the same domain, but failed too, because the services could not find the assets/static folder, resulting in 404. Also tried http-proxy-middleware, as it is recommended on the CRA docs page, but failed to do so. Is there an easier way that I'm not seeing?

Edit: Found something new, but also failed. Used react-rewired to override CRA scripts, to use PUBLIC_PATH on DEV, but now my bundle.js returns an index.html file.

The following code does redirect to the accordingly react project, but the assets are requested to the wrong path.

const apiProxy = httpProxy.createProxyServer();


app.all("/login/*", function(req, res) {
    console.log('redirecting to Login');
    apiProxy.web(req, res, {target: servers.login});
});

app.all("/implementacao/*", function(req, res) {
    console.log('redirecting to Implementation');
    apiProxy.web(req, res, {target: servers.implementation});
});

So I used react-rewired to change the public path

const {
  override,
} = require('customize-cra');

module.exports = {
  webpack: override(
      (config) => {
        config.output.publicPath = '/login/';
        return config;
      },
  ),

  jest: config => {
    return config;
  },

  devServer: configFunction => (proxy, allowedHost) => {
    return configFunction(proxy, allowedHost);
  },

  paths: (paths, env) => {
    return paths;
  }
};

Now, the assets requests are made correctly to /login/, but nothing the dev server always return an index.html file.


Solution

  • Even with react-app-rewired, to override config, and use publicPath on dev, the assets will not be served from the publicPath.

    There is already a pull request on CRA to use PUBLIC_URL in dev mode.