2

I have been trying everything, but I can't succeed. I need to use .env file during development, with react-scripts start

I have been following this: https://create-react-app.dev/docs/adding-custom-environment-variables/ and I keep getting process is not defined.

I tried countless solutions found here, but no luck. I read that it injects the variables during build, so there is no way at all to use it during development?

Last thing I have tried is env-cmd

My script looks like this:

        "start": "env-cmd -f .env.development react-scripts start",

still it says process is undefined. Any help is appreciated thanks

3
  • can you attach one of your env variable key and value? Commented May 9, 2021 at 13:28
  • REACT_APP_ACCOUNT_SID=Axxxxxxxxxxxx I tried with var accountSid=process.env.REACT_APP_ACCOUNT_SID and var accountSid=process.env.ACCOUNT_SID no luck Commented May 9, 2021 at 13:34
  • appConfig.js:4 Uncaught ReferenceError: process is not defined at appConfig.js:4 Commented May 9, 2021 at 13:40

2 Answers 2

1

you have to create an .env file at the root of the project

don't forget to add REACT_APP at the beginning of the variable.

.env

REACT_APP_FOO=foo

App.js

export default function App() {
  return (
    <div className="App">
      <h1>{process.env.REACT_APP_FOO}</h1>
    </div>
  );
}

you can see this sandbox

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

2 Comments

ok it works now in index.js that is inside src.. I have another js that is in public/assets and it doesn't work there..
@jsabina look the sandbox i create a file in public/assets
0

try this

in .env file :

REACT_APP_DEVELOP_URL=https://test.example.com
REACT_APP_PROD_URL=https://api.example.com

in package.json file

  `"start-dev": "set REACT_APP_IP_MODE=development&& npm run dev",`
  `"start-prod": "set REACT_APP_IP_MODE=production&& npm run dev"`

and usage in project :

let baseURL;
const env = process.env;

switch (env.REACT_APP_IP_MODE) {
case "development":
  baseURL = env.REACT_APP_DEVELOP_URL;
  break;
case "production":
  baseURL = env.REACT_APP_PROD_URL;
  break;
default:
  baseURL = env.REACT_APP_DEVELOP_URL;
  break;
}

Comments

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.