1

I created an app with create-react-app and I'd like to configure some envs in JS files. Where should I put these files if I want them to be executed just after server initializing?

I've tried adding index.js to the root folder and creating server/config.js file, but that doesn't work.

2 Answers 2

2

if your purpose here is to check the application environment in the front end then no need set any .env file, you can just set global variables before running the script you need inside package.json file like that:

"scripts": {
   "start": "REACT_APP_ENVIRONMENT=LOCAL react-scripts start"
   "build": "REACT_APP_ENVIRONMENT=PRODUCTION react-scripts build"
}

so whenever you want to work in your local environment you will run npm start and this will set REACT_APP_ENVIRONMENT variable to LOCAL value.

and the same work when you want to run the application in production you run npm run build script and that will set the variable REACT_APP_ENVIRONMENT to PRODUCTION value

you can use the same variables in your js config file to get the current environment like that:

export const isDevelopment = REACT_APP_ENVIRONMENT === 'LOCAL'; export const isProduction = REACT_APP_ENVIRONMENT === 'PRODUCTION';

Sign up to request clarification or add additional context in comments.

1 Comment

It gives me 'REACT_APP_ENVIRONMENT' is not recognized as an internal or external command. I wonder why it works for others
2

Create a .env file in root directory of your app. Prefix every environment variable with the string REACT_APP_varNameHere. Find examples here: https://create-react-app.dev/docs/adding-custom-environment-variables/

1 Comment

Hm, to be honest, my real purpose is setting different HTTP_PROXY value for production and development environment. I wanted to do it by writing conditional statements in JS. Can I achieve that using .env file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.