giorgiogalassi76
giorgiogalassi76

Reputation: 21

react import environment in setupProxy.js of http-proxy-middleware generate unexpected identifier

I need to set the target of proxy http-proxy-middleware in react using a variable obtained by craco. I have followed this guide to have more configuration file for different environments. I have 3 files local.js, development.js, and production.js that are selected by craco using different npm run startlocal, startdevelopment.

In package.json I have:

 "scripts": {
        "startlocal": "cross-env CLIENT_ENV=local craco start",
        "startdevelopment": "cross-env CLIENT_ENV=development craco start",
        "startproduction": "cross-env CLIENT_ENV=production craco start",

The problem is I want to change proxy in function of what environment I am and so using http-proxy-middleware I have used setupProxy.js as stated by guide. If I insert import environment from 'environment'; in setupProxy.js I have the error unexpected identifier.

This is the code of setupProxy.js:

 import environment from 'environment';
    const proxy = require('http-proxy-middleware');

    module.exports = function(app) {
      app.use(proxy('/api', { target: 'http://localhost:5000/' }));
    };

    this my craco.config.js

    const path = require('path');    

    module.exports = function({ env, paths }) {    
      return {    
        webpack: {   
          alias: {    
            environment: path.join(__dirname, 'src', 'environments',     process.env.CLIENT_ENV)    
          }    
        },    
      };    
    };     

Console output by npm run startlocal

Unexpected identifier
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] startlocal: cross-env CLIENT_ENV=local craco start
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] startlocal script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I suppose that the problem is linked to the fact that setupProxy.js is auto loaded and is loaded before craco.config.js so it doesn't have that import.

Upvotes: 2

Views: 5040

Answers (2)

Nicky
Nicky

Reputation: 66

To set up a proxy in a React project with different environments, you can modify the setupProxy.js file based on the environment. Here are the steps to set up a proxy with different environments:

const testHost = '11.22.23.13'; // test env
const devHost = '11.22.238.14'; // dev env
module.exports = function (app) {
  const isDev = process.env.CLIENT_ENV === 'development';
  const host = isDev ? devHost : testHost;
  console.log('launch env:', process.env.CLIENT_ENV, host);
  if (isDev) {
    app.use(
      '/api',
      createProxyMiddleware((pathname) => pathname.match('^/api'), {
        target: `http://${devHost}:8088`,
        changeOrigin: true,
        ws: true,
      }),
    );
    app.use(
      '/admin',
      createProxyMiddleware({
        target: `http://${devHost}:8088`,
        changeOrigin: true,
      }),
    );
  } else {
    app.use(
      '/api',
      createProxyMiddleware((pathname) => pathname.match('^/api'), {
        target: `http://${testHost}:8088`,
        changeOrigin: true,
        ws: true,
      }),
    );
    app.use(
      '/admin',
      createProxyMiddleware({
        target: `http://${testHost}:8088`,
        changeOrigin: true,
      }),
    );
  }

When you make API requests in your React app, they will be automatically proxied to the specified target URL based on the environment. Note that you need to set the CLIENT_ENV environment variable to development or production depending on the environment you are running the app in. You can set this variable in the command line or in your build tool configuration.

Upvotes: 0

Victor Trusov
Victor Trusov

Reputation: 1222

You don't need setupProxy.js and http-proxy-middleware.

Just add proxy to your current craco.config.js:

module.exports = {
...
    devServer: {
        proxy: {
            '/api': 'http://localhost:5000'
        }
    }
};

more info about devServer settings: https://webpack.js.org/configuration/dev-server/#devserverproxy

Upvotes: 9

Related Questions